pragnakalp
commited on
Commit
•
f901e07
1
Parent(s):
7bdb753
Upload 3 files
Browse files- Dockerfile +64 -0
- app.py +257 -0
- requirements.txt +5 -0
Dockerfile
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM ubuntu:latest
|
2 |
+
|
3 |
+
WORKDIR /content
|
4 |
+
|
5 |
+
RUN apt-get update && apt-get install -y \
|
6 |
+
python3 \
|
7 |
+
python3-pip \
|
8 |
+
gnupg \
|
9 |
+
wget \
|
10 |
+
htop \
|
11 |
+
sudo \
|
12 |
+
git \
|
13 |
+
git-lfs \
|
14 |
+
software-properties-common \
|
15 |
+
build-essential \
|
16 |
+
cmake \
|
17 |
+
curl \
|
18 |
+
libavcodec-dev \
|
19 |
+
libavformat-dev \
|
20 |
+
libavdevice-dev \
|
21 |
+
libgl1 \
|
22 |
+
libgtk2.0-0 \
|
23 |
+
jq \
|
24 |
+
libraw1394-dev \
|
25 |
+
libopenblas-base
|
26 |
+
|
27 |
+
RUN alias python=python3
|
28 |
+
|
29 |
+
RUN apt-get install -y gnupg wget htop sudo git git-lfs software-properties-common build-essential cmake curl
|
30 |
+
RUN apt-get install -y ffmpeg libavcodec-dev libavformat-dev libavdevice-dev libgl1 libgtk2.0-0 jq libraw1394-dev libopenblas-base
|
31 |
+
RUN apt-add-repository -y universe
|
32 |
+
|
33 |
+
RUN pip3 install pandas scipy matplotlib torch torchvision ffmpeg-python imageio[ffmpeg] tensorboardX huggingface-hub g2p_en opencv-python fairseq imageio torchaudio gradio gtts soundfile fairseq huggingface-hub g2p_en altair imageio-ffmpeg pocketsphinx dlib ffmpeg jq "numpy==1.23.1"
|
34 |
+
|
35 |
+
RUN pip install cmake==3.24.1.1
|
36 |
+
|
37 |
+
RUN git clone https://github.com/TencentARC/GFPGAN.git && cd GFPGAN && pip install basicsr && pip install facexlib && pip install -r requirements.txt && python3 setup.py develop && pip install realesrgan
|
38 |
+
RUN git clone https://github.com/chi0tzp/PyVideoFramesExtractor && cd PyVideoFramesExtractor && pip install -r requirements.txt
|
39 |
+
|
40 |
+
RUN git lfs install
|
41 |
+
RUN git clone https://huggingface.co/camenduru/pocketsphinx-20.04-t4 pocketsphinx && cd pocketsphinx && cmake -S . -B build && cmake --build build --target install
|
42 |
+
RUN git clone https://huggingface.co/camenduru/one-shot-talking-face-20.04-t4 one-shot-talking-face && cd one-shot-talking-face && pip install -r requirements.txt && chmod 755 OpenFace/FeatureExtraction
|
43 |
+
RUN sed -i 's/.cuda()/ /' one-shot-talking-face/test_script.py
|
44 |
+
RUN sed -i 's/.cuda()/ /' one-shot-talking-face/tools/interface.py
|
45 |
+
RUN sed -i 's/.load(checkpoint_path)/.load(checkpoint_path,map_location=torch.device("cpu")) /' one-shot-talking-face/tools/interface.py
|
46 |
+
RUN sed -i 's/.load(audio2pose)/.load(audio2pose,map_location=torch.device("cpu")) /' one-shot-talking-face/tools/interface.py
|
47 |
+
RUN mkdir /content/out
|
48 |
+
|
49 |
+
COPY app.py /content/app.py
|
50 |
+
|
51 |
+
|
52 |
+
RUN adduser --disabled-password --gecos '' admin
|
53 |
+
RUN adduser admin sudo
|
54 |
+
RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
|
55 |
+
|
56 |
+
RUN chown -R admin:admin /content
|
57 |
+
RUN chmod -R 777 /content
|
58 |
+
RUN chown -R admin:admin /home
|
59 |
+
RUN chmod -R 777 /home
|
60 |
+
USER admin
|
61 |
+
|
62 |
+
EXPOSE 7860
|
63 |
+
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os, subprocess, torchaudio
|
3 |
+
import torch
|
4 |
+
from PIL import Image
|
5 |
+
import gradio as gr
|
6 |
+
import soundfile
|
7 |
+
from gtts import gTTS
|
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 |
+
|
22 |
+
from fairseq.checkpoint_utils import load_model_ensemble_and_task_from_hf_hub
|
23 |
+
from fairseq.models.text_to_speech.hub_interface import TTSHubInterface
|
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):
|
80 |
+
w, h = image.size
|
81 |
+
if w == h:
|
82 |
+
return image
|
83 |
+
elif w > h:
|
84 |
+
new_image = Image.new(image.mode, (w, w), (0, 0, 0))
|
85 |
+
new_image.paste(image, (0, (w - h) // 2))
|
86 |
+
return new_image
|
87 |
+
else:
|
88 |
+
new_image = Image.new(image.mode, (h, h), (0, 0, 0))
|
89 |
+
new_image.paste(image, ((h - w) // 2, 0))
|
90 |
+
return new_image
|
91 |
+
|
92 |
+
def calculate(image_in, audio_in):
|
93 |
+
waveform, sample_rate = torchaudio.load(audio_in)
|
94 |
+
waveform = torch.mean(waveform, dim=0, keepdim=True)
|
95 |
+
torchaudio.save("/content/audio.wav", waveform, sample_rate, encoding="PCM_S", bits_per_sample=16)
|
96 |
+
image_in = image_in.replace("results/", "")
|
97 |
+
print("****"*100)
|
98 |
+
print(f" *#*#*# original image => {image_in} *#*#*# ")
|
99 |
+
if os.path.exists(image_in):
|
100 |
+
print(f"image exists => {image_in}")
|
101 |
+
image = Image.open(image_in)
|
102 |
+
else:
|
103 |
+
print("image not exists reading web image")
|
104 |
+
image_url = "http://labelme.csail.mit.edu/Release3.0/Images/users/DNguyen91/face/m_unsexy_gr.jpg"
|
105 |
+
response = requests.get(image_url)
|
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().style(equal_height=True):
|
237 |
+
image_in = gr.Image(show_label=True, type="filepath",label="Input Image")
|
238 |
+
input_text = gr.Textbox(show_label=True,label="Input Text")
|
239 |
+
gender = gr.Radio(["Female","Male"],value="Female",label="Gender")
|
240 |
+
video_out = gr.Video(show_label=True,label="Output")
|
241 |
+
with gr.Row().style(equal_height=True):
|
242 |
+
btn = gr.Button("Generate")
|
243 |
+
# gr.Markdown(
|
244 |
+
# """
|
245 |
+
# <p style='text-align: center;'>Feel free to give us your thoughts on this demo and please contact us at
|
246 |
+
# <a href="mailto:letstalk@pragnakalp.com" target="_blank">letstalk@pragnakalp.com</a>
|
247 |
+
# <p style='text-align: center;'>Developed by: <a href="https://www.pragnakalp.com" target="_blank">Pragnakalp Techlabs</a></p>
|
248 |
+
|
249 |
+
# """)
|
250 |
+
|
251 |
+
btn.click(one_shot, inputs=[image_in,input_text,gender], outputs=[video_out])
|
252 |
+
demo.queue()
|
253 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
254 |
+
|
255 |
+
|
256 |
+
if __name__ == "__main__":
|
257 |
+
run()
|
requirements.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gtts
|
2 |
+
soundfile
|
3 |
+
fairseq
|
4 |
+
huggingface-hub
|
5 |
+
g2p_en
|