Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
@@ -8,13 +8,14 @@ from gtts import gTTS
|
|
8 |
import tempfile
|
9 |
from pydub.generators import Sine
|
10 |
from pydub import AudioSegment
|
|
|
11 |
import cv2
|
12 |
import imageio
|
|
|
13 |
import ffmpeg
|
14 |
from io import BytesIO
|
15 |
import requests
|
16 |
import sys
|
17 |
-
import mediapipe as mp
|
18 |
|
19 |
python_path = sys.executable
|
20 |
|
@@ -23,35 +24,56 @@ from fairseq.models.text_to_speech.hub_interface import TTSHubInterface
|
|
23 |
|
24 |
block = gr.Blocks()
|
25 |
|
26 |
-
def
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
img = cv2.imread(src_img)
|
|
|
32 |
h, width, _ = img.shape
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
img = img[y:y + h, x:x + w]
|
49 |
-
img = cv2.resize(img, (256, 256))
|
50 |
-
cv2.imwrite(save_img, img)
|
51 |
-
else:
|
52 |
-
# If no face is detected, resize the original image
|
53 |
-
img = cv2.resize(img, (256, 256))
|
54 |
-
cv2.imwrite(save_img, img)
|
55 |
return save_img
|
56 |
|
57 |
def pad_image(image):
|
@@ -84,108 +106,153 @@ def calculate(image_in, audio_in):
|
|
84 |
image = Image.open(BytesIO(response.content))
|
85 |
print("****"*100)
|
86 |
image = pad_image(image)
|
|
|
87 |
image.save("image.png")
|
88 |
|
89 |
pocketsphinx_run = subprocess.run(['pocketsphinx', '-phone_align', 'yes', 'single', '/content/audio.wav'], check=True, capture_output=True)
|
90 |
jq_run = subprocess.run(['jq', '[.w[]|{word: (.t | ascii_upcase | sub("<S>"; "sil") | sub("<SIL>"; "sil") | sub("\\\(2\\\)"; "") | sub("\\\(3\\\)"; "") | sub("\\\(4\\\)"; "") | sub("\\\[SPEECH\\\]"; "SIL") | sub("\\\[NOISE\\\]"; "SIL")), phones: [.w[]|{ph: .t | sub("\\\+SPN\\\+"; "SIL") | sub("\\\+NSN\\\+"; "SIL"), bg: (.b*100)|floor, ed: (.b*100+.d*100)|floor}]}]'], input=pocketsphinx_run.stdout, capture_output=True)
|
91 |
with open("test.json", "w") as f:
|
92 |
f.write(jq_run.stdout.decode('utf-8').strip())
|
|
|
|
|
93 |
os.system(f"cd /content/one-shot-talking-face && {python_path} -B test_script.py --img_path /content/image.png --audio_path /content/audio.wav --phoneme_path /content/test.json --save_dir /content/train")
|
94 |
return "/content/train/image_audio.mp4"
|
95 |
|
96 |
def merge_frames():
|
97 |
-
|
|
|
|
|
98 |
|
99 |
-
|
100 |
-
|
101 |
|
102 |
-
|
103 |
-
|
|
|
104 |
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
|
|
|
|
114 |
|
115 |
def audio_video():
|
116 |
-
input_video = ffmpeg.input('/content/video_output.mp4')
|
117 |
-
input_audio = ffmpeg.input('/content/audio.wav')
|
118 |
-
os.system(f"rm -rf /content/final_output.mp4")
|
119 |
-
ffmpeg.concat(input_video, input_audio, v=1, a=1).output('/content/final_output.mp4').run()
|
120 |
-
return "/content/final_output.mp4"
|
121 |
|
122 |
-
|
123 |
-
crop_img = crop_src_image(image_in)
|
124 |
|
125 |
-
|
126 |
-
|
|
|
127 |
|
128 |
-
|
129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
130 |
|
131 |
-
|
132 |
-
|
|
|
133 |
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
142 |
if gender == "Female":
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
elif gender == 'Male':
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
sample["net_input"]["src_lengths"] = sample["net_input"]["src_lengths"]
|
164 |
-
sample["speaker"] = sample["speaker"]
|
165 |
-
|
166 |
-
wav, rate = TTSHubInterface.get_prediction(task, model, generator, sample)
|
167 |
-
os.system(f"rm -rf /content/audio_before.wav")
|
168 |
-
soundfile.write("/content/audio_before.wav", wav.cpu().clone().numpy(), rate)
|
169 |
-
os.system(f"rm -rf /content/audio.wav")
|
170 |
-
cmd = 'ffmpeg -i /content/audio_before.wav -filter:a "atempo=0.7" -vn /content/audio.wav'
|
171 |
-
os.system(cmd)
|
172 |
-
audio_in = "/content/audio.wav"
|
173 |
-
return one_shot_talking(image_in, audio_in)
|
174 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
175 |
def run():
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
189 |
|
190 |
if __name__ == "__main__":
|
191 |
run()
|
|
|
8 |
import tempfile
|
9 |
from pydub.generators import Sine
|
10 |
from pydub import AudioSegment
|
11 |
+
import dlib
|
12 |
import cv2
|
13 |
import imageio
|
14 |
+
import os
|
15 |
import ffmpeg
|
16 |
from io import BytesIO
|
17 |
import requests
|
18 |
import sys
|
|
|
19 |
|
20 |
python_path = sys.executable
|
21 |
|
|
|
24 |
|
25 |
block = gr.Blocks()
|
26 |
|
27 |
+
def compute_aspect_preserved_bbox(bbox, increase_area, h, w):
|
28 |
+
left, top, right, bot = bbox
|
29 |
+
width = right - left
|
30 |
+
height = bot - top
|
31 |
+
|
32 |
+
width_increase = max(increase_area, ((1 + 2 * increase_area) * height - width) / (2 * width))
|
33 |
+
height_increase = max(increase_area, ((1 + 2 * increase_area) * width - height) / (2 * height))
|
34 |
+
|
35 |
+
left_t = int(left - width_increase * width)
|
36 |
+
top_t = int(top - height_increase * height)
|
37 |
+
right_t = int(right + width_increase * width)
|
38 |
+
bot_t = int(bot + height_increase * height)
|
39 |
+
|
40 |
+
left_oob = -min(0, left_t)
|
41 |
+
right_oob = right - min(right_t, w)
|
42 |
+
top_oob = -min(0, top_t)
|
43 |
+
bot_oob = bot - min(bot_t, h)
|
44 |
+
|
45 |
+
if max(left_oob, right_oob, top_oob, bot_oob) > 0:
|
46 |
+
max_w = max(left_oob, right_oob)
|
47 |
+
max_h = max(top_oob, bot_oob)
|
48 |
+
if max_w > max_h:
|
49 |
+
return left_t + max_w, top_t + max_w, right_t - max_w, bot_t - max_w
|
50 |
+
else:
|
51 |
+
return left_t + max_h, top_t + max_h, right_t - max_h, bot_t - max_h
|
52 |
+
|
53 |
+
else:
|
54 |
+
return (left_t, top_t, right_t, bot_t)
|
55 |
+
|
56 |
+
def crop_src_image(src_img, detector=None):
|
57 |
+
if detector is None:
|
58 |
+
detector = dlib.get_frontal_face_detector()
|
59 |
+
save_img='/content/image_pre.png'
|
60 |
img = cv2.imread(src_img)
|
61 |
+
faces = detector(img, 0)
|
62 |
h, width, _ = img.shape
|
63 |
+
if len(faces) > 0:
|
64 |
+
bbox = [faces[0].left(), faces[0].top(),faces[0].right(), faces[0].bottom()]
|
65 |
+
l = bbox[3]-bbox[1]
|
66 |
+
bbox[1]= bbox[1]-l*0.1
|
67 |
+
bbox[3]= bbox[3]-l*0.1
|
68 |
+
bbox[1] = max(0,bbox[1])
|
69 |
+
bbox[3] = min(h,bbox[3])
|
70 |
+
bbox = compute_aspect_preserved_bbox(tuple(bbox), 0.5, img.shape[0], img.shape[1])
|
71 |
+
img = img[bbox[1] :bbox[3] , bbox[0]:bbox[2]]
|
72 |
+
img = cv2.resize(img, (256, 256))
|
73 |
+
cv2.imwrite(save_img,img)
|
74 |
+
else:
|
75 |
+
img = cv2.resize(img,(256,256))
|
76 |
+
cv2.imwrite(save_img, img)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
return save_img
|
78 |
|
79 |
def pad_image(image):
|
|
|
106 |
image = Image.open(BytesIO(response.content))
|
107 |
print("****"*100)
|
108 |
image = pad_image(image)
|
109 |
+
# os.system(f"rm -rf /content/image.png")
|
110 |
image.save("image.png")
|
111 |
|
112 |
pocketsphinx_run = subprocess.run(['pocketsphinx', '-phone_align', 'yes', 'single', '/content/audio.wav'], check=True, capture_output=True)
|
113 |
jq_run = subprocess.run(['jq', '[.w[]|{word: (.t | ascii_upcase | sub("<S>"; "sil") | sub("<SIL>"; "sil") | sub("\\\(2\\\)"; "") | sub("\\\(3\\\)"; "") | sub("\\\(4\\\)"; "") | sub("\\\[SPEECH\\\]"; "SIL") | sub("\\\[NOISE\\\]"; "SIL")), phones: [.w[]|{ph: .t | sub("\\\+SPN\\\+"; "SIL") | sub("\\\+NSN\\\+"; "SIL"), bg: (.b*100)|floor, ed: (.b*100+.d*100)|floor}]}]'], input=pocketsphinx_run.stdout, capture_output=True)
|
114 |
with open("test.json", "w") as f:
|
115 |
f.write(jq_run.stdout.decode('utf-8').strip())
|
116 |
+
# device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
117 |
+
# os.system(f"rm -rf /content/image_audio.mp4")
|
118 |
os.system(f"cd /content/one-shot-talking-face && {python_path} -B test_script.py --img_path /content/image.png --audio_path /content/audio.wav --phoneme_path /content/test.json --save_dir /content/train")
|
119 |
return "/content/train/image_audio.mp4"
|
120 |
|
121 |
def merge_frames():
|
122 |
+
|
123 |
+
|
124 |
+
path = '/content/video_results/restored_imgs'
|
125 |
|
126 |
+
if not os.path.exists(path):
|
127 |
+
os.makedirs(path)
|
128 |
|
129 |
+
image_folder = os.fsencode(path)
|
130 |
+
print(image_folder)
|
131 |
+
filenames = []
|
132 |
|
133 |
+
for file in os.listdir(image_folder):
|
134 |
+
filename = os.fsdecode(file)
|
135 |
+
if filename.endswith( ('.jpg', '.png', '.gif') ):
|
136 |
+
filenames.append(filename)
|
137 |
|
138 |
+
filenames.sort() # this iteration technique has no built in order, so sort the frames
|
139 |
+
print(filenames)
|
140 |
+
images = list(map(lambda filename: imageio.imread("/content/video_results/restored_imgs/"+filename), filenames))
|
141 |
+
# os.system(f"rm -rf /content/video_output.mp4")
|
142 |
+
imageio.mimsave('/content/video_output.mp4', images, fps=25.0) # modify the frame duration as needed
|
143 |
+
return "/content/video_output.mp4"
|
144 |
|
145 |
def audio_video():
|
|
|
|
|
|
|
|
|
|
|
146 |
|
147 |
+
input_video = ffmpeg.input('/content/video_output.mp4')
|
|
|
148 |
|
149 |
+
input_audio = ffmpeg.input('/content/audio.wav')
|
150 |
+
os.system(f"rm -rf /content/final_output.mp4")
|
151 |
+
ffmpeg.concat(input_video, input_audio, v=1, a=1).output('/content/final_output.mp4').run()
|
152 |
|
153 |
+
return "/content/final_output.mp4"
|
154 |
+
|
155 |
+
def one_shot_talking(image_in,audio_in):
|
156 |
+
|
157 |
+
|
158 |
+
# Pre-processing of image
|
159 |
+
crop_img=crop_src_image(image_in)
|
160 |
+
|
161 |
+
if os.path.exists("/content/results/restored_imgs/image_pre.png"):
|
162 |
+
os.system(f"rm -rf /content/results/restored_imgs/image_pre.png")
|
163 |
+
|
164 |
+
if not os.path.exists( "/content/results" ):
|
165 |
+
os.makedirs("/content/results")
|
166 |
|
167 |
+
#Improve quality of input image
|
168 |
+
os.system(f"{python_path} /content/GFPGAN/inference_gfpgan.py --upscale 2 -i /content/image_pre.png -o /content/results --bg_upsampler realesrgan")
|
169 |
+
# time.sleep(60)
|
170 |
|
171 |
+
image_in_one_shot='/content/results/image_pre.png'
|
172 |
+
|
173 |
+
#One Shot Talking Face algorithm
|
174 |
+
calculate(image_in_one_shot,audio_in)
|
175 |
+
|
176 |
+
#Video Quality Improvement
|
177 |
+
os.system(f"rm -rf /content/extracted_frames/image_audio_frames")
|
178 |
+
#1. Extract the frames from the video file using PyVideoFramesExtractor
|
179 |
+
os.system(f"{python_path} /content/PyVideoFramesExtractor/extract.py --video=/content/train/image_audio.mp4")
|
180 |
+
|
181 |
+
#2. Improve image quality using GFPGAN on each frames
|
182 |
+
# os.system(f"rm -rf /content/extracted_frames/image_audio_frames")
|
183 |
+
os.system(f"rm -rf /content/video_results/")
|
184 |
+
os.system(f"{python_path} /content/GFPGAN/inference_gfpgan.py --upscale 2 -i /content/extracted_frames/image_audio_frames -o /content/video_results --bg_upsampler realesrgan")
|
185 |
+
|
186 |
+
#3. Merge all the frames to a one video using imageio
|
187 |
+
merge_frames()
|
188 |
+
return audio_video()
|
189 |
+
|
190 |
+
|
191 |
+
def one_shot(image_in,input_text,gender):
|
192 |
if gender == "Female":
|
193 |
+
tts = gTTS(input_text)
|
194 |
+
with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as f:
|
195 |
+
tts.write_to_fp(f)
|
196 |
+
f.seek(0)
|
197 |
+
sound = AudioSegment.from_file(f.name, format="mp3")
|
198 |
+
os.system(f"rm -rf /content/audio.wav")
|
199 |
+
sound.export("/content/audio.wav", format="wav")
|
200 |
+
audio_in="/content/audio.wav"
|
201 |
+
return one_shot_talking(image_in,audio_in)
|
202 |
elif gender == 'Male':
|
203 |
+
|
204 |
+
models, cfg, task = load_model_ensemble_and_task_from_hf_hub(
|
205 |
+
"Voicemod/fastspeech2-en-male1",
|
206 |
+
arg_overrides={"vocoder": "hifigan", "fp16": False}
|
207 |
+
)
|
208 |
+
|
209 |
+
model = models[0]
|
210 |
+
TTSHubInterface.update_cfg_with_data_cfg(cfg, task.data_cfg)
|
211 |
+
generator = task.build_generator([model], cfg)
|
212 |
+
# next(model.parameters()).device
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
213 |
|
214 |
+
sample = TTSHubInterface.get_model_input(task, input_text)
|
215 |
+
sample["net_input"]["src_tokens"] = sample["net_input"]["src_tokens"]
|
216 |
+
sample["net_input"]["src_lengths"] = sample["net_input"]["src_lengths"]
|
217 |
+
sample["speaker"] = sample["speaker"]
|
218 |
+
|
219 |
+
wav, rate = TTSHubInterface.get_prediction(task, model, generator, sample)
|
220 |
+
# soundfile.write("/content/audio_before.wav", wav, rate)
|
221 |
+
os.system(f"rm -rf /content/audio_before.wav")
|
222 |
+
soundfile.write("/content/audio_before.wav", wav.cpu().clone().numpy(), rate)
|
223 |
+
os.system(f"rm -rf /content/audio.wav")
|
224 |
+
cmd='ffmpeg -i /content/audio_before.wav -filter:a "atempo=0.7" -vn /content/audio.wav'
|
225 |
+
os.system(cmd)
|
226 |
+
audio_in="/content/audio.wav"
|
227 |
+
|
228 |
+
return one_shot_talking(image_in,audio_in)
|
229 |
+
|
230 |
+
|
231 |
def run():
|
232 |
+
with gr.Blocks(css=".gradio-container {background-color: lightgray} #radio_div {background-color: #FFD8B4; font-size: 40px;}") as demo:
|
233 |
+
gr.Markdown("<h1 style='text-align: center;'>"+ "One Shot Talking Face from Text" + "</h1><br/><br/>")
|
234 |
+
with gr.Group():
|
235 |
+
# with gr.Box():
|
236 |
+
with gr.Row():
|
237 |
+
# with gr.Row().style(equal_height=True):
|
238 |
+
image_in = gr.Image(show_label=True, type="filepath",label="Input Image")
|
239 |
+
input_text = gr.Textbox(show_label=True,label="Input Text")
|
240 |
+
gender = gr.Radio(["Female","Male"],value="Female",label="Gender")
|
241 |
+
video_out = gr.Video(show_label=True,label="Output")
|
242 |
+
with gr.Row():
|
243 |
+
# with gr.Row().style(equal_height=True):
|
244 |
+
btn = gr.Button("Generate")
|
245 |
+
# gr.Markdown(
|
246 |
+
# """
|
247 |
+
# <p style='text-align: center;'>Feel free to give us your thoughts on this demo and please contact us at
|
248 |
+
# <a href="mailto:[email protected]" target="_blank">[email protected]</a>
|
249 |
+
# <p style='text-align: center;'>Developed by: <a href="https://www.pragnakalp.com" target="_blank">Pragnakalp Techlabs</a></p>
|
250 |
+
|
251 |
+
# """)
|
252 |
+
|
253 |
+
btn.click(one_shot, inputs=[image_in,input_text,gender], outputs=[video_out])
|
254 |
+
demo.queue()
|
255 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
256 |
|
257 |
if __name__ == "__main__":
|
258 |
run()
|