Spaces:
Running
on
Zero
Running
on
Zero
artificialguybr
commited on
Commit
•
af6eab9
1
Parent(s):
f704b6f
Update app.py
Browse files
app.py
CHANGED
@@ -6,22 +6,40 @@ import os, stat
|
|
6 |
import uuid
|
7 |
from googletrans import Translator
|
8 |
from TTS.api import TTS
|
|
|
9 |
from faster_whisper import WhisperModel
|
|
|
10 |
import soundfile as sf
|
|
|
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 |
-
#
|
|
|
|
|
|
|
|
|
|
|
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)
|
@@ -39,6 +57,17 @@ def check_for_faces(video_path):
|
|
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:
|
@@ -46,37 +75,33 @@ def process_video(radio, video, target_language, has_closeup_face):
|
|
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 |
-
|
59 |
-
|
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 |
-
|
67 |
|
68 |
-
|
|
|
69 |
|
70 |
print("Attempting to transcribe with Whisper...")
|
71 |
try:
|
72 |
-
|
73 |
-
whisper_text = " ".join(segment.text for segment in segments)
|
74 |
-
whisper_language = info.language
|
75 |
print(f"Transcription successful: {whisper_text}")
|
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
|
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'}
|
@@ -85,19 +110,20 @@ def process_video(radio, video, target_language, has_closeup_face):
|
|
85 |
translated_text = translator.translate(whisper_text, src=whisper_language, dest=target_language_code).text
|
86 |
print(translated_text)
|
87 |
|
88 |
-
|
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 '
|
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 |
-
|
|
|
99 |
else:
|
100 |
-
|
|
|
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.")
|
@@ -109,7 +135,7 @@ def process_video(radio, video, target_language, has_closeup_face):
|
|
109 |
f"{run_uuid}_resized_video.mp4",
|
110 |
f"{run_uuid}_output_audio.wav",
|
111 |
f"{run_uuid}_output_audio_final.wav",
|
112 |
-
|
113 |
]
|
114 |
for file in files_to_delete:
|
115 |
try:
|
@@ -120,11 +146,9 @@ def process_video(radio, video, target_language, has_closeup_face):
|
|
120 |
return output_video_path
|
121 |
|
122 |
def swap(radio):
|
123 |
-
if
|
124 |
-
|
125 |
-
|
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(
|
@@ -133,10 +157,7 @@ iface = gr.Interface(
|
|
133 |
radio,
|
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,
|
@@ -159,5 +180,5 @@ with gr.Blocks() as demo:
|
|
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()
|
163 |
demo.launch()
|
|
|
6 |
import uuid
|
7 |
from googletrans import Translator
|
8 |
from TTS.api import TTS
|
9 |
+
import ffmpeg
|
10 |
from faster_whisper import WhisperModel
|
11 |
+
from scipy.signal import wiener
|
12 |
import soundfile as sf
|
13 |
+
from pydub import AudioSegment
|
14 |
import numpy as np
|
15 |
+
import librosa
|
16 |
+
from zipfile import ZipFile
|
17 |
+
import shlex
|
18 |
import cv2
|
19 |
+
import torch
|
20 |
+
import torchvision
|
21 |
+
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 |
|
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:
|
|
|
75 |
|
76 |
run_uuid = uuid.uuid4().hex[:6]
|
77 |
output_filename = f"{run_uuid}_resized_video.mp4"
|
78 |
+
ffmpeg.input(video).output(output_filename, vf='scale=-2:720').run()
|
|
|
|
|
79 |
|
80 |
video_path = output_filename
|
81 |
|
82 |
if not os.path.exists(video_path):
|
83 |
return f"Error: {video_path} does not exist."
|
84 |
|
85 |
+
video_info = ffmpeg.probe(video_path)
|
86 |
+
video_duration = float(video_info['streams'][0]['duration'])
|
|
|
87 |
|
88 |
if video_duration > 60:
|
89 |
os.remove(video_path)
|
90 |
return gr.Error("Video duration exceeds 1 minute. Please upload a shorter video.")
|
91 |
|
92 |
+
ffmpeg.input(video_path).output(f"{run_uuid}_output_audio.wav", acodec='pcm_s24le', ar=48000, map='a').run()
|
93 |
|
94 |
+
shell_command = f"ffmpeg -y -i {run_uuid}_output_audio.wav -af lowpass=3000,highpass=100 {run_uuid}_output_audio_final.wav".split(" ")
|
95 |
+
subprocess.run([item for item in shell_command], capture_output=False, text=True, check=True)
|
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 |
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"):
|
129 |
raise FileNotFoundError(f"Error: {run_uuid}_output_video.mp4 was not generated.")
|
|
|
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:
|
|
|
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 |
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,
|
|
|
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()
|