artificialguybr commited on
Commit
b361117
1 Parent(s): 7f52f79

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -35
app.py CHANGED
@@ -22,24 +22,18 @@ from tqdm import tqdm
22
  from numba import jit
23
  from huggingface_hub import HfApi
24
 
25
- # Environment setup
26
  HF_TOKEN = os.environ.get("HF_TOKEN")
27
  os.environ["COQUI_TOS_AGREED"] = "1"
28
  api = HfApi(token=HF_TOKEN)
29
  repo_id = "artificialguybr/video-dubbing"
30
-
31
- # Extract ffmpeg
32
  ZipFile("ffmpeg.zip").extractall()
33
  st = os.stat('ffmpeg')
34
  os.chmod('ffmpeg', st.st_mode | stat.S_IEXEC)
35
 
36
- # Initialize Whisper model
37
  model_size = "small"
38
  model = WhisperModel(model_size, device="cpu", compute_type="int8")
39
 
40
- # Initialize TTS model
41
- tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2")
42
-
43
  def check_for_faces(video_path):
44
  face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
45
  cap = cv2.VideoCapture(video_path)
@@ -57,17 +51,6 @@ def check_for_faces(video_path):
57
 
58
  return False
59
 
60
- @spaces.GPU
61
- def transcribe_audio(audio_path):
62
- segments, info = model.transcribe(audio_path, beam_size=5)
63
- whisper_text = " ".join(segment.text for segment in segments)
64
- whisper_language = info.language
65
- return whisper_text, whisper_language
66
-
67
- @spaces.GPU
68
- def generate_tts(text, speaker_wav, language_code):
69
- tts.tts_to_file(text, speaker_wav=speaker_wav, file_path="output_synth.wav", language=language_code)
70
-
71
  @spaces.GPU
72
  def process_video(radio, video, target_language, has_closeup_face):
73
  if target_language is None:
@@ -96,12 +79,14 @@ def process_video(radio, video, target_language, has_closeup_face):
96
 
97
  print("Attempting to transcribe with Whisper...")
98
  try:
99
- whisper_text, whisper_language = transcribe_audio(f"{run_uuid}_output_audio_final.wav")
 
 
100
  print(f"Transcription successful: {whisper_text}")
101
  except RuntimeError as e:
102
  print(f"RuntimeError encountered: {str(e)}")
103
  if "CUDA failed with error device-side assert triggered" in str(e):
104
- gr.Warning("Error. Space needs to restart. Please retry in a minute")
105
  api.restart_space(repo_id=repo_id)
106
 
107
  language_mapping = {'English': 'en', 'Spanish': 'es', 'French': 'fr', 'German': 'de', 'Italian': 'it', 'Portuguese': 'pt', 'Polish': 'pl', 'Turkish': 'tr', 'Russian': 'ru', 'Dutch': 'nl', 'Czech': 'cs', 'Arabic': 'ar', 'Chinese (Simplified)': 'zh-cn'}
@@ -110,19 +95,34 @@ def process_video(radio, video, target_language, has_closeup_face):
110
  translated_text = translator.translate(whisper_text, src=whisper_language, dest=target_language_code).text
111
  print(translated_text)
112
 
113
- generate_tts(translated_text, f"{run_uuid}_output_audio_final.wav", target_language_code)
 
 
114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  if has_closeup_face:
116
  try:
117
- cmd = f"python Wav2Lip/inference.py --checkpoint_path 'Wav2Lip/checkpoints/wav2lip_gan.pth' --face {shlex.quote(video_path)} --audio 'output_synth.wav' --pads 0 15 0 0 --resize_factor 1 --nosmooth --outfile '{run_uuid}_output_video.mp4'"
118
  subprocess.run(cmd, shell=True, check=True)
119
  except subprocess.CalledProcessError as e:
120
  if "Face not detected! Ensure the video contains a face in all the frames." in str(e.stderr):
121
  gr.Warning("Wav2lip didn't detect a face. Please try again with the option disabled.")
122
- cmd = f"ffmpeg -i {video_path} -i output_synth.wav -c:v copy -c:a aac -strict experimental -map 0:v:0 -map 1:a:0 {run_uuid}_output_video.mp4"
123
  subprocess.run(cmd, shell=True)
124
  else:
125
- cmd = f"ffmpeg -i {video_path} -i output_synth.wav -c:v copy -c:a aac -strict experimental -map 0:v:0 -map 1:a:0 {run_uuid}_output_video.mp4"
126
  subprocess.run(cmd, shell=True)
127
 
128
  if not os.path.exists(f"{run_uuid}_output_video.mp4"):
@@ -130,12 +130,11 @@ def process_video(radio, video, target_language, has_closeup_face):
130
 
131
  output_video_path = f"{run_uuid}_output_video.mp4"
132
 
133
- # Cleanup
134
  files_to_delete = [
135
  f"{run_uuid}_resized_video.mp4",
136
  f"{run_uuid}_output_audio.wav",
137
  f"{run_uuid}_output_audio_final.wav",
138
- "output_synth.wav"
139
  ]
