mr2along commited on
Commit
d723316
·
verified ·
1 Parent(s): 87f9b42

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +823 -205
app.py CHANGED
@@ -1,59 +1,96 @@
1
  import os
2
 
3
- # =========================
4
  # FORCE CPU MODE
5
- # =========================
6
  os.environ["CUDA_VISIBLE_DEVICES"] = ""
7
  os.environ["PYTORCH_CUDA_ALLOC_CONF"] = ""
8
 
9
- import torch
10
  import sys
11
  import asyncio
12
  import imageio
13
  import tempfile
14
  import numpy as np
 
15
  import gradio as gr
 
16
 
17
  from typing import Sequence, Mapping, Any, Union
18
-
19
  from PIL import Image
20
  from huggingface_hub import hf_hub_download
21
 
22
- import cv2
23
  from insightface.app import FaceAnalysis
24
 
25
 
26
- # =========================
27
- # DOWNLOAD MODELS (ONLY IF NOT EXISTS)
28
- # =========================
29
 
30
  def download_if_not_exists(repo, filename, local_dir):
31
  path = os.path.join(local_dir, filename)
 
32
  if not os.path.exists(path):
33
  os.makedirs(local_dir, exist_ok=True)
34
- hf_hub_download(repo_id=repo, filename=filename, local_dir=local_dir)
35
 
36
- download_if_not_exists("ezioruan/inswapper_128.onnx", "inswapper_128.onnx", "models/insightface")
37
- download_if_not_exists("martintomov/comfy", "facerestore_models/GPEN-BFR-512.onnx", "models")
38
- download_if_not_exists("facefusion/models-3.3.0", "hyperswap_1a_256.onnx", "models/hyperswap")
39
- download_if_not_exists("facefusion/models-3.3.0", "hyperswap_1b_256.onnx", "models/hyperswap")
40
- download_if_not_exists("facefusion/models-3.3.0", "hyperswap_1c_256.onnx", "models/hyperswap")
41
 
42
- # =========================
43
- # COMFY INIT (GIỮ NGUYÊN)
44
- # =========================
 
 
45
 
46
- from comfy.model_management import CPUState
47
- import comfy.model_management
48
- comfy.model_management.cpu_state = CPUState.CPU
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
- def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any:
51
  try:
52
  return obj[index]
53
  except Exception:
54
  return obj["result"][index]
55
 
 
56
  def find_path(name: str, path: str = None) -> str:
 
57
  if path is None:
58
  path = os.getcwd()
59
 
@@ -61,31 +98,61 @@ def find_path(name: str, path: str = None) -> str:
61
  return os.path.join(path, name)
62
 
63
  parent = os.path.dirname(path)
 
64
  if parent == path:
65
  return None
66
 
67
  return find_path(name, parent)
68
 
 
69
  def add_comfyui_directory_to_sys_path():
 
70
  comfyui_path = find_path("ComfyUI")
 
71
  if comfyui_path and os.path.isdir(comfyui_path):
72
- sys.path.append(comfyui_path)
 
 
 
 
 
73
 
74
  add_comfyui_directory_to_sys_path()
75
 
 
76
  def add_extra_model_paths():
 
77
  try:
78
  from main import load_extra_path_config
 
79
  except ImportError:
80
  from utils.extra_config import load_extra_path_config
81
 
82
  extra_model_paths = find_path("extra_model_paths.yaml")
 
83
  if extra_model_paths:
84
  load_extra_path_config(extra_model_paths)
85
 
 
86
  add_extra_model_paths()
87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  def import_custom_nodes():
 
89
  import execution
90
  from nodes import init_extra_nodes
91
  import server
@@ -94,21 +161,29 @@ def import_custom_nodes():
94
  asyncio.set_event_loop(loop)
95
 
96
  server_instance = server.PromptServer(loop)
 
97
  execution.PromptQueue(server_instance)
98
- loop.run_until_complete(init_extra_nodes())
 
 
 
 
99
 
100
  import_custom_nodes()
101
 
 
102
  from nodes import NODE_CLASS_MAPPINGS
103
 
 
104
  loadimage = NODE_CLASS_MAPPINGS["LoadImage"]()
105
  reactorfaceswap = NODE_CLASS_MAPPINGS["ReActorFaceSwap"]()
106
 
107
- # =========================
108
- # FAST FACE PREVIEW
109
- # =========================
110
 
111
- face_cache = {}
 
 
 
 
112
 
