dramsden/profanity-sanitizer
0
1 2import gradio as gr3from faster_whisper import WhisperModel4import ffmpeg5from pydub import AudioSegment6from better_profanity import profanity7import os8import tempfile9 10# Load Whisper model11model = WhisperModel("base")12 13# Load default + extra profanity words14profanity.load_censor_words(extra_censor_words=["fucking", "shit", "asshole", "bitch", "damn", "motherfucker"])15 16def mute_profanity(audio_path, segments):17 sound = AudioSegment.from_file(audio_path)18 19 for segment in segments:20 text = segment.text.lower()21 if profanity.contains_profanity(text):22 start_ms = int(segment.start * 1000)23 end_ms = int(segment.end * 1000)24 silence = AudioSegment.silent(duration=(end_ms - start_ms))25 sound = sound[:start_ms] + silence + sound[end_ms:]26 27 cleaned_audio_path = tempfile.mktemp(suffix=".wav")28 sound.export(cleaned_audio_path, format="wav")29 return cleaned_audio_path30 31def process_video(video_file):32 video_path = video_file33 audio_path = "audio.wav"34 output_path = "sanitized_video.mp4"35 36 # Extract audio from video37 ffmpeg.input(video_path).output(audio_path, ac=1, ar=16000).overwrite_output().run(quiet=True)38 39 # Transcribe and convert generator to list40 segments_gen, _ = model.transcribe(audio_path, beam_size=5)41 segments = list(segments_gen)42 43 # Sanitize profanity44 cleaned_audio_path = mute_profanity(audio_path, segments)45 46 # Replace original audio with cleaned version47 (48 ffmpeg49 .input(video_path)50 .output(output_path,51 i=cleaned_audio_path,52 c="copy",53 c_a="aac",54 map="0:v:0",55 map_1="1:a:0",56 shortest=None)57 .overwrite_output()58 .run(quiet=True)59 )60 61 return output_path62 63iface = gr.Interface(64 fn=process_video,65 inputs=gr.Video(label="Upload MP4 video"),66 outputs=gr.Video(label="Sanitized video"),67 title="Profanity Filter Video Sanitizer",68 description="Upload an MP4 to automatically mute profanity in the audio."69)70 71if __name__ == "__main__":72 iface.launch()73 74 