artificialguybr commited on
Commit
6877edc
1 Parent(s): f5ba8ee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -52
app.py CHANGED
@@ -1,11 +1,9 @@
1
- import os
2
- import stat
3
- import uuid
4
- import subprocess
5
  import tempfile
6
- from zipfile import ZipFile
7
  import gradio as gr
8
- import spaces
 
 
9
  from googletrans import Translator
10
  from TTS.api import TTS
11
  from faster_whisper import WhisperModel
@@ -13,66 +11,61 @@ import soundfile as sf
13
  import numpy as np
14
  import cv2
15
  from huggingface_hub import HfApi
 
16
 
17
  HF_TOKEN = os.environ.get("HF_TOKEN")
18
  os.environ["COQUI_TOS_AGREED"] = "1"
19
  api = HfApi(token=HF_TOKEN)
20
  repo_id = "artificialguybr/video-dubbing"
21
 
22
- # Extract FFmpeg
23
- ZipFile("ffmpeg.zip").extractall()
24
- st = os.stat('ffmpeg')
25
- os.chmod('ffmpeg', st.st_mode | stat.S_IEXEC)
26
-
27
- # Whisper model initialization
28
  model_size = "small"
29
  model = WhisperModel(model_size, device="cpu", compute_type="int8")
30
 
31
  def check_for_faces(video_path):
32
  face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
33
  cap = cv2.VideoCapture(video_path)
34
-
35
  while True:
36
  ret, frame = cap.read()
37
  if not ret:
38
  break
39
-
40
  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
41
  faces = face_cascade.detectMultiScale(gray, 1.1, 4)
42
-
43
  if len(faces) > 0:
44
  return True
45
-
46
  return False
47
 
48
  @spaces.GPU
49
  def process_video(radio, video, target_language, has_closeup_face):
50
  if target_language is None:
51
  return gr.Error("Please select a Target Language for Dubbing.")
52
-
53
  run_uuid = uuid.uuid4().hex[:6]
54
  output_filename = f"{run_uuid}_resized_video.mp4"
55
 
56
- # Use FFmpeg via subprocess
57
- subprocess.run(['ffmpeg', '-i', video, '-vf', 'scale=-2:720', output_filename])
58
-
59
  video_path = output_filename
 
60
  if not os.path.exists(video_path):
61
  return f"Error: {video_path} does not exist."
62
-
63
  # Check video duration
64
- video_info = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', video_path], capture_output=True, text=True)
65
- video_duration = float(video_info.stdout)
66
-
67
  if video_duration > 60:
68
  os.remove(video_path)
69
  return gr.Error("Video duration exceeds 1 minute. Please upload a shorter video.")
70
-
71
- # Extract audio
72
- subprocess.run(['ffmpeg', '-i', video_path, '-acodec', 'pcm_s24le', '-ar', '48000', '-map', 'a', f"{run_uuid}_output_audio.wav"])
73
-
74
- # Audio processing
75
- subprocess.run(['ffmpeg', '-y', '-i', f"{run_uuid}_output_audio.wav", '-af', 'lowpass=3000,highpass=100', f"{run_uuid}_output_audio_final.wav"])
76
 
77
  print("Attempting to transcribe with Whisper...")
78
  try:
@@ -83,35 +76,34 @@ def process_video(radio, video, target_language, has_closeup_face):
83
  except RuntimeError as e:
84
  print(f"RuntimeError encountered: {str(e)}")
85
  if "CUDA failed with error device-side assert triggered" in str(e):
86
- gr.Warning("Error. Space needs to restart. Please retry in a minute")
87
  api.restart_space(repo_id=repo_id)
88
-
89
  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'}
90
  target_language_code = language_mapping[target_language]
91
  translator = Translator()
92
  translated_text = translator.translate(whisper_text, src=whisper_language, dest=target_language_code).text
93
  print(translated_text)
94
-
95
  tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2")
96
  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)
97
 
98
- has_face = check_for_faces(video_path) if not has_closeup_face else True
99
-
100
  if has_closeup_face:
101
  try:
102
- subprocess.run(['python', 'Wav2Lip/inference.py', '--checkpoint_path', 'Wav2Lip/checkpoints/wav2lip_gan.pth', '--face', video_path, '--audio', f'{run_uuid}_output_synth.wav', '--pads', '0', '15', '0', '0', '--resize_factor', '1', '--nosmooth', '--outfile', f'{run_uuid}_output_video.mp4'], check=True)
 
103
  except subprocess.CalledProcessError as e:
104
  if "Face not detected! Ensure the video contains a face in all the frames." in str(e.stderr):
105
  gr.Warning("Wav2lip didn't detect a face. Please try again with the option disabled.")