113
  face_analyzer = FaceAnalysis(
114
  name="buffalo_s",
@@ -120,13 +195,70 @@ face_analyzer.prepare(
120
  det_size=(320, 320)
121
  )
122
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
  def preview_faces(image_path):
125
 
 
 
 
126
  img = cv2.imread(image_path)
127
 
128
  if img is None:
129
- return None,[]
130
 
131
  h, w = img.shape[:2]
132
 
@@ -150,31 +282,40 @@ def preview_faces(image_path):
150
  scale = 1.0
151
  img_small = img
152
 
 
153
  cache_key = (
154
  image_path,
155
  os.path.getmtime(image_path)
156
  )
157
 
 
158
  if cache_key in face_cache:
159
 
160
  faces = face_cache[cache_key]
161
 
162
  else:
163
 
 
 
164
  faces = sorted(
165
- face_analyzer.get(img_small),
166
  key=lambda f:
167
- (f.bbox[2]-f.bbox[0]) *
168
- (f.bbox[3]-f.bbox[1]),
169
  reverse=True
170
  )
171
 
172
-
173
-
174
  face_cache[cache_key] = faces
175
 
 
 
 
 
 
 
 
176
  face_boxes = []
177
- face_previews = []
178
 
179
  for idx, face in enumerate(faces):
180
 
@@ -185,89 +326,154 @@ def preview_faces(image_path):
185
  x2 = int(x2 / scale)
186
  y2 = int(y2 / scale)
187
 
188
- face_boxes.append([x1, y1, x2, y2])
 
 
 
 
 
 
 
189
 
190
- crop = img[y1:y2, x1:x2]
191
 
192
- if crop.size == 0:
193
- continue
 
194
 
195
- crop = cv2.resize(
196
- crop,
197
- (180, 180),
198
- interpolation=cv2.INTER_AREA
 
 
199
  )
200
 
 
 
 
 
 
 
 
201
  cv2.rectangle(
202
- crop,
203
- (0, 0),
204
- (179, 35),
205
- (0, 255, 0),
206
- -1
 
 
 
 
 
 
207
  )
208
 
209
  cv2.putText(
210
- crop,
211
- f"FACE {idx}",
212
- (10, 24),
213
- cv2.FONT_HERSHEY_SIMPLEX,
214
- 0.7,
215
- (0, 0, 0),
216
- 2
 
 
 
217
  )
218
 
219
- face_previews.append(crop)
220
-
221
- if len(face_previews) == 0:
222
- return None, []
223
 
224
- preview = np.hstack(face_previews)
 
 
 
225
 
226
- preview = cv2.cvtColor(
227
- preview,
228
- cv2.COLOR_BGR2RGB
229
- )
230
 
231
- return preview, face_boxes
232
 
233
 
 
 
 
234
 
235
- def show_face_indexes(target_files):
236
 
237
- if not target_files:
238
- return None, [],[]
239
 
240
- target_path = target_files[0].name
241
 
242
  if target_path.lower().endswith(".gif"):
243
 
244
  reader = imageio.get_reader(target_path)
245
 
246
- first_frame = reader.get_data(0)
 
 
 
 
 
 
247
 
248
- reader.close()
249
 
250
  with tempfile.NamedTemporaryFile(
251
  suffix=".png",
252
  delete=False
253
  ) as tmp:
254
 
255
- Image.fromarray(first_frame).save(tmp.name)
 
 
 
 
 
 
 
256
 
257
- preview = preview_faces(tmp.name)
258
 
259
- os.remove(tmp.name)
 
 
 
 
 
 
260
 
261
- return preview
262
 
263
  return preview_faces(target_path)
264
 
265
- # =========================
266
- # MAIN FUNCTION
267
- # =========================
 
 
268
  def update_face_selector(target_files):
269
 
270
- preview, boxes, choices = [str(i) for i in range(len(face_boxes))]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
 
272
  return (
273
  preview,
@@ -278,6 +484,122 @@ def update_face_selector(target_files):
278
  )
279
  )
