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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import onnxruntime as ort
|
2 |
+
from huggingface_hub import hf_hub_download
|
3 |
+
import requests
|
4 |
import os
|
5 |
+
import gradio as gr
|
6 |
+
import spaces
|
7 |
+
from typing import Any, List, Callable
|
8 |
+
import cv2
|
9 |
+
import insightface
|
10 |
+
import time
|
11 |
+
import tempfile
|
12 |
+
import subprocess
|
13 |
+
import gfpgan
|
14 |
|
15 |
+
print("instaling cudnn 9")
|
16 |
+
import subprocess
|
17 |
+
import sys
|
18 |
+
|
19 |
+
def get_pip_version(package_name):
|
20 |
+
try:
|
21 |
+
result = subprocess.run(
|
22 |
+
[sys.executable, '-m', 'pip', 'show', package_name],
|
23 |
+
capture_output=True,
|
24 |
+
text=True,
|
25 |
+
check=True
|
26 |
+
)
|
27 |
+
output = result.stdout
|
28 |
+
version_line = next(line for line in output.split('\n') if line.startswith('Version:'))
|
29 |
+
return version_line.split(': ')[1]
|
30 |
+
except subprocess.CalledProcessError as e:
|
31 |
+
print(f"Erro ao executar o comando: {e}")
|
32 |
+
return None
|
33 |
+
|
34 |
+
package_name = 'nvidia-cudnn-cu12'
|
35 |
+
version = get_pip_version(package_name)
|
36 |
+
print(f"A versão instalada de {package_name} é: {version}")
|
37 |
+
|
38 |
+
command = "find / -path /proc -prune -o -path /sys -prune -o -name 'libcudnn*' -print"
|
39 |
+
process = subprocess.run(command, shell=True, text=True, capture_output=True)
|
40 |
+
if process.returncode == 0:
|
41 |
+
print("Resultados da busca:\n", process.stdout)
|
42 |
+
else:
|
43 |
+
print("Houve um erro na execução do comando:", process.stderr)
|
44 |
+
|
45 |
+
source_path = '/usr/local/lib/python3.10/site-packages/nvidia/cublas/lib/libcublasLt.so.12'
|
46 |
+
destination_path = '/usr/local/lib/python3.10/site-packages/nvidia/cudnn/lib/'
|
47 |
+
command = ['mv', source_path, destination_path]
|
48 |
+
subprocess.run(command, check=True)
|
49 |
+
|
50 |
+
command = ['mv', "/usr/local/lib/python3.10/site-packages/nvidia/cublas/lib/libcublas.so.12", destination_path]
|
51 |
+
subprocess.run(command, check=True)
|
52 |
+
|
53 |
+
command = ['mv', "/usr/local/lib/python3.10/site-packages/nvidia/cufft/lib/libcufft.so.11", destination_path]
|
54 |
+
subprocess.run(command, check=True)
|
55 |
+
|
56 |
+
command = ['mv', "/usr/local/lib/python3.10/site-packages/nvidia/cufft/lib/libcufftw.so.11", destination_path]
|
57 |
+
subprocess.run(command, check=True)
|
58 |
+
|
59 |
+
command = ['mv', "/usr/local/lib/python3.10/site-packages/nvidia/cuda_runtime/lib/libcudart.so.12", destination_path]
|
60 |
+
subprocess.run(command, check=True)
|
61 |
+
|
62 |
+
command = ['mv', "/usr/local/lib/python3.10/site-packages/nvidia/cuda_cupti/lib/libcupti.so.12", destination_path]
|
63 |
+
subprocess.run(command, check=True)
|
64 |
+
|
65 |
+
command = ['cp', "/usr/local/lib/python3.10/site-packages/nvidia/curand/lib/libcurand.so.10", destination_path]
|
66 |
+
subprocess.run(command, check=True)
|
67 |
+
|
68 |
+
command = ['cp', "/usr/local/lib/python3.10/site-packages/nvidia/cusolver/lib/libcusolver.so.11", destination_path]
|
69 |
+
subprocess.run(command, check=True)
|
70 |
+
|
71 |
+
command = ['cp', "/usr/local/lib/python3.10/site-packages/nvidia/cusolver/lib/libcusolverMg.so.11", destination_path]
|
72 |
+
subprocess.run(command, check=True)
|
73 |
+
|
74 |
+
command = ['cp', "/usr/local/lib/python3.10/site-packages/nvidia/cusparse/lib/libcusparse.so.12", destination_path]
|
75 |
+
subprocess.run(command, check=True)
|
76 |
+
|
77 |
+
command = "find / -path /proc -prune -o -path /sys -prune -o -name 'libcu*' -print"
|
78 |
+
process = subprocess.run(command, shell=True, text=True, capture_output=True)
|
79 |
+
if process.returncode == 0:
|
80 |
+
print("Resultados da busca:\n", process.stdout)
|
81 |
+
else:
|
82 |
+
print("Houve um erro na execução do comando:", process.stderr)
|
83 |
+
|
84 |
+
print("done")
|
85 |
+
print("---------------------")
|
86 |
+
print(ort.get_available_providers())
|
87 |
+
|
88 |
+
def conditional_download(download_directory_path, urls):
|
89 |
+
if not os.path.exists(download_directory_path):
|
90 |
+
os.makedirs(download_directory_path)
|
91 |
+
for url in urls:
|
92 |
+
filename = url.split('/')[-1]
|
93 |
+
file_path = os.path.join(download_directory_path, filename)
|
94 |
+
if not os.path.exists(file_path):
|
95 |
+
print(f"Baixando {filename}...")
|
96 |
+
response = requests.get(url, stream=True)
|
97 |
+
if response.status_code == 200:
|
98 |
+
with open(file_path, 'wb') as file:
|
99 |
+
for chunk in response.iter_content(chunk_size=8192):
|
100 |
+
file.write(chunk)
|
101 |
+
print(f"{filename} baixado com sucesso.")
|
102 |
+
else:
|
103 |
+
print(f"Falha ao baixar {filename}. Status code: {response.status_code}")
|
104 |
+
else:
|
105 |
+
print(f"{filename} já existe. Pulando o download.")
|
106 |
+
|
107 |
+
model_path = hf_hub_download(repo_id="countfloyd/deepfake", filename="inswapper_128.onnx")
|
108 |
+
conditional_download("./", ['https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/GFPGANv1.4.pth'])
|
109 |
+
|
110 |
+
FACE_SWAPPER = None
|
111 |
+
FACE_ANALYSER = None
|
112 |
+
FACE_ENHANCER = None
|
113 |
+
|
114 |
+
@spaces.GPU(duration=300, enable_queue=True)
|
115 |
+
def process_video(source_path: str, target_path: str, enhance = False, progress=gr.Progress(), output_path='result.mp4') -> None:
|
116 |
+
def get_face_analyser():
|
117 |
+
global FACE_ANALYSER
|
118 |
+
if FACE_ANALYSER is None:
|
119 |
+
FACE_ANALYSER = insightface.app.FaceAnalysis(name='buffalo_l', providers=["CUDAExecutionProvider"])
|
120 |
+
FACE_ANALYSER.prepare(ctx_id=0, det_size=(640, 640))
|
121 |
+
return FACE_ANALYSER
|
122 |
+
|
123 |
+
def get_face_enhancer() -> Any:
|
124 |
+
global FACE_ENHANCER
|
125 |
+
if FACE_ENHANCER is None:
|
126 |
+
FACE_ENHANCER = gfpgan.GFPGANer(model_path="./GFPGANv1.4.pth", upscale=2, ) # type: ignore[attr-defined]
|
127 |
+
return FACE_ENHANCER
|
128 |
+
|
129 |
+
def get_one_face(frame):
|
130 |
+
face = get_face_analyser().get(frame)
|
131 |
+
try:
|
132 |
+
return min(face, key=lambda x: x.bbox[0])
|
133 |
+
except ValueError:
|
134 |
+
return None
|
135 |
+
|
136 |
+
def get_face_swapper():
|
137 |
+
global FACE_SWAPPER
|
138 |
+
if FACE_SWAPPER is None:
|
139 |
+
FACE_SWAPPER = insightface.model_zoo.get_model(model_path, providers=["CUDAExecutionProvider"])
|
140 |
+
return FACE_SWAPPER
|
141 |
+
|
142 |
+
def swap_face(source_face, target_face, temp_frame):
|
143 |
+
return get_face_swapper().get(temp_frame, target_face, source_face, paste_back=True)
|
144 |
+
|
145 |
+
def process_frame(source_face, temp_frame, enhance):
|
146 |
+
target_face = get_one_face(temp_frame)
|
147 |
+
if target_face:
|
148 |
+
temp_frame = swap_face(source_face, target_face, temp_frame)
|
149 |
+
if enhance:
|
150 |
+
temp_frame = enhance_face(temp_frame)
|
151 |
+
return temp_frame
|
152 |
+
|
153 |
+
def process_image(source_path: str, target_path: str, output_path: str, enhance = False) -> None:
|
154 |
+
source_face = get_one_face(cv2.imread(source_path))
|
155 |
+
target_frame = cv2.imread(target_path)
|
156 |
+
result = process_frame(source_face, target_frame, enhance)
|
157 |
+
cv2.imwrite(output_path, result)
|
158 |
+
|
159 |
+
def create_temp_directory():
|
160 |
+
temp_dir = tempfile.mkdtemp()
|
161 |
+
return temp_dir
|
162 |
+
|
163 |
+
def enhance_face(temp_frame):
|
164 |
+
_, _, temp_frame = get_face_enhancer().enhance(
|
165 |
+
temp_frame,
|
166 |
+
paste_back=True
|
167 |
+
)
|
168 |
+
return temp_frame
|
169 |
+
|
170 |
+
def remove_temp_directory(temp_dir):
|
171 |
+
try:
|
172 |
+
for filename in os.listdir(temp_dir):
|
173 |
+
file_path = os.path.join(temp_dir, filename)
|
174 |
+
if os.path.isfile(file_path):
|
175 |
+
os.unlink(file_path)
|
176 |
+
elif os.path.isdir(file_path):
|
177 |
+
os.rmdir(file_path)
|
178 |
+
os.rmdir(temp_dir)
|
179 |
+
except Exception as e:
|
180 |
+
print(f"Erro ao remover a pasta temporária: {e}")
|
181 |
+
|
182 |
+
def extract_frames(video_path: str):
|
183 |
+
video_capture = cv2.VideoCapture(video_path)
|
184 |
+
if not video_capture.isOpened():
|
185 |
+
print("Erro ao abrir o vídeo.")
|
186 |
+
return []
|
187 |
+
frames = []
|
188 |
+
|
189 |
+
while True:
|
190 |
+
ret, frame = video_capture.read()
|
191 |
+
if not ret:
|
192 |
+
break
|
193 |
+
|
194 |
+
frames.append(frame)
|
195 |
+
|
196 |
+
video_capture.release()
|
197 |
+
|
198 |
+
return frames
|
199 |
+
|
200 |
+
def get_video_fps(video_path: str) -> float:
|
201 |
+
video_capture = cv2.VideoCapture(video_path)
|
202 |
+
if not video_capture.isOpened():
|
203 |
+
raise ValueError("Erro ao abrir o vídeo.")
|
204 |
+
fps = video_capture.get(cv2.CAP_PROP_FPS)
|
205 |
+
video_capture.release()
|
206 |
+
return fps
|
207 |
+
|
208 |
+
def create_video_from_frames(temp_dir: str, output_video_path: str, fps: float) -> None:
|
209 |
+
temp_frames_pattern = os.path.join(temp_dir, "frame_%04d.jpg")
|
210 |
+
|
211 |
+
ffmpeg_command = [
|
212 |
+
'ffmpeg',
|
213 |
+
'-y',
|
214 |
+
'-framerate', str(fps),
|
215 |
+
'-i', temp_frames_pattern,
|
216 |
+
'-c:v', 'libx264',
|
217 |
+
'-pix_fmt', 'yuv420p',
|
218 |
+
'-preset', 'ultrafast',
|
219 |
+
output_video_path
|
220 |
+
]
|
221 |
+
|
222 |
+
subprocess.run(ffmpeg_command, check=True)
|
223 |
+
|
224 |
+
def extract_audio(video_path: str, audio_path: str) -> None:
|
225 |
+
ffmpeg_command = [
|
226 |
+
'ffmpeg',
|
227 |
+
'-y',
|
228 |
+
'-i', video_path,
|
229 |
+
'-q:a', '0',
|
230 |
+
'-map', 'a',
|
231 |
+
'-preset', 'ultrafast',
|
232 |
+
audio_path
|
233 |
+
]
|
234 |
+
|
235 |
+
subprocess.run(ffmpeg_command, check=True)
|
236 |
+
|
237 |
+
def add_audio_to_video(video_path: str, audio_path: str, output_video_path: str) -> None:
|
238 |
+
ffmpeg_command = [
|
239 |
+
'ffmpeg',
|
240 |
+
'-y',
|
241 |
+
'-i', video_path,
|
242 |
+
'-i', audio_path,
|
243 |
+
'-c:v', 'copy',
|
244 |
+
'-c:a', 'aac',
|
245 |
+
'-strict', 'experimental',
|
246 |
+
'-preset', 'ultrafast',
|
247 |
+
output_video_path
|
248 |
+
]
|
249 |
+
|
250 |
+
subprocess.run(ffmpeg_command, check=True)
|
251 |
+
|
252 |
+
def delete_file(file_path: str) -> None:
|
253 |
+
try:
|
254 |
+
os.remove(file_path)
|
255 |
+
except Exception as e:
|
256 |
+
print(f"Erro ao remover o arquivo: {e}")
|
257 |
+
|
258 |
+
def reduce_video(video_path: str, output_video_path: str) -> None:
|
259 |
+
ffmpeg_command = [
|
260 |
+
'ffmpeg',
|
261 |
+
'-y',
|
262 |
+
'-i', video_path,
|
263 |
+
'-vf', "scale='if(gte(iw,ih),720,-1)':'if(gte(iw,ih),-1,720)',pad=ceil(iw/2)*2:ceil(ih/2)*2",
|
264 |
+
'-preset', 'ultrafast',
|
265 |
+
'-r', '24',
|
266 |
+
output_video_path
|
267 |
+
]
|
268 |
+
subprocess.run(ffmpeg_command, check=True)
|
269 |
+
|
270 |
+
if not target_path.endswith('.mp4') and not target_path.endswith('.mov') and not target_path.endswith('.avi'):
|
271 |
+
process_image(source_path, target_path, "./output.jpg", enhance)
|
272 |
+
return "./output.jpg"
|
273 |
+
|
274 |
+
temp_dir = create_temp_directory()
|
275 |
+
video_input = temp_dir + "/input.mp4"
|
276 |
+
reduce_video(target_path , video_input)
|
277 |
+
|
278 |
+
source_face = get_one_face(cv2.imread(source_path))
|
279 |
+
frames = extract_frames(video_input)
|
280 |
+
|
281 |
+
for index, frame in progress.tqdm(enumerate(frames), total=len(frames)):
|
282 |
+
processed_frame = process_frame(source_face, frame, enhance)
|
283 |
+
frame_filename = os.path.join(temp_dir, f"frame_{index:04d}.jpg")
|
284 |
+
cv2.imwrite(frame_filename, processed_frame)
|
285 |
+
|
286 |
+
video_path = temp_dir + "/out.mp4"
|
287 |
+
create_video_from_frames(temp_dir, video_path, get_video_fps(video_input))
|
288 |
+
audio_path = temp_dir + "/audio.wav"
|
289 |
+
extract_audio(video_input, audio_path)
|
290 |
+
add_audio_to_video(video_path, audio_path, output_path)
|
291 |
+
remove_temp_directory(temp_dir)
|
292 |
+
return output_path
|
293 |
+
|
294 |
+
app = gr.Interface(
|
295 |
+
fn=process_video,
|
296 |
+
inputs=[gr.Image(type='filepath'), gr.File(label="Upload Image or Video", file_types=["image", "video"]), gr.Checkbox(label="Use Face GAN(increase render time)", value=False)],
|
297 |
+
outputs=[gr.File()],
|
298 |
+
description="Videos get downsampled to 720p and 24fps. To modify the code or purchase a modification, send an email to [email protected] to donate to the owner of the space: https://donate.stripe.com/3csg0D0tadXU4mYcMM"
|
299 |
+
)
|
300 |
+
|
301 |
+
app.launch()
|