106
- subprocess.run(['ffmpeg', '-i', video_path, '-i', f'{run_uuid}_output_synth.wav', '-c:v', 'copy', '-c:a', 'aac', '-strict', 'experimental', '-map', '0:v:0', '-map', '1:a:0', f'{run_uuid}_output_video.mp4'])
107
- else:
108
- subprocess.run(['ffmpeg', '-i', video_path, '-i', f'{run_uuid}_output_synth.wav', '-c:v', 'copy', '-c:a', 'aac', '-strict', 'experimental', '-map', '0:v:0', '-map', '1:a:0', f'{run_uuid}_output_video.mp4'])
109
-
110
  if not os.path.exists(f"{run_uuid}_output_video.mp4"):
111
  raise FileNotFoundError(f"Error: {run_uuid}_output_video.mp4 was not generated.")
112
-
113
  output_video_path = f"{run_uuid}_output_video.mp4"
114
-
115
  # Cleanup
116
  files_to_delete = [
117
  f"{run_uuid}_resized_video.mp4",
@@ -124,15 +116,15 @@ def process_video(radio, video, target_language, has_closeup_face):
124
  os.remove(file)
125
  except FileNotFoundError:
126
  print(f"File {file} not found for deletion.")
127
-
128
  return output_video_path
129
 
130
  def swap(radio):
131
- if radio == "Upload":
132
  return gr.update(source="upload")
133
  else:
134
  return gr.update(source="webcam")
135
-
136
  video = gr.Video()
137
  radio = gr.Radio(["Upload", "Record"], value="Upload", show_label=False)
138
  iface = gr.Interface(
@@ -142,9 +134,9 @@ iface = gr.Interface(
142
  video,
143
  gr.Dropdown(choices=["English", "Spanish", "French", "German", "Italian", "Portuguese", "Polish", "Turkish", "Russian", "Dutch", "Czech", "Arabic", "Chinese (Simplified)"], label="Target Language for Dubbing", value="Spanish"),
144
  gr.Checkbox(
145
- label="Video has a close-up face. Use Wav2lip.",
146
- value=False,
147
- info="Say if video have close-up face. For Wav2lip. Will not work if checked wrongly.")
148
  ],
149
  outputs=gr.Video(),
150
  live=False,
@@ -158,14 +150,14 @@ with gr.Blocks() as demo:
158
  radio.change(swap, inputs=[radio], outputs=video)
159
  gr.Markdown("""
160
  **Note:**
161
- - Video limit is 1 minute. It will dubbling all people using just one voice.
162
  - Generation may take up to 5 minutes.
163
  - By using this demo you agree to the terms of the Coqui Public Model License at https://coqui.ai/cpml
164
- - The tool uses open-source models for all models. It's a alpha version.
165
  - Quality can be improved but would require more processing time per video. For scalability and hardware limitations, speed was chosen, not just quality.
166
  - If you need more than 1 minute, duplicate the Space and change the limit on app.py.
167
  - If you incorrectly mark the 'Video has a close-up face' checkbox, the dubbing may not work as expected.
168
  """)
169
 
170
- demo.queue()
171
- demo.launch()
 
1
+ import spaces
 
 
 
2
  import tempfile
 
3
  import gradio as gr
4
+ import subprocess
5
+ import os, stat
6
+ import uuid
7
  from googletrans import Translator
8
  from TTS.api import TTS
9
  from faster_whisper import WhisperModel
 
11
  import numpy as np
12
  import cv2
13
  from huggingface_hub import HfApi
14
+ import shlex
15
 
16
  HF_TOKEN = os.environ.get("HF_TOKEN")
17
  os.environ["COQUI_TOS_AGREED"] = "1"
18
  api = HfApi(token=HF_TOKEN)
19
  repo_id = "artificialguybr/video-dubbing"
20
 
21
+ # Whisper
 
 
 
 
 
22
  model_size = "small"
23
  model = WhisperModel(model_size, device="cpu", compute_type="int8")
24
 
25
  def check_for_faces(video_path):
26
  face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
27
  cap = cv2.VideoCapture(video_path)
28
+
29
  while True:
30
  ret, frame = cap.read()
31
  if not ret:
32
  break
33
+
34
  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
35
  faces = face_cascade.detectMultiScale(gray, 1.1, 4)
36
+
37
  if len(faces) > 0:
38
  return True
39
+
40
  return False
41
 
42
  @spaces.GPU
43
  def process_video(radio, video, target_language, has_closeup_face):
44
  if target_language is None:
45
  return gr.Error("Please select a Target Language for Dubbing.")
46
+
47
  run_uuid = uuid.uuid4().hex[:6]
48
  output_filename = f"{run_uuid}_resized_video.mp4"
49
 
50
+ # Use subprocess for ffmpeg operations
51
+ subprocess.run(["ffmpeg", "-i", video, "-vf", "scale=-2:720", output_filename])
52
+
53
  video_path = output_filename
54
+
55
  if not os.path.exists(video_path):
56
  return f"Error: {video_path} does not exist."
57
+
58
  # Check video duration
59
+ video_info = subprocess.check_output(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", video_path])
60
+ video_duration = float(video_info)
61
+
62
  if video_duration > 60:
63
  os.remove(video_path)
64
  return gr.Error("Video duration exceeds 1 minute. Please upload a shorter video.")
65
+
66
+ subprocess.run(["ffmpeg", "-i", video_path, "-acodec", "pcm_s24le", "-ar", "48000", "-map", "a", f"{run_uuid}_output_audio.wav"])
67
+
68
+ subprocess.run(["ffmpeg", "-y", "-i", f"{run_uuid}_output_audio.wav", "-af", "lowpass=3000,highpass=100", f"{run_uuid}_output_audio_final.wav"])
 
 
69
 
70
  print("Attempting to transcribe with Whisper...")
71
  try:
 
76
  except RuntimeError as e:
77
  print(f"RuntimeError encountered: {str(e)}")
78
  if "CUDA failed with error device-side assert triggered" in str(e):
79
+ gr.Warning("Error. Space need to restart. Please retry in a minute")
80
  api.restart_space(repo_id=repo_id)
81
+
82
  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'}
83
  target_language_code = language_mapping[target_language]
84
  translator = Translator()
85
  translated_text = translator.translate(whisper_text, src=whisper_language, dest=target_language_code).text
86
  print(translated_text)
87
+
88
  tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2")
89
  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)
90
 
 
 
91
  if has_closeup_face:
92
  try:
93
+ 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 0 15 0 0 --resize_factor 1 --nosmooth --outfile '{run_uuid}_output_video.mp4'"
94
+ subprocess.run(cmd, shell=True, check=True)
95
  except subprocess.CalledProcessError as e:
96
  if "Face not detected! Ensure the video contains a face in all the frames." in str(e.stderr):
97
  gr.Warning("Wav2lip didn't detect a face. Please try again with the option disabled.")
98
+ subprocess.run(["ffmpeg", "-i", video_path, "-i", f"{run_uuid}_output_synth.wav", "-c:v", "copy", "-c:a", "aac", "-strict", "experimental", "-map", "0:v:0", "-map", "1:a:0", f"{run_uuid}_output_video.mp4"])
99
+ else:
100
+ subprocess.run(["ffmpeg", "-i", video_path, "-i", f"{run_uuid}_output_synth.wav", "-c:v", "copy", "-c:a", "aac", "-strict", "experimental", "-map", "0:v:0", "-map", "1:a:0", f"{run_uuid}_output_video.mp4"])
101
+
102
  if not os.path.exists(f"{run_uuid}_output_video.mp4"):
103
  raise FileNotFoundError(f"Error: {run_uuid}_output_video.mp4 was not generated.")
104
+
105
  output_video_path = f"{run_uuid}_output_video.mp4"
106
+
107
  # Cleanup
108
  files_to_delete = [
109
  f"{run_uuid}_resized_video.mp4",
 
116
  os.remove(file)
117
  except FileNotFoundError:
118
  print(f"File {file} not found for deletion.")
119
+
120
  return output_video_path
121
 
122
  def swap(radio):
123
+ if(radio == "Upload"):
124
  return gr.update(source="upload")
125
  else:
126
  return gr.update(source="webcam")
127
+
128
  video = gr.Video()
129
  radio = gr.Radio(["Upload", "Record"], value="Upload", show_label=False)
130
  iface = gr.Interface(
 
134
  video,
135
  gr.Dropdown(choices=["English", "Spanish", "French", "German", "Italian", "Portuguese", "Polish", "Turkish", "Russian", "Dutch", "Czech", "Arabic", "Chinese (Simplified)"], label="Target Language for Dubbing", value="Spanish"),
136
  gr.Checkbox(
137
+ label="Video has a close-up face. Use Wav2lip.",
138
+ value=False,
139
+ info="Say if video have close-up face. For Wav2lip. Will not work if checked wrongly.")
140
  ],
141
  outputs=gr.Video(),
142
  live=False,
 
150
  radio.change(swap, inputs=[radio], outputs=video)
151
  gr.Markdown("""
152
  **Note:**
153
+ - Video limit is 1 minute. It will dubbing all people using just one voice.
154
  - Generation may take up to 5 minutes.
155
  - By using this demo you agree to the terms of the Coqui Public Model License at https://coqui.ai/cpml
156
+ - The tool uses open-source models for all models. It's an alpha version.
157
  - Quality can be improved but would require more processing time per video. For scalability and hardware limitations, speed was chosen, not just quality.
158
  - If you need more than 1 minute, duplicate the Space and change the limit on app.py.
159
  - If you incorrectly mark the 'Video has a close-up face' checkbox, the dubbing may not work as expected.
160
  """)
161
 
162
+ demo.queue(concurrency_count=1, max_size=15)
163
+ demo.launch()