140
  for file in files_to_delete:
141
  try:
@@ -144,11 +143,13 @@ def process_video(radio, video, target_language, has_closeup_face):
144
  print(f"File {file} not found for deletion.")
145
 
146
  return output_video_path
147
-
148
  def swap(radio):
149
- return gr.update(source="upload" if radio == "Upload" else "webcam")
150
-
151
- # Gradio interface setup
 
 
152
  video = gr.Video()
153
  radio = gr.Radio(["Upload", "Record"], value="Upload", show_label=False)
154
  iface = gr.Interface(
@@ -157,7 +158,10 @@ iface = gr.Interface(
157
  radio,
158
  video,
159
  gr.Dropdown(choices=["English", "Spanish", "French", "German", "Italian", "Portuguese", "Polish", "Turkish", "Russian", "Dutch", "Czech", "Arabic", "Chinese (Simplified)"], label="Target Language for Dubbing", value="Spanish"),
160
- gr.Checkbox(label="Video has a close-up face. Use Wav2lip.", value=False, info="Say if video have close-up face. For Wav2lip. Will not work if checked wrongly.")
 
 
 
161
  ],
162
  outputs=gr.Video(),
163
  live=False,
@@ -165,20 +169,18 @@ iface = gr.Interface(
165
  description="""This tool was developed by [@artificialguybr](https://twitter.com/artificialguybr) using entirely open-source tools. Special thanks to Hugging Face for the GPU support. Thanks [@yeswondwer](https://twitter.com/@yeswondwerr) for original code. Test the [Video Transcription and Translate](https://huggingface.co/spaces/artificialguybr/VIDEO-TRANSLATION-TRANSCRIPTION) space!""",
166
  allow_flagging=False
167
  )
168
-
169
  with gr.Blocks() as demo:
170
  iface.render()
171
  radio.change(swap, inputs=[radio], outputs=video)
172
  gr.Markdown("""
173
  **Note:**
174
- - Video limit is 1 minute. It will dubbing all people using just one voice.
175
  - Generation may take up to 5 minutes.
176
  - By using this demo you agree to the terms of the Coqui Public Model License at https://coqui.ai/cpml
177
- - The tool uses open-source models for all models. It's an alpha version.
178
  - Quality can be improved but would require more processing time per video. For scalability and hardware limitations, speed was chosen, not just quality.
179
  - If you need more than 1 minute, duplicate the Space and change the limit on app.py.
180
  - If you incorrectly mark the 'Video has a close-up face' checkbox, the dubbing may not work as expected.
181
  """)
182
-
183
  demo.queue(concurrency_count=1, max_size=15)
184
  demo.launch()
 
22
  from numba import jit
23
  from huggingface_hub import HfApi
24
 
 
25
  HF_TOKEN = os.environ.get("HF_TOKEN")
26
  os.environ["COQUI_TOS_AGREED"] = "1"
27
  api = HfApi(token=HF_TOKEN)
28
  repo_id = "artificialguybr/video-dubbing"
 
 
29
  ZipFile("ffmpeg.zip").extractall()
30
  st = os.stat('ffmpeg')
31
  os.chmod('ffmpeg', st.st_mode | stat.S_IEXEC)
32
 
33
+ #Whisper
34
  model_size = "small"
35
  model = WhisperModel(model_size, device="cpu", compute_type="int8")
36
 
 
 
 
37
  def check_for_faces(video_path):
38
  face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
39
  cap = cv2.VideoCapture(video_path)
 
51
 
52
  return False
53
 
 
 
 
 
 
 
 
 
 
 
 
54
  @spaces.GPU
55
  def process_video(radio, video, target_language, has_closeup_face):
56
  if target_language is None:
 
79
 
80
  print("Attempting to transcribe with Whisper...")
81
  try:
82
+ segments, info = model.transcribe(f"{run_uuid}_output_audio_final.wav", beam_size=5)
83
+ whisper_text = " ".join(segment.text for segment in segments)
84
+ whisper_language = info.language
85
  print(f"Transcription successful: {whisper_text}")
86
  except RuntimeError as e:
87
  print(f"RuntimeError encountered: {str(e)}")
88
  if "CUDA failed with error device-side assert triggered" in str(e):
89
+ gr.Warning("Error. Space need to restart. Please retry in a minute")
90
  api.restart_space(repo_id=repo_id)
91
 
92
  language_mapping = {'English': 'en', 'Spanish': 'es', 'French': 'fr', 'German': 'de', 'Italian': 'it', 'Portuguese': 'pt', 'Polish': 'pl', 'Turkish': 'tr', 'Russian': 'ru', 'Dutch': 'nl', 'Czech': 'cs', 'Arabic': 'ar', 'Chinese (Simplified)': 'zh-cn'}
 
95
  translated_text = translator.translate(whisper_text, src=whisper_language, dest=target_language_code).text
96
  print(translated_text)
97
 
98
+ tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2")
99
+ tts.to('cuda')
100
+ tts.tts_to_file(translated_text, speaker_wav=f"{run_uuid}_output_audio_final.wav", file_path=f"{run_uuid}_output_synth.wav", language=target_language_code)
101
 
102
+ pad_top = 0
103
+ pad_bottom = 15
104
+ pad_left = 0
105
+ pad_right = 0
106
+ rescaleFactor = 1
107
+
108
+ video_path_fix = video_path
109
+
110
+ if has_closeup_face:
111
+ has_face = True
112
+ else:
113
+ has_face = check_for_faces(video_path)
114
+
115
  if has_closeup_face:
116
  try:
117
+ cmd = f"python Wav2Lip/inference.py --checkpoint_path 'Wav2Lip/checkpoints/wav2lip_gan.pth' --face {shlex.quote(video_path)} --audio '{run_uuid}_output_synth.wav' --pads {pad_top} {pad_bottom} {pad_left} {pad_right} --resize_factor {rescaleFactor} --nosmooth --outfile '{run_uuid}_output_video.mp4'"
118
  subprocess.run(cmd, shell=True, check=True)
119
  except subprocess.CalledProcessError as e:
120
  if "Face not detected! Ensure the video contains a face in all the frames." in str(e.stderr):
121
  gr.Warning("Wav2lip didn't detect a face. Please try again with the option disabled.")
122
+ cmd = f"ffmpeg -i {video_path} -i {run_uuid}_output_synth.wav -c:v copy -c:a aac -strict experimental -map 0:v:0 -map 1:a:0 {run_uuid}_output_video.mp4"
123
  subprocess.run(cmd, shell=True)
124
  else:
125
+ cmd = f"ffmpeg -i {video_path} -i {run_uuid}_output_synth.wav -c:v copy -c:a aac -strict experimental -map 0:v:0 -map 1:a:0 {run_uuid}_output_video.mp4"
126
  subprocess.run(cmd, shell=True)
127
 
128
  if not os.path.exists(f"{run_uuid}_output_video.mp4"):
 
130
 
131
  output_video_path = f"{run_uuid}_output_video.mp4"
132
 
 
133
  files_to_delete = [
134
  f"{run_uuid}_resized_video.mp4",
135
  f"{run_uuid}_output_audio.wav",
136
  f"{run_uuid}_output_audio_final.wav",
137
+ f"{run_uuid}_output_synth.wav"
138
  ]
139
  for file in files_to_delete:
140
  try:
 
143
  print(f"File {file} not found for deletion.")
144
 
145
  return output_video_path
146
+
147
  def swap(radio):
148
+ if(radio == "Upload"):
149
+ return gr.update(source="upload")
150
+ else:
151
+ return gr.update(source="webcam")
152
+
153
  video = gr.Video()
154
  radio = gr.Radio(["Upload", "Record"], value="Upload", show_label=False)
155
  iface = gr.Interface(
 
158
  radio,
159
  video,
160
  gr.Dropdown(choices=["English", "Spanish", "French", "German", "Italian", "Portuguese", "Polish", "Turkish", "Russian", "Dutch", "Czech", "Arabic", "Chinese (Simplified)"], label="Target Language for Dubbing", value="Spanish"),
161
+ gr.Checkbox(
162
+ label="Video has a close-up face. Use Wav2lip.",
163
+ value=False,
164
+ info="Say if video have close-up face. For Wav2lip. Will not work if checked wrongly.")
165
  ],
166
  outputs=gr.Video(),
167
  live=False,
 
169
  description="""This tool was developed by [@artificialguybr](https://twitter.com/artificialguybr) using entirely open-source tools. Special thanks to Hugging Face for the GPU support. Thanks [@yeswondwer](https://twitter.com/@yeswondwerr) for original code. Test the [Video Transcription and Translate](https://huggingface.co/spaces/artificialguybr/VIDEO-TRANSLATION-TRANSCRIPTION) space!""",
170
  allow_flagging=False
171
  )
 
172
  with gr.Blocks() as demo:
173
  iface.render()
174
  radio.change(swap, inputs=[radio], outputs=video)
175
  gr.Markdown("""
176
  **Note:**
177
+ - Video limit is 1 minute. It will dubbling all people using just one voice.
178
  - Generation may take up to 5 minutes.
179
  - By using this demo you agree to the terms of the Coqui Public Model License at https://coqui.ai/cpml
180
+ - The tool uses open-source models for all models. It's a alpha version.
181
  - Quality can be improved but would require more processing time per video. For scalability and hardware limitations, speed was chosen, not just quality.
182
  - If you need more than 1 minute, duplicate the Space and change the limit on app.py.
183
  - If you incorrectly mark the 'Video has a close-up face' checkbox, the dubbing may not work as expected.
184
  """)
 
185
  demo.queue(concurrency_count=1, max_size=15)
186
  demo.launch()