280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
  def generate_image(
282
  source_files,
283
  target_files,
@@ -287,214 +609,510 @@ def generate_image(
287
  restore_strength
288
  ):
289
 
290
- selected_face_index = int(selected_face_index)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
 
292
- os.makedirs("output", exist_ok=True)
293
  output_paths = []
294
 
295
- if not source_files or not target_files:
296
- return []
297
 
298
  with torch.inference_mode():
299
 
300
- for s in source_files:
 
 
 
 
 
 
301
 
302
- source_path = s.name
303
- loadimage_source = loadimage.load_image(image=source_path)
304
- source_tensor = get_value_at_index(loadimage_source, 0)
305
- source_base = os.path.splitext(os.path.basename(source_path))[0]
 
306
 
307
- for t in target_files:
308
 
309
- target_path = t.name
310
- target_base = os.path.splitext(os.path.basename(target_path))[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
 
312
- # ================= GIF =================
313
  if target_path.lower().endswith(".gif"):
314
 
315
- reader = imageio.get_reader(target_path)
 
 
 
 
 
 
 
 
 
 
316
  frames = []
317
  durations = []
318
 
319
- for i, frame in enumerate(reader):
320
- frame_rgb = Image.fromarray(frame).convert("RGB")
321
- frames.append(np.array(frame_rgb))
322
- meta = reader.get_meta_data(index=i)
323
- durations.append(meta.get("duration", 100))
324
 
325
- reader.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
 
327
  output_frames = []
328
 
329
- for frame in frames:
330
 
331
- with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
332
- Image.fromarray(frame).save(tmp.name)
333
- temp_path = tmp.name
334
 
335
- loadimage_target = loadimage.load_image(image=temp_path)
336
- target_tensor = get_value_at_index(loadimage_target, 0)
337
-
338
- result = reactorfaceswap.execute(
339
- enabled=True,
340
- swap_model=swap_model,
341
- facedetection="retinaface_resnet50",
342
- face_restore_model=face_restore_model,
343
- face_restore_visibility=restore_strength,
344
- codeformer_weight=0.5,
345
- detect_gender_input="no",
346
- detect_gender_source="no",
347
- input_faces_index=str(selected_face_index),
348
- source_faces_index="0",
349
- console_log_level=1,
350
- input_image=target_tensor,
351
- source_image=source_tensor,
352
  )
353
 
354
- swapped = get_value_at_index(result, 0)[0]
355
 
356
- if isinstance(swapped, torch.Tensor):
357
- swapped = swapped.detach().cpu().float().numpy()
 
 
358
 
359
- if swapped.max() <= 1.0:
360
- swapped *= 255.0
361
 
362
- swapped = np.clip(swapped, 0, 255).astype(np.uint8)
 
 
 
 
363
 
364
- output_frames.append(Image.fromarray(swapped).convert("RGB"))
365
- os.remove(temp_path)
366
 
367
- output_path = f"output/{source_base}_to_{target_base}.webp"
368
 
369
- output_frames[0].save(
370
- output_path,
371
- save_all=True,
372
- append_images=output_frames[1:],
373
- duration=durations,
374
- loop=0,
375
- format="WEBP",
376
- quality=90,
377
- method=6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
378
  )
379
 
380
- # ================= IMAGE =================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
381
  else:
382
 
383
- loadimage_target = loadimage.load_image(image=target_path)
384
- target_tensor = get_value_at_index(loadimage_target, 0)
385
-
386
- result = reactorfaceswap.execute(
387
- enabled=True,
388
- swap_model=swap_model,
389
- facedetection="retinaface_resnet50",
390
- face_restore_model=face_restore_model,
391
- face_restore_visibility=restore_strength,
392
- codeformer_weight=0.5,
393
- detect_gender_input="no",
394
- detect_gender_source="no",
395
- input_faces_index=str(selected_face_index),
396
- source_faces_index="0",
397
- console_log_level=1,
398
- input_image=target_tensor,
399
- source_image=source_tensor,
400
  )
401
 
402
- swapped = get_value_at_index(result, 0)[0]
403
 
404
- if isinstance(swapped, torch.Tensor):
405
- swapped = swapped.detach().cpu().float().numpy()
 
 
 
 
 
 
 
 
 
 
 
 
 
406
 
407
- if swapped.max() <= 1.0:
408
- swapped *= 255.0
 
 
 
 
 
409
 
410
- swapped = np.clip(swapped, 0, 255).astype(np.uint8)
411
 
412
- output_path = f"output/{source_base}_to_{target_base}.webp"
413
 
414
- Image.fromarray(swapped).save(
415
  output_path,
 
416
  format="WEBP",
 
417
  quality=90,
 
418
  method=6
419
  )
420
 
421
- output_paths.append(output_path)
 
 
 
 
 
 
 
 
 
 
422
 
423
  return output_paths
424
 
425
- # =========================
 
426
  # GRADIO UI
427
- # =========================
428
 
429
- with gr.Blocks() as app:
 
 
430
 
431
 
432
- face_boxes = gr.State([])
433
- source_files = gr.File(label="Source Faces", file_count="multiple", interactive=True)
434
- target_files = gr.File(label="Target Images / GIFs", file_count="multiple", interactive=True)
435
- preview_btn = gr.Button("Preview Face Index")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
436
 
437
  preview_image = gr.Image(
 
438
  label="Click vào khuôn mặt muốn swap",
 
439
  type="numpy",
440
- interactive=True,
441
- height =600
442
-
 
443
  )
 
 
 
 
 
444
  face_selector = gr.Dropdown(
445
- choices=[],
446
- value=None,
447
- label="Select Face"
 
 
 
448
  )
449
 
450
-
 
 
 
 
451
  swap_model = gr.Dropdown(
452
- choices=["inswapper_128.onnx",
453
- "hyperswap_1a_256.onnx",
454
- "hyperswap_1b_256.onnx",
455
- "hyperswap_1c_256.onnx"],
 
 
 
 
456
  value="hyperswap_1b_256.onnx",
 
457
  label="Swap Model"
458
  )
459
 
 
 
 
 
 
460
  face_restore_model = gr.Dropdown(
461
- choices=["none", "GPEN-BFR-512.onnx"],
 
 
 
 
 
462
  value="none",
 
463
  label="Face Restore Model"
464
  )
465
 
466
- restore_strength = gr.Slider(0, 1, 0.7, step=0.05)
467
- #target_index = gr.Dropdown([0,1,2,3,4], value=0)
468
 
469
- generate_btn = gr.Button("Generate")
470
- output_files = gr.Files(label="Output WebPs")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
471
 
472
  preview_btn.click(
473
- fn=update_face_selector,
474
- inputs=[target_files],
475
- outputs=[
476
- preview_image,
477
- face_boxes,
478
- face_selector
479
- ]
 
 
 
 
 
480
  )
481
 
482
 
483
-
484
  generate_btn.click(
 
485
  fn=generate_image,
 
486
  inputs=[
487
- source_files,
488
- target_files,
489
- face_selector,
490
- swap_model,
491
- face_restore_model,
492
- restore_strength
493
- ]
494
 
495
- outputs=output_files
496
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
497
 
498
 
 
 
 
499
 
500
- app.launch(share=True)
 
 
 
1
  import os
2
 
3
+ # ============================================================
4
  # FORCE CPU MODE
5
+ # ============================================================
6
  os.environ["CUDA_VISIBLE_DEVICES"] = ""
7
  os.environ["PYTORCH_CUDA_ALLOC_CONF"] = ""
8
 
 
9
  import sys
10
  import asyncio
11
  import imageio
12
  import tempfile
13
  import numpy as np
14
+ import torch
15
  import gradio as gr
16
+ import cv2
17
 
18
  from typing import Sequence, Mapping, Any, Union
 
19
  from PIL import Image
20
  from huggingface_hub import hf_hub_download
21
 
 
22
  from insightface.app import FaceAnalysis
23
 
24
 
25
+ # ============================================================
26
+ # DOWNLOAD MODELS
27
+ # ============================================================
28
 
29
  def download_if_not_exists(repo, filename, local_dir):
30
  path = os.path.join(local_dir, filename)
31
+
32
  if not os.path.exists(path):
33
  os.makedirs(local_dir, exist_ok=True)
 
34
 
35
+ print(f"Downloading: {filename}")
 
 
 
 
36
 
37
+ hf_hub_download(
38
+ repo_id=repo,
39
+ filename=filename,
40
+ local_dir=local_dir
41
+ )
42
 
43
+ return path
44
+
45
+
46
+ download_if_not_exists(
47
+ "ezioruan/inswapper_128.onnx",
48
+ "inswapper_128.onnx",
49
+ "models/insightface"
50
+ )
51
+
52
+ download_if_not_exists(
53
+ "martintomov/comfy",
54
+ "facerestore_models/GPEN-BFR-512.onnx",
55
+ "models"
56
+ )
57
+
58
+ download_if_not_exists(
59
+ "facefusion/models-3.3.0",
60
+ "hyperswap_1a_256.onnx",
61
+ "models/hyperswap"
62
+ )
63
+
64
+ download_if_not_exists(
65
+ "facefusion/models-3.3.0",
66
+ "hyperswap_1b_256.onnx",
67
+ "models/hyperswap"
68
+ )
69
+
70
+ download_if_not_exists(
71
+ "facefusion/models-3.3.0",
72
+ "hyperswap_1c_256.onnx",
73
+ "models/hyperswap"
74
+ )
75
+
76
+
77
+ # ============================================================
78
+ # COMFYUI INIT
79
+ # ============================================================
80
+
81
+ def get_value_at_index(
82
+ obj: Union[Sequence, Mapping],
83
+ index: int
84
+ ) -> Any:
85
 
 
86
  try:
87
  return obj[index]
88
  except Exception:
89
  return obj["result"][index]
90
 
91
+
92
  def find_path(name: str, path: str = None) -> str:
93
+
94
  if path is None:
95
  path = os.getcwd()
96
 
 
98
  return os.path.join(path, name)
99
 
100
  parent = os.path.dirname(path)
101
+
102
  if parent == path:
103
  return None
104
 
105
  return find_path(name, parent)
106
 
107
+
108
  def add_comfyui_directory_to_sys_path():
109
+
110
  comfyui_path = find_path("ComfyUI")
111
+
112
  if comfyui_path and os.path.isdir(comfyui_path):
113
+
114
+ if comfyui_path not in sys.path:
115
+ sys.path.append(comfyui_path)
116
+
117
+ print("ComfyUI:", comfyui_path)
118
+
119
 
120
  add_comfyui_directory_to_sys_path()
121
 
122
+
123
  def add_extra_model_paths():
124
+
125
  try:
126
  from main import load_extra_path_config
127
+
128
  except ImportError:
129
  from utils.extra_config import load_extra_path_config
130
 
131
  extra_model_paths = find_path("extra_model_paths.yaml")
132
+
133
  if extra_model_paths:
134
  load_extra_path_config(extra_model_paths)
135
 
136
+
137
  add_extra_model_paths()
138
 
139
+
140
+ # ============================================================
141
+ # FORCE COMFY CPU
142
+ # ============================================================
143
+
144
+ from comfy.model_management import CPUState
145
+ import comfy.model_management
146
+
147
+ comfy.model_management.cpu_state = CPUState.CPU
148
+
149
+
150
+ # ============================================================
151
+ # LOAD CUSTOM NODES
152
+ # ============================================================
153
+
154
  def import_custom_nodes():
155
+
156
  import execution
157
  from nodes import init_extra_nodes
158
  import server
 
161
  asyncio.set_event_loop(loop)
162
 
163
  server_instance = server.PromptServer(loop)
164
+
165
  execution.PromptQueue(server_instance)
166
+
167
+ loop.run_until_complete(
168
+ init_extra_nodes()
169
+ )
170
+
171
 
172
  import_custom_nodes()
173
 
174
+
175
  from nodes import NODE_CLASS_MAPPINGS
176
 
177
+
178
  loadimage = NODE_CLASS_MAPPINGS["LoadImage"]()
179
  reactorfaceswap = NODE_CLASS_MAPPINGS["ReActorFaceSwap"]()
180
 
 
 
 
181
 
182
+ # ============================================================
183
+ # INSIGHTFACE
184
+ # ============================================================
185
+
186
+ print("Loading InsightFace...")
187
 
188
  face_analyzer = FaceAnalysis(
189
  name="buffalo_s",
 
195
  det_size=(320, 320)
196
  )
197
 
198
+ print("InsightFace ready.")
199
+
200
+
201
+ # ============================================================
202
+ # CACHE
203
+ # ============================================================
204
+
205
+ face_cache = {}
206
+
207
+
208
+ # ============================================================
209
+ # GRADIO FILE HELPER
210
+ # ============================================================
211
+
212
+ def get_file_path(file):
213
+
214
+ if file is None:
215
+ return None
216
+
217
+ # Gradio mới
218
+ if isinstance(file, str):
219
+ return file
220
+
221
+ # Gradio FileData
222
+ if hasattr(file, "path"):
223
+ return file.path
224
+
225
+ # Gradio cũ
226
+ if hasattr(file, "name"):
227
+ return file.name
228
+
229
+ return str(file)
230
+
231
+
232
+ def get_file_paths(files):
233
+
234
+ if not files:
235
+ return []
236
+
237
+ result = []
238
+
239
+ for file in files:
240
+
241
+ path = get_file_path(file)
242
+
243
+ if path and os.path.exists(path):
244
+ result.append(path)
245
+
246
+ return result
247
+
248
+
249
+ # ============================================================
250
+ # PREVIEW FACE
251
+ # ============================================================
252
 
253
  def preview_faces(image_path):
254
 
255
+ if not image_path:
256
+ return None, []
257
+
258
  img = cv2.imread(image_path)
259
 
260
  if img is None:
261
+ return None, []
262
 
263
  h, w = img.shape[:2]
264
 
 
282
  scale = 1.0
283
  img_small = img
284
 
285
+
286
  cache_key = (
287
  image_path,
288
  os.path.getmtime(image_path)
289
  )
290
 
291
+
292
  if cache_key in face_cache:
293
 
294
  faces = face_cache[cache_key]
295
 
296
  else:
297
 
298
+ faces = face_analyzer.get(img_small)
299
+
300
  faces = sorted(
301
+ faces,
302
  key=lambda f:
303
+ (f.bbox[2] - f.bbox[0]) *
304
+ (f.bbox[3] - f.bbox[1]),
305
  reverse=True
306
  )
307
 
 
 
308
  face_cache[cache_key] = faces
309
 
310
+
311
+ # ========================================================
312
+ # DRAW FULL IMAGE
313
+ # ========================================================
314
+
315
+ preview_img = img.copy()
316
+
317
  face_boxes = []
318
+
319
 
320
  for idx, face in enumerate(faces):
321
 
 
326
  x2 = int(x2 / scale)
327
  y2 = int(y2 / scale)
328
 
329
+ x1 = max(0, x1)
330
+ y1 = max(0, y1)
331
+ x2 = min(w, x2)
332
+ y2 = min(h, y2)
333
+
334
+ face_boxes.append(
335
+ [x1, y1, x2, y2]
336
+ )
337
 
 
338
 
339
+ # ====================================================
340
+ # FACE BOX
341
+ # ====================================================
342
 
343
+ cv2.rectangle(
344
+ preview_img,
345
+ (x1, y1),
346
+ (x2, y2),
347
+ (0, 255, 0),
348
+ 3
349
  )
350
 
351
+
352
+ # ====================================================
353
+ # FACE INDEX
354
+ # ====================================================
355
+
356
+ text = f"FACE {idx}"
357
+
358
  cv2.rectangle(
359
+ preview_img,
360
+ (
361
+ x1,
362
+ max(0, y1 - 35)
363
+ ),
364
+ (
365
+ x1 + 120,
366
+ y1
367
+ ),
368
+ (0, 255, 0),
369
+ -1
370
  )
371
 
372
  cv2.putText(
373
+ preview_img,
374
+ text,
375
+ (
376
+ x1 + 8,
377
+ max(24, y1 - 10)
378
+ ),
379
+ cv2.FONT_HERSHEY_SIMPLEX,
380
+ 0.7,
381
+ (0, 0, 0),
382
+ 2
383
  )
384
 
 
 
 
 
385
 
386
+ preview_img = cv2.cvtColor(
387
+ preview_img,
388
+ cv2.COLOR_BGR2RGB
389
+ )
390
 
 
 
 
 
391
 
392
+ return preview_img, face_boxes
393
 
394
 
395
+ # ============================================================
396
+ # GIF FIRST FRAME
397
+ # ============================================================
398
 
399
+ def get_preview_image(target_path):
400
 
401
+ if not target_path:
402
+ return None, []
403
 
 
404
 
405
  if target_path.lower().endswith(".gif"):
406
 
407
  reader = imageio.get_reader(target_path)
408
 
409
+ try:
410
+
411
+ first_frame = reader.get_data(0)
412
+
413
+ finally:
414
+
415
+ reader.close()
416
 
 
417
 
418
  with tempfile.NamedTemporaryFile(
419
  suffix=".png",
420
  delete=False
421
  ) as tmp:
422
 
423
+ temp_path = tmp.name
424
+
425
+ Image.fromarray(
426
+ first_frame
427
+ ).save(temp_path)
428
+
429
+
430
+ try:
431
 
432
+ result = preview_faces(temp_path)
433
 
434
+ finally:
435
+
436
+ if os.path.exists(temp_path):
437
+ os.remove(temp_path)
438
+
439
+
440
+ return result
441
 
 
442
 
443
  return preview_faces(target_path)
444
 
445
+
446
+ # ============================================================
447
+ # UPDATE FACE SELECTOR
448
+ # ============================================================
449
+
450
  def update_face_selector(target_files):
451
 
452
+ paths = get_file_paths(target_files)
453
+
454
+ if not paths:
455
+
456
+ return (
457
+ None,
458
+ [],
459
+ gr.update(
460
+ choices=[],
461
+ value=None
462
+ )
463
+ )
464
+
465
+
466
+ # Chọn target đầu tiên để preview
467
+ preview, boxes = get_preview_image(
468
+ paths[0]
469
+ )
470
+
471
+
472
+ choices = [
473
+ str(i)
474
+ for i in range(len(boxes))
475
+ ]
476
+
477
 
478
  return (
479
  preview,
 
484
  )
485
  )
486
 
487
+
488
+ # ============================================================
489
+ # CONVERT COMFY OUTPUT -> NUMPY
490
+ # ============================================================
491
+
492
+ def comfy_image_to_numpy(swapped):
493
+
494
+ if isinstance(swapped, torch.Tensor):
495
+
496
+ swapped = (
497
+ swapped
498
+ .detach()
499
+ .cpu()
500
+ .float()
501
+ .numpy()
502
+ )
503
+
504
+
505
+ swapped = np.asarray(swapped)
506
+
507
+
508
+ if swapped.ndim == 4:
509
+
510
+ swapped = swapped[0]
511
+
512
+
513
+ if swapped.max() <= 1.0:
514
+
515
+ swapped = swapped * 255.0
516
+
517
+
518
+ swapped = np.clip(
519
+ swapped,
520
+ 0,
521
+ 255
522
+ ).astype(np.uint8)
523
+
524
+
525
+ return swapped
526
+
527
+
528
+ # ============================================================
529
+ # SWAP ONE IMAGE
530
+ # ============================================================
531
+
532
+ def swap_single_image(
533
+ source_tensor,
534
+ target_path,
535
+ selected_face_index,
536
+ swap_model,
537
+ face_restore_model,
538
+ restore_strength
539
+ ):
540
+
541
+ loadimage_target = loadimage.load_image(
542
+ image=target_path
543
+ )
544
+
545
+ target_tensor = get_value_at_index(
546
+ loadimage_target,
547
+ 0
548
+ )
549
+
550
+
551
+ result = reactorfaceswap.execute(
552
+
553
+ enabled=True,
554
+
555
+ swap_model=swap_model,
556
+
557
+ facedetection="retinaface_resnet50",
558
+
559
+ face_restore_model=face_restore_model,
560
+
561
+ face_restore_visibility=restore_strength,
562
+
563
+ codeformer_weight=0.5,
564
+
565
+ detect_gender_input="no",
566
+
567
+ detect_gender_source="no",
568
+
569
+ input_faces_index=str(
570
+ selected_face_index
571
+ ),
572
+
573
+ source_faces_index="0",
574
+
575
+ console_log_level=1,
576
+
577
+ input_image=target_tensor,
578
+
579
+ source_image=source_tensor,
580
+ )
581
+
582
+
583
+ swapped = get_value_at_index(
584
+ result,
585
+ 0
586
+ )[0]
587
+
588
+
589
+ swapped = comfy_image_to_numpy(
590
+ swapped
591
+ )
592
+
593
+
594
+ return Image.fromarray(
595
+ swapped
596
+ ).convert("RGB")
597
+
598
+
599
+ # ============================================================
600
+ # MAIN GENERATE
601
+ # ============================================================
602
+
603
  def generate_image(
604
  source_files,
605
  target_files,
 
609
  restore_strength
610
  ):
611
 
612
+ source_paths = get_file_paths(
613
+ source_files
614
+ )
615
+
616
+ target_paths = get_file_paths(
617
+ target_files
618
+ )
619
+
620
+
621
+ if not source_paths:
622
+
623
+ raise gr.Error(
624
+ "Chưa chọn Source Face."
625
+ )
626
+
627
+
628
+ if not target_paths:
629
+
630
+ raise gr.Error(
631
+ "Chưa chọn Target Image/GIF."
632
+ )
633
+
634
+
635
+ if selected_face_index is None:
636
+
637
+ raise gr.Error(
638
+ "Hãy chọn khuôn mặt cần swap."
639
+ )
640
+
641
+
642
+ selected_face_index = int(
643
+ selected_face_index
644
+ )
645
+
646
+
647
+ os.makedirs(
648
+ "output",
649
+ exist_ok=True
650
+ )
651
+
652
 
 
653
  output_paths = []
654
 
 
 
655
 
656
  with torch.inference_mode():
657
 
658
+ for source_path in source_paths:
659
+
660
+ print(
661
+ "SOURCE:",
662
+ source_path
663
+ )
664
+
665
 
666
+ loadimage_source = (
667
+ loadimage.load_image(
668
+ image=source_path
669
+ )
670
+ )
671
 
 
672
 
673
+ source_tensor = (
674
+ get_value_at_index(
675
+ loadimage_source,
676
+ 0
677
+ )
678
+ )
679
+
680
+
681
+ source_base = os.path.splitext(
682
+ os.path.basename(
683
+ source_path
684
+ )
685
+ )[0]
686
+
687
+
688
+ for target_path in target_paths:
689
+
690
+ target_base = os.path.splitext(
691
+ os.path.basename(
692
+ target_path
693
+ )
694
+ )[0]
695
+
696
+
697
+ # ====================================================
698
+ # GIF
699
+ # ====================================================
700
 
 
701
  if target_path.lower().endswith(".gif"):
702
 
703
+ print(
704
+ "Processing GIF:",
705
+ target_path
706
+ )
707
+
708
+
709
+ reader = imageio.get_reader(
710
+ target_path
711
+ )
712
+
713
+
714
  frames = []
715
  durations = []
716
 
 
 
 
 
 
717
 
718
+ try:
719
+
720
+ for i, frame in enumerate(reader):
721
+
722
+ frame_rgb = Image.fromarray(
723
+ frame
724
+ ).convert("RGB")
725
+
726
+
727
+ frames.append(
728
+ np.array(
729
+ frame_rgb
730
+ )
731
+ )
732
+
733
+
734
+ try:
735
+
736
+ meta = (
737
+ reader
738
+ .get_meta_data(
739
+ index=i
740
+ )
741
+ )
742
+
743
+ duration = meta.get(
744
+ "duration",
745
+ 100
746
+ )
747
+
748
+ except Exception:
749
+
750
+ duration = 100
751
+
752
+
753
+ durations.append(
754
+ duration
755
+ )
756
+
757
+
758
+ finally:
759
+
760
+ reader.close()
761
+
762
 
763
  output_frames = []
764
 
 
765
 
766
+ for frame_index, frame in enumerate(frames):
 
 
767
 
768
+ print(
769
+ f"GIF frame "
770
+ f"{frame_index + 1}/"
771
+ f"{len(frames)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
772
  )
773
 
 
774
 
775
+ with tempfile.NamedTemporaryFile(
776
+ suffix=".png",
777
+ delete=False
778
+ ) as tmp:
779
 
780
+ temp_path = tmp.name
 
781
 
782
+ Image.fromarray(
783
+ frame
784
+ ).save(
785
+ temp_path
786
+ )
787
 
 
 
788
 
789
+ try:
790
 
791
+ result_image = swap_single_image(
792
+
793
+ source_tensor,
794
+
795
+ temp_path,
796
+
797
+ selected_face_index,
798
+
799
+ swap_model,
800
+
801
+ face_restore_model,
802
+
803
+ restore_strength
804
+ )
805
+
806
+ output_frames.append(
807
+ result_image
808
+ )
809
+
810
+ finally:
811
+
812
+ if os.path.exists(
813
+ temp_path
814
+ ):
815
+ os.remove(
816
+ temp_path
817
+ )
818
+
819
+
820
+ output_path = (
821
+ f"output/"
822
+ f"{source_base}"
823
+ f"_to_"
824
+ f"{target_base}"
825
+ f".webp"
826
  )
827
 
828
+
829
+ if output_frames:
830
+
831
+ output_frames[0].save(
832
+
833
+ output_path,
834
+
835
+ save_all=True,
836
+
837
+ append_images=(
838
+ output_frames[1:]
839
+ ),
840
+
841
+ duration=durations,
842
+
843
+ loop=0,
844
+
845
+ format="WEBP",
846
+
847
+ quality=90,
848
+
849
+ method=6
850
+ )
851
+
852
+
853
+ # ====================================================
854
+ # IMAGE
855
+ # ====================================================
856
+
857
  else:
858
 
859
+ print(
860
+ "Processing:",
861
+ target_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
862
  )
863
 
 
864
 
865
+ result_image = swap_single_image(
866
+
867
+ source_tensor,
868
+
869
+ target_path,
870
+
871
+ selected_face_index,
872
+
873
+ swap_model,
874
+
875
+ face_restore_model,
876
+
877
+ restore_strength
878
+ )
879
+
880
 
881
+ output_path = (
882
+ f"output/"
883
+ f"{source_base}"
884
+ f"_to_"
885
+ f"{target_base}"
886
+ f".webp"
887
+ )
888
 
 
889
 
890
+ result_image.save(
891
 
 
892
  output_path,
893
+
894
  format="WEBP",
895
+
896
  quality=90,
897
+
898
  method=6
899
  )
900
 
901
+
902
+ output_paths.append(
903
+ output_path
904
+ )
905
+
906
+
907
+ print(
908
+ "DONE:",
909
+ output_paths
910
+ )
911
+
912
 
913
  return output_paths
914
 
915
+
916
+ # ============================================================
917
  # GRADIO UI
918
+ # ============================================================
919
 
920
+ with gr.Blocks(
921
+ title="CPU Face Swap"
922
+ ) as app:
923
 
924
 
925
+ gr.Markdown(
926
+ """
927
+ # CPU Face Swap
928
+
929
+ 1. Upload **Source Face**
930
+ 2. Upload **Target Image/GIF**
931
+ 3. Click **Preview Face Index**
932
+ 4. Chọn `FACE 0`, `FACE 1`, ...
933
+ 5. Chọn Swap Model
934
+ 6. Click **Generate**
935
+ """
936
+ )
937
+
938
+
939
+ # ========================================================
940
+ # FILE INPUT
941
+ # ========================================================
942
+
943
+ source_files = gr.File(
944
+
945
+ label="Source Faces",
946
+
947
+ file_count="multiple",
948
+
949
+ type="filepath",
950
+
951
+ interactive=True
952
+ )
953
+
954
+
955
+ target_files = gr.File(
956
+
957
+ label="Target Images / GIFs",
958
+
959
+ file_count="multiple",
960
+
961
+ type="filepath",
962
+
963
+ interactive=True
964
+ )
965
+
966
+
967
+ # ========================================================
968
+ # PREVIEW
969
+ # ========================================================
970
+
971
+ preview_btn = gr.Button(
972
+ "Preview Face Index"
973
+ )
974
+
975
 
976
  preview_image = gr.Image(
977
+
978
  label="Click vào khuôn mặt muốn swap",
979
+
980
  type="numpy",
981
+
982
+ interactive=False,
983
+
984
+ height=600
985
  )
986
+
987
+
988
+ face_boxes = gr.State([])
989
+
990
+
991
  face_selector = gr.Dropdown(
992
+
993
+ choices=[],
994
+
995
+ value=None,
996
+
997
+ label="Select Face"
998
  )
999
 
1000
+
1001
+ # ========================================================
1002
+ # SWAP MODEL
1003
+ # ========================================================
1004
+
1005
  swap_model = gr.Dropdown(
1006
+
1007
+ choices=[
1008
+ "inswapper_128.onnx",
1009
+ "hyperswap_1a_256.onnx",
1010
+ "hyperswap_1b_256.onnx",
1011
+ "hyperswap_1c_256.onnx"
1012
+ ],
1013
+
1014
  value="hyperswap_1b_256.onnx",
1015
+
1016
  label="Swap Model"
1017
  )
1018
 
1019
+
1020
+ # ========================================================
1021
+ # RESTORE
1022
+ # ========================================================
1023
+
1024
  face_restore_model = gr.Dropdown(
1025
+
1026
+ choices=[
1027
+ "none",
1028
+ "GPEN-BFR-512.onnx"
1029
+ ],
1030
+
1031
  value="none",
1032
+
1033
  label="Face Restore Model"
1034
  )
1035
 
 
 
1036
 
1037
+ restore_strength = gr.Slider(
1038
+
1039
+ minimum=0,
1040
+
1041
+ maximum=1,
1042
+
1043
+ value=0.7,
1044
+
1045
+ step=0.05,
1046
+
1047
+ label="Restore Strength"
1048
+ )
1049
+
1050
+
1051
+ # ========================================================
1052
+ # GENERATE
1053
+ # ========================================================
1054
+
1055
+ generate_btn = gr.Button(
1056
+ "Generate",
1057
+ variant="primary"
1058
+ )
1059
+
1060
+
1061
+ output_files = gr.Files(
1062
+ label="Output WebPs"
1063
+ )
1064
+
1065
+
1066
+ # ========================================================
1067
+ # EVENTS
1068
+ # ========================================================
1069
 
1070
  preview_btn.click(
1071
+
1072
+ fn=update_face_selector,
1073
+
1074
+ inputs=[
1075
+ target_files
1076
+ ],
1077
+
1078
+ outputs=[
1079
+ preview_image,
1080
+ face_boxes,
1081
+ face_selector
1082
+ ]
1083
  )
1084
 
1085
 
 
1086
  generate_btn.click(
1087
+
1088
  fn=generate_image,
1089
+
1090
  inputs=[
 
 
 
 
 
 
 
1091
 
1092
+ source_files,
1093
+
1094
+ target_files,
1095
+
1096
+ face_selector,
1097
+
1098
+ swap_model,
1099
+
1100
+ face_restore_model,
1101
+
1102
+ restore_strength
1103
+
1104
+ ],
1105
+
1106
+ outputs=[
1107
+ output_files
1108
+ ]
1109
+ )
1110
 
1111
 
1112
+ # ============================================================
1113
+ # LAUNCH
1114
+ # ============================================================
1115
 
1116
+ app.launch(
1117
+ share=True
1118
+ )