mr2along commited on
Commit
feca4bf
·
verified ·
1 Parent(s): 7692141

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1675 -2035
app.py CHANGED
@@ -1,25 +1,29 @@
1
  import os
2
 
3
  # ============================================================
4
- # FORCE CPU - MUST BE BEFORE TORCH IMPORT
 
 
5
  # ============================================================
6
 
7
  os.environ["CUDA_VISIBLE_DEVICES"] = ""
8
  os.environ["PYTORCH_CUDA_ALLOC_CONF"] = ""
 
 
 
 
 
9
 
10
  import sys
11
  import asyncio
12
- import tempfile
13
- import threading
14
  import gc
15
- import re
16
- import traceback
17
-
18
  import imageio
 
 
 
19
  import numpy as np
20
- import torch
21
- import gradio as gr
22
  import cv2
 
23
 
24
  from PIL import Image
25
  from huggingface_hub import hf_hub_download
@@ -29,56 +33,162 @@ from huggingface_hub import hf_hub_download
29
  # CONFIG
30
  # ============================================================
31
 
32
- APP_TITLE = "CPU Multi Face Swap"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- OUTPUT_DIR = "/app/output"
35
- MODEL_DIR = "/app/models"
 
 
36
 
37
- DEFAULT_SWAP_MODEL = "inswapper_128.onnx"
38
- DEFAULT_RESTORE_MODEL = "GPEN-BFR-512.onnx"
 
 
39
 
40
- DETECTION_SIZE = (640, 640)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- FORCE_CPU = True
43
 
44
- PROCESS_LOCK = threading.Lock()
 
 
45
 
46
- FACE_CACHE = {}
47
 
48
- REACTOR_NODE = None
 
 
 
49
 
 
 
 
 
 
50
 
51
  # ============================================================
52
- # REACTOR PATHS
53
  # ============================================================
54
 
55
- REACTOR_PATHS = [
56
- "/app/custom_nodes/comfyui-reactor-node",
57
- "/app/custom_nodes/ComfyUI-ReActor",
58
  os.path.join(
59
- os.getcwd(),
60
  "custom_nodes",
61
  "comfyui-reactor-node"
62
  ),
 
 
 
63
  os.path.join(
64
  os.getcwd(),
65
  "custom_nodes",
66
- "ComfyUI-ReActor"
67
  ),
68
  ]
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
  # ============================================================
72
- # DIRECTORIES
73
  # ============================================================
74
 
 
 
 
 
 
75
  os.makedirs(
76
  OUTPUT_DIR,
77
  exist_ok=True
78
  )
79
 
80
  os.makedirs(
81
- MODEL_DIR,
 
 
 
 
 
 
 
 
 
 
82
  exist_ok=True
83
  )
84
 
@@ -87,664 +197,792 @@ os.makedirs(
87
  # LOG
88
  # ============================================================
89
 
90
- def log(*args):
91
- print(
92
- *args,
93
- flush=True
94
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
 
97
  # ============================================================
98
  # MODEL DOWNLOAD
99
  # ============================================================
100
 
101
- def download_if_not_exists(
102
- repo,
103
- filename,
104
- local_dir
105
  ):
106
- """
107
- Download model only if missing.
108
 
109
- Supports filenames containing subdirectories.
110
- """
111
 
112
- os.makedirs(
113
- local_dir,
114
- exist_ok=True
 
 
 
 
 
115
  )
116
 
117
- local_path = os.path.abspath(
118
- os.path.join(
119
- local_dir,
120
  filename
121
  )
122
  )
123
 
124
- if (
125
- os.path.isfile(local_path)
126
- and os.path.getsize(local_path) > 0
 
 
 
127
  ):
128
- log(
129
- "[MODEL] Ready:",
 
130
  local_path
131
  )
 
132
  return local_path
133
 
134
  os.makedirs(
135
- os.path.dirname(local_path),
136
  exist_ok=True
137
  )
138
 
139
- log("=" * 70)
140
- log("[MODEL] Downloading:", filename)
141
- log("[MODEL] Repository:", repo)
142
- log("[MODEL] Destination:", local_path)
143
- log("=" * 70)
144
-
145
- downloaded = hf_hub_download(
146
- repo_id=repo,
147
- filename=filename,
148
- local_dir=local_dir
149
  )
150
 
151
- if (
152
- downloaded
153
- and os.path.isfile(downloaded)
154
- and os.path.getsize(downloaded) > 0
155
- ):
156
- log(
157
- "[MODEL] Ready:",
158
- downloaded
159
- )
160
- return downloaded
161
-
162
- if (
163
- os.path.isfile(local_path)
164
- and os.path.getsize(local_path) > 0
165
- ):
166
- return local_path
167
-
168
- raise RuntimeError(
169
- "Model download failed: "
170
- + filename
171
  )
172
 
173
-
174
- # ============================================================
175
- # REQUIRED MODELS
176
- # NO HYPERSWAP
177
- # ============================================================
178
-
179
- INSWAPPER_PATH = download_if_not_exists(
180
- "ezioruan/inswapper_128.onnx",
181
- "inswapper_128.onnx",
182
- os.path.join(
183
- MODEL_DIR,
184
- "insightface"
185
  )
186
- )
187
-
188
- GPEN_PATH = download_if_not_exists(
189
- "martintomov/comfy",
190
- "facerestore_models/GPEN-BFR-512.onnx",
191
- MODEL_DIR
192
- )
193
 
194
- log(
195
- "[MODEL] INSWAPPER:",
196
- INSWAPPER_PATH
197
- )
198
 
199
- log(
200
- "[MODEL] GPEN:",
201
- GPEN_PATH
202
- )
203
 
 
 
 
 
 
204
 
205
- # ============================================================
206
- # FIND PATH
207
- # ============================================================
208
 
209
- def find_path(
210
- name,
211
- start=None,
212
- max_depth=8
213
- ):
214
- """
215
- Search locally and upward.
216
- """
217
 
218
- if start is None:
219
- start = os.getcwd()
 
 
220
 
221
- start = os.path.abspath(
222
- start
223
- )
224
 
225
- direct = os.path.join(
226
- start,
227
- name
228
- )
229
 
230
- if os.path.exists(direct):
231
- return direct
 
232
 
233
- current = start
234
 
235
- for _ in range(max_depth):
 
 
 
236
 
237
- candidate = os.path.join(
238
- current,
239
- name
240
- )
241
 
242
- if os.path.exists(candidate):
243
- return candidate
 
244
 
245
- parent = os.path.dirname(
246
- current
 
247
  )
248
 
249
- if parent == current:
250
- break
251
-
252
- current = parent
253
 
254
- return None
255
 
256
 
257
  # ============================================================
258
- # FIND COMFYUI
259
  # ============================================================
260
 
261
- def add_comfyui_directory_to_sys_path():
262
 
263
- candidates = [
264
- "/app/ComfyUI",
265
- "/ComfyUI",
266
- os.path.join(
267
- os.getcwd(),
268
- "ComfyUI"
269
- )
270
- ]
271
 
272
- for candidate in candidates:
 
 
273
 
274
- if (
275
- os.path.isdir(candidate)
276
- and os.path.isfile(
277
- os.path.join(
278
- candidate,
279
- "nodes.py"
280
- )
281
- )
282
- ):
283
 
284
- if candidate not in sys.path:
285
- sys.path.insert(
286
- 0,
287
- candidate
288
- )
289
 
290
- log(
291
- "[COMFYUI] Path:",
292
- candidate
293
- )
294
 
295
- return candidate
296
 
297
- found = find_path(
298
- "ComfyUI",
299
- os.getcwd(),
300
- 8
301
  )
302
 
303
- if (
304
- found
305
- and os.path.isdir(found)
306
  ):
307
 
308
- if found not in sys.path:
309
- sys.path.insert(
310
- 0,
311
- found
312
- )
313
-
314
- log(
315
- "[COMFYUI] Path:",
316
- found
317
  )
318
 
319
- return found
320
-
321
- raise RuntimeError(
322
- "Không tìm thấy ComfyUI."
323
- )
324
-
325
 
326
- COMFYUI_PATH = (
327
- add_comfyui_directory_to_sys_path()
328
- )
329
 
330
 
331
  # ============================================================
332
- # EXTRA MODEL PATHS
333
  # ============================================================
334
 
335
- def add_extra_model_paths():
336
-
337
- try:
338
-
339
- from main import load_extra_path_config
340
 
341
- except ImportError:
 
342
 
343
- try:
 
 
 
344
 
345
- from utils.extra_config import (
346
- load_extra_path_config
347
- )
 
 
348
 
349
- except ImportError:
 
 
 
350
 
351
- log(
352
- "[COMFYUI] Extra path loader unavailable."
353
- )
 
354
 
355
- return
 
 
 
 
356
 
357
- extra_paths = find_path(
358
- "extra_model_paths.yaml",
359
- os.getcwd(),
360
- 8
 
361
  )
362
 
363
- if extra_paths:
 
 
 
 
 
364
 
365
- try:
 
 
 
366
 
367
- load_extra_path_config(
368
- extra_paths
369
- )
370
 
371
- log(
372
- "[COMFYUI] Extra model paths:",
373
- extra_paths
374
- )
375
 
376
- except Exception as e:
 
 
377
 
378
- log(
379
- "[COMFYUI] Extra path error:",
380
- repr(e)
381
- )
382
 
 
383
 
384
- add_extra_model_paths()
 
 
385
 
 
386
 
387
- # ============================================================
388
- # FORCE COMFY CPU
389
- # ============================================================
390
 
391
- try:
392
 
393
- import comfy.model_management
 
 
394
 
395
- try:
396
 
397
- from comfy.model_management import CPUState
398
 
399
- comfy.model_management.cpu_state = (
400
- CPUState.CPU
401
- )
402
 
403
- except Exception as e:
404
 
405
- log(
406
- "[DEVICE] CPUState warning:",
407
- repr(e)
408
  )
409
 
410
- log(
411
- "[DEVICE] Forced CPU"
412
- )
413
 
414
- except Exception as e:
415
 
416
- log(
417
- "[DEVICE] Could not force Comfy CPU:",
418
- repr(e)
419
- )
420
 
421
 
422
  # ============================================================
423
- # LOAD CUSTOM NODES
424
  # ============================================================
425
 
426
- def import_custom_nodes():
427
-
428
- import execution
429
 
430
- from nodes import init_extra_nodes
431
 
432
- log(
433
- "[COMFYUI] Loading custom nodes..."
 
 
 
 
 
 
 
 
 
 
434
  )
435
 
436
- try:
437
-
438
- loop = asyncio.get_event_loop()
439
 
440
- if loop.is_closed():
441
 
442
- loop = asyncio.new_event_loop()
 
 
 
 
 
 
 
 
443
 
444
- asyncio.set_event_loop(
445
- loop
 
 
 
 
 
 
 
 
 
 
 
 
 
 
446
  )
 
 
 
447
 
448
- except Exception:
449
 
450
- loop = asyncio.new_event_loop()
 
 
 
 
 
 
451
 
452
- asyncio.set_event_loop(
453
- loop
 
 
 
 
454
  )
 
455
 
456
- try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
457
 
458
- if asyncio.iscoroutinefunction(
459
- init_extra_nodes
 
 
 
 
 
 
 
 
460
  ):
461
 
462
- loop.run_until_complete(
463
- init_extra_nodes()
464
- )
465
 
466
- else:
467
 
468
- init_extra_nodes()
469
 
470
- except Exception:
 
 
471
 
472
- log(
473
- "[COMFYUI] Custom node loading warning:"
 
 
474
  )
475
 
476
- traceback.print_exc()
477
 
478
- log(
479
- "[COMFYUI] Custom nodes loaded."
 
480
  )
481
 
 
482
 
483
- import_custom_nodes()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
484
 
485
 
486
  # ============================================================
487
- # NODE MAPPINGS
488
  # ============================================================
489
 
490
- from nodes import NODE_CLASS_MAPPINGS
491
 
 
492
 
493
- if "ReActorFaceSwap" not in NODE_CLASS_MAPPINGS:
 
 
494
 
495
- raise RuntimeError(
496
- "Không tìm thấy ReActorFaceSwap node.\n"
497
- "Kiểm tra ComfyUI-ReActor."
498
- )
499
 
 
 
 
500
 
501
- REACTOR_NODE = (
502
- NODE_CLASS_MAPPINGS[
503
- "ReActorFaceSwap"
504
- ]()
505
  )
506
 
507
 
508
  # ============================================================
509
- # FIND REACTOR DIRECTORY
510
  # ============================================================
511
 
512
- REACTOR_PATH = None
513
 
514
- for candidate in REACTOR_PATHS:
515
 
516
- if os.path.isdir(candidate):
 
 
517
 
518
- REACTOR_PATH = candidate
519
 
520
- break
 
 
521
 
 
522
 
523
- if REACTOR_PATH is None:
 
 
524
 
525
- raise RuntimeError(
526
- "Không tìm thấy ComfyUI-ReActor.\n\n"
527
- "Expected:\n"
528
- + "\n".join(
529
- REACTOR_PATHS
 
 
530
  )
531
  )
532
 
 
 
 
533
 
534
- if REACTOR_PATH not in sys.path:
 
 
535
 
536
- sys.path.insert(
537
- 0,
538
- REACTOR_PATH
 
 
 
539
  )
540
 
 
 
 
541
 
542
- log(
543
- "[REACTOR] Path:",
544
- REACTOR_PATH
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
545
  )
546
 
547
 
548
  # ============================================================
549
- # REACTOR FACE FUNCTIONS
550
  # ============================================================
551
 
552
- from scripts.reactor_swapper import (
553
- analyze_faces,
554
- sort_by_order
555
  )
556
 
557
 
558
  # ============================================================
559
- # SAFE VALUE EXTRACTION
560
  # ============================================================
561
 
562
  def get_value_at_index(
563
  obj,
564
- index=0
565
  ):
566
 
567
- if obj is None:
568
- return None
569
-
570
- if isinstance(
571
- obj,
572
- (tuple, list)
573
- ):
574
-
575
- if not obj:
576
- return None
577
-
578
- try:
579
-
580
- return obj[index]
581
 
582
- except Exception:
583
 
584
- return obj[0]
 
 
585
 
586
- if isinstance(
587
- obj,
588
- dict
 
589
  ):
590
 
591
- if not obj:
592
- return None
593
-
594
- keys = list(
595
- obj.keys()
596
- )
597
 
598
- if index < len(keys):
 
 
599
 
600
- return obj[
601
- keys[index]
602
  ]
603
 
604
- return obj[
605
- keys[0]
606
- ]
607
-
608
- return obj
609
 
610
 
611
  # ============================================================
612
- # FILE HELPERS
613
  # ============================================================
614
 
615
- def get_file_path(
616
- file
617
- ):
618
-
619
- if file is None:
620
- return None
621
 
622
- if isinstance(
623
- file,
624
- str
625
  ):
626
 
627
- return file
628
-
629
- if hasattr(
630
- file,
631
- "path"
632
- ):
633
 
634
- return file.path
635
 
636
- if hasattr(
637
- file,
638
- "name"
639
- ):
640
 
641
- return file.name
642
 
643
- return str(file)
 
 
 
 
 
 
 
644
 
645
 
646
- def get_file_paths(
647
- files
648
- ):
649
 
650
- if files is None:
651
- return []
 
 
652
 
653
- if isinstance(
654
- files,
655
- str
656
- ):
657
 
658
- files = [
659
- files
660
- ]
 
661
 
662
- result = []
663
 
664
- for file in files:
 
 
665
 
666
- path = get_file_path(
667
- file
668
- )
669
 
670
- if (
671
- path
672
- and os.path.isfile(path)
673
- ):
 
674
 
675
- result.append(
676
- path
677
- )
678
 
679
- return result
 
 
 
 
680
 
681
 
682
  # ============================================================
683
- # LOAD IMAGE DIRECTLY
684
- # Do NOT use Comfy LoadImage.
685
- # Gradio files may be outside ComfyUI/input.
686
  # ============================================================
687
 
688
- def load_image_tensor(
689
- path
690
- ):
691
 
692
- if not path:
 
 
 
 
693
 
694
- raise RuntimeError(
695
- "Image path rỗng."
696
- )
697
 
698
- if not os.path.isfile(path):
 
 
 
 
699
 
700
- raise RuntimeError(
701
- "Không tìm thấy image: "
702
- + path
703
- )
704
 
705
- image = Image.open(
706
- path
707
- ).convert(
708
- "RGB"
709
- )
710
 
711
- array = np.asarray(
712
- image,
713
- dtype=np.float32
714
- )
715
 
716
- array = (
717
- array / 255.0
718
- )
 
 
719
 
720
- tensor = torch.from_numpy(
721
- array
 
722
  )
723
 
724
- # ComfyUI IMAGE format:
725
- # [B, H, W, C]
726
 
727
- tensor = tensor.unsqueeze(
728
- 0
 
 
729
  )
730
 
731
- return tensor
732
-
733
 
734
  # ============================================================
735
- # FACE DETECTION
736
  # ============================================================
737
 
 
 
 
 
 
 
 
 
 
 
 
 
738
  def detect_reactor_faces(
739
  image_path
740
  ):
741
 
742
  if not image_path:
 
743
  return []
744
 
745
  if not os.path.isfile(
746
  image_path
747
  ):
 
748
  return []
749
 
750
  try:
@@ -755,74 +993,169 @@ def detect_reactor_faces(
755
 
756
  except Exception:
757
 
758
- mtime = 0
759
 
760
  cache_key = (
761
- os.path.abspath(
762
- image_path
763
- ),
764
  mtime
765
  )
766
 
767
- if cache_key in FACE_CACHE:
 
 
768
 
769
- return FACE_CACHE[
 
 
770
  cache_key
771
- ]
 
 
 
 
 
 
 
 
 
 
772
 
773
  img = cv2.imread(
774
  image_path
775
  )
776
 
777
  if img is None:
 
778
  return []
779
 
780
- try:
 
 
781
 
782
- faces = analyze_faces(
783
- img,
784
- det_size=DETECTION_SIZE
 
 
785
  )
 
786
 
787
- except Exception as e:
788
-
789
- log(
790
- "[FACE DETECT ERROR]",
791
- repr(e)
792
- )
793
 
794
  faces = []
795
 
796
- if faces is None:
797
- faces = []
 
798
 
799
- try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
800
 
801
- faces = sort_by_order(
802
- faces,
803
- "large-small"
804
  )
805
 
806
- except Exception:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
807
 
808
- faces = list(
809
- faces
810
  )
811
 
812
- FACE_CACHE[
813
- cache_key
814
- ] = faces
 
 
 
815
 
816
- return faces
 
 
 
 
817
 
818
 
819
  # ============================================================
820
- # CREATE FACE PREVIEW
821
  # ============================================================
822
 
823
- def create_face_preview(
824
- image_path,
825
- label_prefix="FACE"
826
  ):
827
 
828
  if not image_path:
@@ -837,7 +1170,9 @@ def create_face_preview(
837
 
838
  return None, []
839
 
840
- h, w = img.shape[:2]
 
 
841
 
842
  faces = detect_reactor_faces(
843
  image_path
@@ -848,21 +1183,16 @@ def create_face_preview(
848
  return None, []
849
 
850
  previews = []
 
851
  boxes = []
852
 
853
  for index, face in enumerate(
854
  faces
855
  ):
856
 
857
- try:
858
-
859
- x1, y1, x2, y2 = (
860
- face.bbox
861
- )
862
-
863
- except Exception:
864
-
865
- continue
866
 
867
  x1 = max(
868
  0,
@@ -875,22 +1205,15 @@ def create_face_preview(
875
  )
876
 
877
  x2 = min(
878
- w,
879
  int(x2)
880
  )
881
 
882
  y2 = min(
883
- h,
884
  int(y2)
885
  )
886
 
887
- if (
888
- x2 <= x1
889
- or y2 <= y1
890
- ):
891
-
892
- continue
893
-
894
  boxes.append(
895
  [
896
  x1,
@@ -900,6 +1223,10 @@ def create_face_preview(
900
  ]
901
  )
902
 
 
 
 
 
903
  fw = max(
904
  1,
905
  x2 - x1
@@ -929,12 +1256,12 @@ def create_face_preview(
929
  )
930
 
931
  cx2 = min(
932
- w,
933
  x2 + px
934
  )
935
 
936
  cy2 = min(
937
- h,
938
  y2 + py
939
  )
940
 
@@ -947,6 +1274,10 @@ def create_face_preview(
947
 
948
  continue
949
 
 
 
 
 
950
  ch, cw = (
951
  crop.shape[:2]
952
  )
@@ -978,27 +1309,55 @@ def create_face_preview(
978
  ox:ox + cw
979
  ] = crop
980
 
 
 
 
 
981
  crop = cv2.resize(
982
  square,
983
- (300, 300),
 
 
 
984
  interpolation=cv2.INTER_AREA
985
  )
986
 
 
 
 
 
987
  cv2.rectangle(
988
  crop,
989
- (0, 0),
990
- (300, 52),
991
- (0, 255, 0),
 
 
 
 
 
 
 
 
 
 
992
  -1
993
  )
994
 
995
  cv2.putText(
996
  crop,
997
- f"{label_prefix} {index}",
998
- (12, 36),
 
 
 
999
  cv2.FONT_HERSHEY_SIMPLEX,
1000
- 0.85,
1001
- (0, 0, 0),
 
 
 
 
1002
  2,
1003
  cv2.LINE_AA
1004
  )
@@ -1016,46 +1375,18 @@ def create_face_preview(
1016
 
1017
  return None, []
1018
 
1019
- columns = min(
1020
- 4,
1021
- len(previews)
1022
- )
1023
-
1024
- rows = int(
1025
- np.ceil(
1026
- len(previews) / columns
1027
- )
1028
- )
1029
-
1030
- canvas = np.ones(
1031
- (
1032
- rows * 300,
1033
- columns * 300,
1034
- 3
1035
- ),
1036
- dtype=np.uint8
1037
- ) * 35
1038
-
1039
- for i, preview in enumerate(
1040
  previews
1041
- ):
1042
-
1043
- row = i // columns
1044
- col = i % columns
1045
-
1046
- canvas[
1047
- row * 300:(row + 1) * 300,
1048
- col * 300:(col + 1) * 300
1049
- ] = preview
1050
 
1051
  return (
1052
- canvas,
1053
  boxes
1054
  )
1055
 
1056
 
1057
  # ============================================================
1058
- # GIF FIRST FRAME
1059
  # ============================================================
1060
 
1061
  def get_preview_image(
@@ -1066,32 +1397,27 @@ def get_preview_image(
1066
 
1067
  return None, []
1068
 
1069
- if not target_path.lower().endswith(
 
 
 
 
1070
  ".gif"
1071
  ):
1072
 
1073
- return create_face_preview(
1074
- target_path,
1075
- "TARGET FACE"
1076
  )
1077
 
1078
- reader = imageio.get_reader(
1079
- target_path
1080
- )
1081
-
1082
- temp_path = None
1083
-
1084
- try:
1085
-
1086
- frame = reader.get_data(
1087
- 0
1088
- )
1089
 
1090
- finally:
 
 
1091
 
1092
- reader.close()
1093
 
1094
- try:
1095
 
1096
  with tempfile.NamedTemporaryFile(
1097
  suffix=".png",
@@ -1100,27 +1426,19 @@ def get_preview_image(
1100
 
1101
  temp_path = tmp.name
1102
 
1103
- Image.fromarray(
1104
- frame
1105
- ).convert(
1106
- "RGB"
1107
- ).save(
1108
- temp_path
1109
- )
1110
-
1111
- return create_face_preview(
1112
- temp_path,
1113
- "TARGET FACE"
1114
- )
1115
 
1116
- finally:
 
 
 
 
1117
 
1118
- if (
1119
- temp_path
1120
- and os.path.exists(
1121
  temp_path
1122
  )
1123
- ):
 
1124
 
1125
  try:
1126
 
@@ -1132,92 +1450,57 @@ def get_preview_image(
1132
 
1133
  pass
1134
 
 
 
 
1135
 
1136
- # ============================================================
1137
- # SOURCE IMAGE SELECTOR
1138
- # ============================================================
1139
-
1140
- def update_source_image_selector(
1141
- source_files
1142
- ):
1143
-
1144
- paths = get_file_paths(
1145
- source_files
1146
- )
1147
-
1148
- choices = [
1149
- f"{i}: {os.path.basename(path)}"
1150
- for i, path in enumerate(
1151
- paths
1152
- )
1153
- ]
1154
-
1155
- return gr.update(
1156
- choices=choices,
1157
- value=(
1158
- choices[0]
1159
- if choices
1160
- else None
1161
- )
1162
  )
1163
 
1164
 
1165
  # ============================================================
1166
- # SHOW SELECTED SOURCE
1167
  # ============================================================
1168
 
1169
- def show_selected_source(
1170
- source_files,
1171
- selected_source
1172
  ):
1173
 
1174
  paths = get_file_paths(
1175
- source_files
1176
  )
1177
 
1178
  if not paths:
1179
 
1180
  return (
1181
  None,
 
1182
  gr.update(
1183
  choices=[],
1184
  value=None
1185
  )
1186
  )
1187
 
1188
- index = 0
1189
-
1190
- if selected_source:
1191
-
1192
- try:
1193
-
1194
- index = int(
1195
- str(
1196
- selected_source
1197
- ).split(":")[0]
1198
- )
1199
-
1200
- except Exception:
1201
-
1202
- index = 0
1203
-
1204
- index = max(
1205
- 0,
1206
- min(
1207
- index,
1208
- len(paths) - 1
1209
  )
1210
  )
1211
 
1212
- preview, boxes = (
1213
- create_face_preview(
1214
- paths[index],
1215
- f"SOURCE {index}"
 
 
 
 
 
1216
  )
1217
- )
1218
 
1219
  choices = [
1220
- f"SOURCE {index} / FACE {i}"
1221
  for i in range(
1222
  len(boxes)
1223
  )
@@ -1225,697 +1508,50 @@ def show_selected_source(
1225
 
1226
  return (
1227
  preview,
 
1228
  gr.update(
1229
  choices=choices,
1230
- value=(
1231
- choices[0]
1232
- if choices
1233
- else None
1234
- )
1235
  )
1236
  )
1237
 
1238
 
1239
  # ============================================================
1240
- # TARGET SELECTOR
1241
  # ============================================================
1242
 
1243
- def update_target_selector(
1244
- target_files
1245
  ):
1246
 
1247
- paths = get_file_paths(
1248
- target_files
1249
- )
1250
 
1251
- choices = [
1252
- f"{i}: {os.path.basename(path)}"
1253
- for i, path in enumerate(
1254
- paths
1255
- )
1256
- ]
1257
 
1258
- return gr.update(
1259
- choices=choices,
1260
- value=(
1261
- choices[0]
1262
- if choices
1263
- else None
1264
  )
 
 
 
1265
  )
1266
 
 
1267
 
1268
- # ============================================================
1269
- # SHOW SELECTED TARGET
1270
- # ============================================================
1271
 
1272
- def show_selected_target(
1273
- target_files,
1274
- selected_target
1275
- ):
1276
-
1277
- paths = get_file_paths(
1278
- target_files
1279
- )
1280
-
1281
- if not paths:
1282
-
1283
- return (
1284
- None,
1285
- gr.update(
1286
- choices=[],
1287
- value=None
1288
- )
1289
- )
1290
-
1291
- index = 0
1292
-
1293
- if selected_target:
1294
-
1295
- try:
1296
-
1297
- index = int(
1298
- str(
1299
- selected_target
1300
- ).split(":")[0]
1301
- )
1302
-
1303
- except Exception:
1304
-
1305
- index = 0
1306
-
1307
- index = max(
1308
- 0,
1309
- min(
1310
- index,
1311
- len(paths) - 1
1312
- )
1313
- )
1314
-
1315
- preview, boxes = (
1316
- get_preview_image(
1317
- paths[index]
1318
- )
1319
- )
1320
-
1321
- choices = [
1322
- f"FACE {i}"
1323
- for i in range(
1324
- len(boxes)
1325
- )
1326
- ]
1327
-
1328
- return (
1329
- preview,
1330
- gr.update(
1331
- choices=choices,
1332
- value=(
1333
- choices[0]
1334
- if choices
1335
- else None
1336
- )
1337
- )
1338
- )
1339
-
1340
-
1341
- # ============================================================
1342
- # PARSE SOURCE SELECTION
1343
- # ============================================================
1344
-
1345
- def parse_source_selection(
1346
- value
1347
- ):
1348
-
1349
- if value is None:
1350
- return 0, 0
1351
-
1352
- text = str(
1353
- value
1354
- )
1355
-
1356
- try:
1357
-
1358
- if "/" in text:
1359
-
1360
- left, right = (
1361
- text.split(
1362
- "/",
1363
- 1
1364
- )
1365
- )
1366
-
1367
- source_match = re.search(
1368
- r"\d+",
1369
- left
1370
- )
1371
-
1372
- face_match = re.search(
1373
- r"\d+",
1374
- right
1375
- )
1376
-
1377
- if (
1378
- source_match
1379
- and face_match
1380
- ):
1381
-
1382
- return (
1383
- int(
1384
- source_match.group()
1385
- ),
1386
- int(
1387
- face_match.group()
1388
- )
1389
- )
1390
-
1391
- except Exception:
1392
-
1393
- pass
1394
-
1395
- nums = re.findall(
1396
- r"\d+",
1397
- text
1398
- )
1399
-
1400
- if len(nums) >= 2:
1401
-
1402
- return (
1403
- int(nums[0]),
1404
- int(nums[1])
1405
- )
1406
-
1407
- return 0, 0
1408
-
1409
-
1410
- # ============================================================
1411
- # PARSE TARGET FACE
1412
- # ============================================================
1413
-
1414
- def parse_target_face(
1415
- value
1416
- ):
1417
-
1418
- if value is None:
1419
- return 0
1420
-
1421
- nums = re.findall(
1422
- r"\d+",
1423
- str(value)
1424
- )
1425
-
1426
- if not nums:
1427
- return 0
1428
-
1429
- return int(
1430
- nums[-1]
1431
- )
1432
-
1433
-
1434
- # ============================================================
1435
- # PARSE TARGET IMAGE
1436
- # ============================================================
1437
-
1438
- def parse_target_image(
1439
- value
1440
- ):
1441
-
1442
- if value is None:
1443
- return 0
1444
-
1445
- nums = re.findall(
1446
- r"\d+",
1447
- str(value)
1448
- )
1449
-
1450
- if not nums:
1451
- return 0
1452
-
1453
- return int(
1454
- nums[0]
1455
- )
1456
-
1457
-
1458
- # ============================================================
1459
- # ADD MAPPING
1460
- # ============================================================
1461
-
1462
- def add_mapping(
1463
- current_mapping,
1464
- source_selection,
1465
- target_selection,
1466
- target_image_selection
1467
- ):
1468
-
1469
- if not source_selection:
1470
-
1471
- raise gr.Error(
1472
- "Hãy chọn Source Face."
1473
- )
1474
-
1475
- if not target_selection:
1476
-
1477
- raise gr.Error(
1478
- "Hãy chọn Target Face."
1479
- )
1480
-
1481
- source_image_index, source_face_index = (
1482
- parse_source_selection(
1483
- source_selection
1484
- )
1485
- )
1486
-
1487
- target_image_index = (
1488
- parse_target_image(
1489
- target_image_selection
1490
- )
1491
- )
1492
-
1493
- target_face_index = (
1494
- parse_target_face(
1495
- target_selection
1496
- )
1497
- )
1498
-
1499
- line = (
1500
- f"SOURCE {source_image_index} "
1501
- f"FACE {source_face_index} "
1502
- f"-> TARGET {target_image_index} "
1503
- f"FACE {target_face_index}"
1504
- )
1505
-
1506
- current = (
1507
- str(
1508
- current_mapping
1509
- ).strip()
1510
- if current_mapping
1511
- else ""
1512
- )
1513
-
1514
- if current:
1515
-
1516
- return (
1517
- current
1518
- + "\n"
1519
- + line
1520
- )
1521
-
1522
- return line
1523
-
1524
-
1525
- # ============================================================
1526
- # REMOVE LAST MAPPING
1527
- # ============================================================
1528
-
1529
- def remove_last_mapping(
1530
- current_mapping
1531
- ):
1532
-
1533
- if not current_mapping:
1534
- return ""
1535
-
1536
- lines = [
1537
- x.strip()
1538
- for x in str(
1539
- current_mapping
1540
- ).splitlines()
1541
- if x.strip()
1542
- ]
1543
-
1544
- if not lines:
1545
- return ""
1546
-
1547
- return "\n".join(
1548
- lines[:-1]
1549
- )
1550
-
1551
-
1552
- # ============================================================
1553
- # CLEAR MAPPING
1554
- # ============================================================
1555
-
1556
- def clear_mapping():
1557
-
1558
- return ""
1559
-
1560
-
1561
- # ============================================================
1562
- # DEFAULT MAPPING
1563
- # ============================================================
1564
-
1565
- def default_mapping():
1566
-
1567
- return (
1568
- "SOURCE 0 FACE 0 "
1569
- "-> TARGET 0 FACE 0"
1570
- )
1571
-
1572
-
1573
- # ============================================================
1574
- # BUILD MAPPING
1575
- # ============================================================
1576
-
1577
- def build_mapping(
1578
- source_files,
1579
- target_files,
1580
- mapping_text
1581
- ):
1582
-
1583
- source_paths = get_file_paths(
1584
- source_files
1585
- )
1586
-
1587
- target_paths = get_file_paths(
1588
- target_files
1589
- )
1590
-
1591
- if not source_paths:
1592
-
1593
- raise gr.Error(
1594
- "Chưa upload Source Face."
1595
- )
1596
-
1597
- if not target_paths:
1598
-
1599
- raise gr.Error(
1600
- "Chưa upload Target."
1601
- )
1602
-
1603
- if (
1604
- not mapping_text
1605
- or not str(mapping_text).strip()
1606
- ):
1607
-
1608
- raise gr.Error(
1609
- "Chưa có mapping."
1610
- )
1611
-
1612
- mappings = []
1613
-
1614
- for line_number, raw_line in enumerate(
1615
- str(
1616
- mapping_text
1617
- ).splitlines(),
1618
- start=1
1619
- ):
1620
-
1621
- line = raw_line.strip()
1622
-
1623
- if not line:
1624
- continue
1625
-
1626
- try:
1627
-
1628
- if "->" in line:
1629
-
1630
- left, right = (
1631
- line.split(
1632
- "->",
1633
- 1
1634
- )
1635
- )
1636
-
1637
- elif "=" in line:
1638
-
1639
- left, right = (
1640
- line.split(
1641
- "=",
1642
- 1
1643
- )
1644
- )
1645
-
1646
- else:
1647
-
1648
- log(
1649
- "[MAPPING] Invalid line:",
1650
- line
1651
- )
1652
-
1653
- continue
1654
-
1655
- left_upper = left.upper()
1656
- right_upper = right.upper()
1657
-
1658
- # ------------------------------------------------
1659
- # SOURCE IMAGE
1660
- # ------------------------------------------------
1661
-
1662
- source_match = re.search(
1663
- r"SOURCE\s*(\d+)",
1664
- left_upper
1665
- )
1666
-
1667
- if source_match:
1668
-
1669
- source_image_index = int(
1670
- source_match.group(1)
1671
- )
1672
-
1673
- else:
1674
-
1675
- left_nums = re.findall(
1676
- r"\d+",
1677
- left
1678
- )
1679
-
1680
- if len(left_nums) >= 2:
1681
-
1682
- source_image_index = int(
1683
- left_nums[0]
1684
- )
1685
-
1686
- elif len(left_nums) == 1:
1687
-
1688
- source_image_index = 0
1689
-
1690
- else:
1691
-
1692
- continue
1693
-
1694
- # ------------------------------------------------
1695
- # SOURCE FACE
1696
- # ------------------------------------------------
1697
-
1698
- face_match = re.search(
1699
- r"FACE\s*(\d+)",
1700
- left_upper
1701
- )
1702
-
1703
- if face_match:
1704
-
1705
- source_face_index = int(
1706
- face_match.group(1)
1707
- )
1708
-
1709
- else:
1710
-
1711
- left_nums = re.findall(
1712
- r"\d+",
1713
- left
1714
- )
1715
-
1716
- if len(left_nums) >= 2:
1717
-
1718
- source_face_index = int(
1719
- left_nums[-1]
1720
- )
1721
-
1722
- else:
1723
-
1724
- source_face_index = 0
1725
-
1726
- # ------------------------------------------------
1727
- # TARGET IMAGE
1728
- # ------------------------------------------------
1729
-
1730
- target_match = re.search(
1731
- r"TARGET\s*(\d+)",
1732
- right_upper
1733
- )
1734
-
1735
- right_nums = re.findall(
1736
- r"\d+",
1737
- right
1738
- )
1739
-
1740
- if target_match:
1741
-
1742
- target_image_index = int(
1743
- target_match.group(1)
1744
- )
1745
-
1746
- elif len(right_nums) >= 2:
1747
-
1748
- target_image_index = int(
1749
- right_nums[0]
1750
- )
1751
-
1752
- elif len(right_nums) == 1:
1753
-
1754
- target_image_index = 0
1755
-
1756
- else:
1757
-
1758
- continue
1759
-
1760
- # ------------------------------------------------
1761
- # TARGET FACE
1762
- # ------------------------------------------------
1763
-
1764
- target_face_match = re.search(
1765
- r"FACE\s*(\d+)",
1766
- right_upper
1767
- )
1768
-
1769
- if target_face_match:
1770
-
1771
- target_face_index = int(
1772
- target_face_match.group(1)
1773
- )
1774
-
1775
- elif len(right_nums) >= 2:
1776
-
1777
- target_face_index = int(
1778
- right_nums[-1]
1779
- )
1780
-
1781
- elif len(right_nums) == 1:
1782
-
1783
- target_face_index = int(
1784
- right_nums[0]
1785
- )
1786
-
1787
- else:
1788
-
1789
- target_face_index = 0
1790
-
1791
- # ------------------------------------------------
1792
- # VALIDATION
1793
- # ------------------------------------------------
1794
-
1795
- if not (
1796
- 0 <= source_image_index
1797
- < len(source_paths)
1798
- ):
1799
-
1800
- log(
1801
- "[MAPPING] Skip line",
1802
- line_number,
1803
- "- invalid source image:",
1804
- source_image_index
1805
- )
1806
-
1807
- continue
1808
-
1809
- if not (
1810
- 0 <= target_image_index
1811
- < len(target_paths)
1812
- ):
1813
-
1814
- log(
1815
- "[MAPPING] Skip line",
1816
- line_number,
1817
- "- invalid target image:",
1818
- target_image_index
1819
- )
1820
-
1821
- continue
1822
-
1823
- if source_face_index < 0:
1824
- continue
1825
-
1826
- if target_face_index < 0:
1827
- continue
1828
-
1829
- mappings.append(
1830
- (
1831
- source_image_index,
1832
- source_face_index,
1833
- target_image_index,
1834
- target_face_index
1835
- )
1836
- )
1837
-
1838
- except Exception as e:
1839
-
1840
- log(
1841
- "[MAPPING] Parse error:",
1842
- line_number,
1843
- repr(e)
1844
- )
1845
-
1846
- if not mappings:
1847
-
1848
- raise gr.Error(
1849
- "Mapping không hợp lệ.\n\n"
1850
- "Ví dụ:\n"
1851
- "SOURCE 0 FACE 0 -> TARGET 0 FACE 0\n"
1852
- "SOURCE 1 FACE 0 -> TARGET 0 FACE 1"
1853
- )
1854
-
1855
- return mappings
1856
-
1857
-
1858
- # ============================================================
1859
- # CONVERT RESULT
1860
- # ============================================================
1861
-
1862
- def convert_result(
1863
- image
1864
- ):
1865
-
1866
- if isinstance(
1867
- image,
1868
- torch.Tensor
1869
- ):
1870
 
1871
  image = (
1872
- image
1873
- .detach()
1874
- .cpu()
1875
- .float()
1876
- .numpy()
1877
- )
1878
-
1879
- image = np.asarray(
1880
- image
1881
- )
1882
-
1883
- if image.ndim == 4:
1884
-
1885
- image = image[0]
1886
-
1887
- if image.ndim != 3:
1888
-
1889
- raise RuntimeError(
1890
- "Invalid image shape: "
1891
- + str(
1892
- image.shape
1893
- )
1894
- )
1895
-
1896
- # ComfyUI = BHWC
1897
- # Also support CHW.
1898
-
1899
- if (
1900
- image.shape[0] in (1, 3, 4)
1901
- and image.shape[2] not in (1, 3, 4)
1902
- ):
1903
-
1904
- image = np.transpose(
1905
- image,
1906
- (1, 2, 0)
1907
- )
1908
-
1909
- if image.size == 0:
1910
-
1911
- raise RuntimeError(
1912
- "ReActor trả về image rỗng."
1913
- )
1914
-
1915
- if image.max() <= 1.0:
1916
-
1917
- image = (
1918
- image * 255.0
1919
  )
1920
 
1921
  image = np.clip(
@@ -1926,433 +1562,293 @@ def convert_result(
1926
  np.uint8
1927
  )
1928
 
1929
- if image.shape[2] == 1:
1930
-
1931
- image = np.repeat(
1932
- image,
1933
- 3,
1934
- axis=2
1935
- )
1936
-
1937
- if image.shape[2] >= 3:
1938
-
1939
- image = image[:, :, :3]
1940
-
1941
  return image
1942
 
1943
 
1944
  # ============================================================
1945
- # SWAP ONE FACE
1946
  # ============================================================
1947
 
1948
- def swap_single_face(
1949
  source_tensor,
1950
- target_tensor,
1951
- source_face_index,
1952
- target_face_index,
1953
  swap_model,
1954
  face_restore_model,
1955
  restore_strength
1956
  ):
1957
 
1958
- log(
1959
- "--------------------------------------"
1960
  )
1961
 
1962
- log(
1963
- "[SWAP]",
1964
- "source_face=",
1965
- source_face_index,
1966
- "target_face=",
1967
- target_face_index,
1968
- "swap=",
1969
- swap_model,
1970
- "restore=",
1971
- face_restore_model
1972
  )
1973
 
1974
- result = REACTOR_NODE.execute(
1975
-
1976
- enabled=True,
1977
-
1978
- input_image=target_tensor,
1979
-
1980
- swap_model=swap_model,
1981
-
1982
- facedetection="retinaface_resnet50",
1983
-
1984
- face_restore_model=face_restore_model,
1985
-
1986
- face_restore_visibility=float(
1987
- restore_strength
1988
- ),
1989
-
1990
- codeformer_weight=0.5,
1991
-
1992
- detect_gender_input="no",
1993
-
1994
- detect_gender_source="no",
1995
-
1996
- input_faces_index=str(
1997
- target_face_index
1998
- ),
1999
-
2000
- source_faces_index=str(
2001
- source_face_index
2002
- ),
2003
-
2004
- console_log_level=1,
2005
-
2006
- source_image=source_tensor
2007
  )
2008
 
2009
- swapped = get_value_at_index(
2010
- result,
2011
- 0
2012
  )
2013
 
2014
- if swapped is None:
2015
-
2016
- raise RuntimeError(
2017
- "ReActor không trả về ảnh."
2018
- )
2019
-
2020
- swapped = convert_result(
2021
- swapped
2022
  )
2023
 
2024
- return Image.fromarray(
2025
- swapped
2026
- ).convert(
2027
- "RGB"
2028
  )
2029
 
2030
-
2031
- # ============================================================
2032
- # MULTI FACE SWAP ON ONE TARGET
2033
- # ============================================================
2034
-
2035
- def swap_target_with_mappings(
2036
- source_files,
2037
- target_path,
2038
- target_mappings,
2039
- swap_model,
2040
- face_restore_model,
2041
- restore_strength
2042
- ):
2043
-
2044
- source_paths = get_file_paths(
2045
- source_files
2046
  )
2047
 
2048
- if not source_paths:
2049
-
2050
- raise RuntimeError(
2051
- "Không có source."
2052
- )
2053
-
2054
- current_image = Image.open(
2055
- target_path
2056
- ).convert(
2057
- "RGB"
2058
  )
2059
 
2060
- # Cache source tensors during this target.
2061
-
2062
- source_tensor_cache = {}
2063
-
2064
- for (
2065
- source_image_index,
2066
- source_face_index,
2067
- target_face_index
2068
- ) in target_mappings:
2069
-
2070
- if not (
2071
- 0 <= source_image_index
2072
- < len(source_paths)
2073
- ):
2074
-
2075
- raise RuntimeError(
2076
- "Source index không hợp lệ: "
2077
- + str(
2078
- source_image_index
2079
- )
2080
- )
2081
-
2082
- source_path = source_paths[
2083
- source_image_index
2084
- ]
2085
 
2086
- log(
2087
- "[MULTI SWAP]"
2088
- )
2089
-
2090
- log(
2091
- " SOURCE IMAGE:",
2092
- source_image_index
2093
- )
2094
 
2095
- log(
2096
- " SOURCE FACE:",
2097
- source_face_index
2098
- )
2099
 
2100
- log(
2101
- " TARGET FACE:",
2102
- target_face_index
2103
  )
2104
 
2105
- if source_image_index not in (
2106
- source_tensor_cache
2107
- ):
2108
-
2109
- source_tensor_cache[
2110
- source_image_index
2111
- ] = load_image_tensor(
2112
- source_path
2113
- )
2114
 
2115
- source_tensor = (
2116
- source_tensor_cache[
2117
- source_image_index
2118
- ]
2119
- )
2120
-
2121
- target_array = np.asarray(
2122
- current_image,
2123
- dtype=np.float32
2124
- ) / 255.0
2125
-
2126
- target_tensor = (
2127
- torch.from_numpy(
2128
- target_array
2129
- )
2130
- .unsqueeze(0)
2131
- )
2132
-
2133
- current_image = (
2134
- swap_single_face(
2135
- source_tensor=source_tensor,
2136
- target_tensor=target_tensor,
2137
- source_face_index=source_face_index,
2138
- target_face_index=target_face_index,
2139
- swap_model=swap_model,
2140
- face_restore_model=face_restore_model,
2141
- restore_strength=restore_strength
2142
- )
2143
- )
2144
-
2145
- gc.collect()
2146
-
2147
- return current_image
2148
-
2149
-
2150
- # ============================================================
2151
- # GROUP MAPPINGS BY TARGET
2152
- # ============================================================
2153
-
2154
- def group_mappings_by_target(
2155
- mappings
2156
- ):
2157
-
2158
- grouped = {}
2159
-
2160
- for mapping in mappings:
2161
-
2162
- (
2163
- source_image_index,
2164
- source_face_index,
2165
- target_image_index,
2166
- target_face_index
2167
- ) = mapping
2168
-
2169
- grouped.setdefault(
2170
- target_image_index,
2171
- []
2172
  )
 
2173
 
2174
- grouped[
2175
- target_image_index
2176
- ].append(
2177
- (
2178
- source_image_index,
2179
- source_face_index,
2180
- target_face_index
2181
- )
2182
  )
2183
-
2184
- return grouped
2185
-
2186
-
2187
- # ============================================================
2188
- # GIF METADATA
2189
- # ============================================================
2190
-
2191
- def read_gif_frames(
2192
- target_path
2193
- ):
2194
-
2195
- reader = imageio.get_reader(
2196
- target_path
2197
  )
2198
 
2199
- frames = []
2200
- durations = []
 
2201
 
2202
- try:
 
 
 
 
2203
 
2204
- meta = reader.get_meta_data()
 
 
2205
 
2206
- default_duration = meta.get(
2207
- "duration",
2208
- 100
2209
- )
2210
 
2211
- for frame_number, frame in enumerate(
2212
- reader
2213
- ):
2214
 
2215
- frames.append(
2216
- Image.fromarray(
2217
- frame
2218
- ).convert(
2219
- "RGB"
2220
- )
2221
- )
2222
 
2223
- try:
 
 
2224
 
2225
- frame_meta = (
2226
- reader.get_meta_data(
2227
- index=frame_number
2228
- )
2229
- )
2230
 
2231
- duration = frame_meta.get(
2232
- "duration",
2233
- default_duration
2234
  )
 
2235
 
2236
- except Exception:
2237
 
2238
- duration = default_duration
2239
 
2240
- if duration is None:
2241
 
2242
- duration = 100
 
 
2243
 
2244
- durations.append(
2245
- max(
2246
- 10,
2247
- int(duration)
2248
- )
2249
- )
2250
 
2251
- finally:
2252
 
2253
- reader.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2254
 
2255
  return (
2256
- frames,
2257
- durations
 
 
 
2258
  )
2259
 
2260
 
2261
  # ============================================================
2262
- # PROCESS GIF
2263
  # ============================================================
2264
 
2265
  def process_gif(
2266
- source_files,
2267
  target_path,
2268
- target_mappings,
2269
  swap_model,
2270
  face_restore_model,
2271
  restore_strength
2272
  ):
2273
 
2274
- frames, durations = (
2275
- read_gif_frames(
2276
- target_path
2277
- )
2278
  )
2279
 
2280
- if not frames:
2281
 
2282
- raise RuntimeError(
2283
- "GIF không có frame."
2284
- )
2285
 
2286
- output_frames = []
2287
 
2288
- total_frames = len(
2289
- frames
2290
- )
2291
 
2292
- log(
2293
- "[GIF] Total frames:",
2294
- total_frames
2295
- )
2296
 
2297
- for frame_number, frame in enumerate(
2298
- frames
2299
- ):
2300
 
2301
- log(
2302
- f"[GIF] Frame "
2303
- f"{frame_number + 1}/"
2304
- f"{total_frames}"
 
2305
  )
2306
 
2307
- temp_frame = None
 
 
 
 
 
 
 
2308
 
2309
- try:
 
 
 
 
 
 
 
 
 
 
2310
 
2311
  with tempfile.NamedTemporaryFile(
2312
  suffix=".png",
2313
  delete=False
2314
  ) as tmp:
2315
 
2316
- temp_frame = tmp.name
2317
 
2318
- frame.save(
2319
- temp_frame
2320
- )
2321
 
2322
- result_image = (
2323
- swap_target_with_mappings(
2324
- source_files=source_files,
2325
- target_path=temp_frame,
2326
- target_mappings=target_mappings,
2327
- swap_model=swap_model,
2328
- face_restore_model=face_restore_model,
2329
- restore_strength=restore_strength
2330
  )
2331
- )
2332
 
2333
- output_frames.append(
2334
- result_image
2335
- )
2336
 
2337
- finally:
 
 
 
 
2338
 
2339
- if (
2340
- temp_frame
2341
- and os.path.exists(
2342
- temp_frame
 
 
2343
  )
2344
- ):
 
 
 
 
 
 
 
 
 
2345
 
2346
  try:
2347
 
2348
  os.remove(
2349
- temp_frame
2350
  )
2351
 
2352
  except Exception:
2353
 
2354
  pass
2355
 
 
 
 
 
 
 
 
 
 
 
2356
  return (
2357
  output_frames,
2358
  durations
@@ -2360,17 +1856,54 @@ def process_gif(
2360
 
2361
 
2362
  # ============================================================
2363
- # GENERATE
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2364
  # ============================================================
2365
 
2366
  def generate_image(
2367
  source_files,
2368
  target_files,
2369
- mapping_text,
2370
  swap_model,
2371
  face_restore_model,
2372
- restore_strength,
2373
- progress=gr.Progress()
2374
  ):
2375
 
2376
  source_paths = get_file_paths(
@@ -2381,6 +1914,10 @@ def generate_image(
2381
  target_files
2382
  )
2383
 
 
 
 
 
2384
  if not source_paths:
2385
 
2386
  raise gr.Error(
@@ -2393,113 +1930,185 @@ def generate_image(
2393
  "Chưa chọn Target."
2394
  )
2395
 
2396
- mappings = build_mapping(
2397
- source_files,
2398
- target_files,
2399
- mapping_text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2400
  )
2401
 
2402
- grouped = group_mappings_by_target(
2403
- mappings
 
 
 
 
2404
  )
2405
 
2406
- log("")
2407
- log("=" * 70)
2408
- log("[GENERATE]")
2409
 
2410
- log(
2411
- "[SOURCE FILES]:",
2412
  len(source_paths)
2413
  )
2414
 
2415
- log(
2416
- "[TARGET FILES]:",
2417
  len(target_paths)
2418
  )
2419
 
2420
- log(
2421
- "[SWAP MODEL]:",
 
 
 
 
 
2422
  swap_model
2423
  )
2424
 
2425
- log(
2426
- "[RESTORE MODEL]:",
2427
  face_restore_model
2428
  )
2429
 
2430
- log(
2431
- "[RESTORE]:",
2432
  restore_strength
2433
  )
2434
 
2435
- log(
2436
- "[MAPPINGS]:",
2437
- mappings
2438
  )
2439
 
2440
- log("=" * 70)
 
 
 
2441
 
2442
  output_paths = []
2443
 
2444
- total_targets = len(
2445
- target_paths
 
 
 
 
2446
  )
2447
 
2448
- with PROCESS_LOCK:
 
 
 
2449
 
2450
- with torch.inference_mode():
 
 
2451
 
2452
- for target_index, target_path in enumerate(
2453
- target_paths
2454
- ):
2455
 
2456
- progress(
2457
- target_index / max(
2458
- 1,
2459
- total_targets
2460
- ),
2461
- desc=(
2462
- f"Target "
2463
- f"{target_index + 1}/"
2464
- f"{total_targets}"
2465
- )
2466
- )
2467
 
2468
- target_mappings = (
2469
- grouped.get(
2470
- target_index,
2471
- []
2472
- )
2473
- )
2474
 
2475
- if not target_mappings:
 
 
 
2476
 
2477
- log(
2478
- "[TARGET]",
2479
- target_index,
2480
- "has no mapping - skipped."
2481
- )
2482
 
2483
- continue
 
 
 
 
2484
 
2485
- target_base = (
2486
- os.path.splitext(
2487
- os.path.basename(
2488
- target_path
2489
- )
2490
- )[0]
2491
  )
 
 
 
 
 
 
 
2492
 
2493
- log("")
2494
- log(
2495
  "[TARGET]",
2496
- target_index,
2497
  target_path
2498
  )
2499
 
2500
- # ------------------------------------------------
 
 
 
 
 
 
 
2501
  # GIF
2502
- # ------------------------------------------------
2503
 
2504
  if target_path.lower().endswith(
2505
  ".gif"
@@ -2509,96 +2118,126 @@ def generate_image(
2509
  output_frames,
2510
  durations
2511
  ) = process_gif(
2512
- source_files=source_files,
2513
- target_path=target_path,
2514
- target_mappings=target_mappings,
2515
- swap_model=swap_model,
2516
- face_restore_model=face_restore_model,
2517
- restore_strength=restore_strength
 
 
 
 
 
 
2518
  )
2519
 
2520
  if not output_frames:
2521
 
2522
- raise RuntimeError(
2523
- "GIF không tạo được output."
2524
  )
2525
 
2526
- output_path = os.path.join(
2527
- OUTPUT_DIR,
2528
- f"multi_source_to_{target_base}.webp"
2529
- )
2530
-
2531
  output_frames[0].save(
 
2532
  output_path,
 
2533
  save_all=True,
2534
- append_images=output_frames[1:],
 
 
 
 
2535
  duration=durations,
 
2536
  loop=0,
 
2537
  format="WEBP",
 
2538
  quality=90,
 
2539
  method=6
2540
  )
2541
 
2542
- # ------------------------------------------------
2543
- # IMAGE
2544
- # ------------------------------------------------
 
 
 
 
2545
 
2546
  else:
2547
 
2548
  result_image = (
2549
- swap_target_with_mappings(
2550
- source_files=source_files,
2551
- target_path=target_path,
2552
- target_mappings=target_mappings,
2553
- swap_model=swap_model,
2554
- face_restore_model=face_restore_model,
2555
- restore_strength=restore_strength
2556
- )
2557
- )
2558
 
2559
- output_path = os.path.join(
2560
- OUTPUT_DIR,
2561
- f"multi_source_to_{target_base}.webp"
 
 
 
2562
  )
2563
 
2564
  result_image.save(
 
2565
  output_path,
 
2566
  format="WEBP",
 
2567
  quality=90,
 
2568
  method=6
2569
  )
2570
 
 
 
2571
  output_paths.append(
2572
  output_path
2573
  )
2574
 
2575
- log(
2576
- "[OUTPUT]",
2577
- output_path
2578
- )
2579
 
2580
- progress(
2581
- 1.0,
2582
- desc="Completed"
2583
- )
 
 
 
2584
 
2585
  gc.collect()
2586
 
2587
- if not output_paths:
2588
 
2589
- raise gr.Error(
2590
- "Không tạo được output.\n"
2591
- "Kiểm tra mapping."
2592
- )
 
 
 
 
 
 
 
 
2593
 
2594
  return output_paths
2595
 
2596
 
2597
  # ============================================================
2598
- # USE OUTPUT AS TARGET
2599
  # ============================================================
2600
 
2601
- def use_output_as_target(
2602
  output_files
2603
  ):
2604
 
@@ -2615,7 +2254,9 @@ def use_output_as_target(
2615
  valid_paths = [
2616
  p
2617
  for p in paths
2618
- if os.path.isfile(p)
 
 
2619
  ]
2620
 
2621
  if not valid_paths:
@@ -2623,140 +2264,133 @@ def use_output_as_target(
2623
  raise gr.Error(
2624
  "Không tìm thấy file kết quả."
2625
  )
2626
-
2627
- return valid_paths
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2628
 
2629
 
2630
  # ============================================================
2631
- # CLEAR FILES
2632
  # ============================================================
2633
 
2634
- def clear_files():
2635
 
2636
- return []
2637
 
 
2638
 
2639
- # ============================================================
2640
- # PREVIEW FIRST SOURCE
2641
- # ============================================================
2642
 
2643
- def preview_first_source(
2644
- source_files
2645
- ):
2646
 
2647
- paths = get_file_paths(
2648
- source_files
2649
- )
2650
 
2651
- if not paths:
2652
 
2653
- return (
2654
- None,
2655
- gr.update(
2656
- choices=[],
2657
- value=None
2658
- )
2659
- )
2660
 
2661
- return show_selected_source(
2662
- source_files,
2663
- f"0: {os.path.basename(paths[0])}"
2664
  )
2665
 
2666
 
2667
  # ============================================================
2668
- # PREVIEW FIRST TARGET
2669
  # ============================================================
2670
 
2671
- def preview_first_target(
2672
- target_files
2673
- ):
2674
-
2675
- paths = get_file_paths(
2676
- target_files
2677
- )
2678
-
2679
- if not paths:
2680
 
2681
- return (
2682
- None,
2683
- gr.update(
2684
- choices=[],
2685
- value=None
2686
- )
2687
- )
2688
 
2689
- return show_selected_target(
2690
- target_files,
2691
- f"0: {os.path.basename(paths[0])}"
2692
- )
2693
 
 
2694
 
2695
- # ============================================================
2696
- # OUTPUT PREVIEW
2697
- # ============================================================
2698
 
2699
- def preview_output(
2700
- output_files
2701
- ):
2702
 
2703
- paths = get_file_paths(
2704
- output_files
2705
  )
2706
 
2707
- if not paths:
2708
-
2709
- return None
2710
-
2711
- return paths[0]
2712
-
2713
 
2714
  # ============================================================
2715
  # UI
2716
  # ============================================================
2717
 
2718
  with gr.Blocks(
2719
- title=APP_TITLE,
2720
- theme=gr.themes.Soft()
2721
  ) as app:
2722
 
2723
  # ========================================================
2724
- # SOURCE
2725
  # ========================================================
2726
 
2727
  gr.Markdown(
2728
- "## 👤 Source Images"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2729
  )
2730
 
 
 
 
 
2731
  source_files = gr.File(
2732
- label="Upload Source Images",
2733
- file_count="multiple",
2734
- file_types=[
2735
- ".jpg",
2736
- ".jpeg",
2737
- ".png",
2738
- ".webp"
2739
- ],
2740
- type="filepath"
2741
- )
2742
 
2743
- source_selector = gr.Dropdown(
2744
- label="Source Image",
2745
- choices=[],
2746
- value=None,
2747
- interactive=True
2748
- )
2749
 
2750
- source_preview = gr.Image(
2751
- label="Detected Source Faces",
2752
- type="numpy",
2753
- interactive=False
2754
- )
2755
 
2756
- source_face_selector = gr.Dropdown(
2757
- label="Source Face",
2758
- choices=[],
2759
- value=None,
2760
  interactive=True
2761
  )
2762
 
@@ -2764,236 +2398,216 @@ with gr.Blocks(
2764
  # TARGET
2765
  # ========================================================
2766
 
2767
- gr.Markdown(
2768
- "## 🎯 Target Images"
2769
- )
2770
-
2771
  target_files = gr.File(
2772
- label="Upload Target Images / GIF",
 
 
2773
  file_count="multiple",
2774
- file_types=[
2775
- ".jpg",
2776
- ".jpeg",
2777
- ".png",
2778
- ".webp",
2779
- ".gif"
2780
- ],
2781
- type="filepath"
2782
- )
2783
 
2784
- target_selector = gr.Dropdown(
2785
- label="Target Image",
2786
- choices=[],
2787
- value=None,
2788
  interactive=True
2789
  )
2790
 
2791
- target_preview = gr.Image(
2792
- label="Detected Target Faces",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2793
  type="numpy",
2794
- interactive=False
2795
- )
2796
 
2797
- target_face_selector = gr.Dropdown(
2798
- label="Target Face",
2799
- choices=[],
2800
- value=None,
2801
- interactive=True
2802
  )
2803
 
2804
  # ========================================================
2805
- # MAPPING
2806
  # ========================================================
2807
 
2808
- gr.Markdown(
2809
- "## 🔗 Face Mapping"
2810
  )
2811
 
2812
- mapping_text = gr.Textbox(
2813
- label="Mapping",
2814
- value=default_mapping(),
2815
- lines=8,
2816
- placeholder=(
2817
- "SOURCE 0 FACE 0 -> TARGET 0 FACE 0\n"
2818
- "SOURCE 1 FACE 0 -> TARGET 0 FACE 1\n"
2819
- "SOURCE 2 FACE 0 -> TARGET 0 FACE 2"
2820
- )
2821
- )
2822
 
2823
- with gr.Row():
2824
 
2825
- add_mapping_btn = gr.Button(
2826
- "➕ Add Mapping",
2827
- variant="primary"
2828
- )
2829
 
2830
- remove_mapping_btn = gr.Button(
2831
- "➖ Remove Last"
2832
- )
2833
 
2834
- clear_mapping_btn = gr.Button(
2835
- "🗑️ Clear"
2836
- )
2837
 
2838
  # ========================================================
2839
- # SETTINGS
2840
  # ========================================================
2841
 
2842
- gr.Markdown(
2843
- "## ⚙️ Settings"
2844
- )
2845
-
2846
  swap_model = gr.Dropdown(
2847
- label="Swap Model",
2848
  choices=[
2849
- DEFAULT_SWAP_MODEL
 
 
 
 
 
 
 
2850
  ],
2851
- value=DEFAULT_SWAP_MODEL,
2852
- interactive=False
 
 
 
 
2853
  )
2854
 
 
 
 
 
2855
  face_restore_model = gr.Dropdown(
2856
- label="Face Restore",
2857
  choices=[
2858
- DEFAULT_RESTORE_MODEL
 
 
 
2859
  ],
2860
- value=DEFAULT_RESTORE_MODEL,
2861
- interactive=False
 
 
 
 
2862
  )
2863
 
 
 
 
 
2864
  restore_strength = gr.Slider(
2865
- label="Face Restore Visibility",
2866
- minimum=0.0,
2867
- maximum=1.0,
2868
- value=0.80,
2869
- step=0.05
 
 
 
 
 
2870
  )
2871
 
2872
  # ========================================================
2873
  # GENERATE
2874
  # ========================================================
2875
 
2876
- gr.Markdown(
2877
- "## 🚀 Generate"
2878
- )
2879
-
2880
  generate_btn = gr.Button(
 
2881
  "🚀 GENERATE",
2882
- variant="primary",
2883
- size="lg"
2884
- )
2885
 
2886
- output_files = gr.File(
2887
- label="Output Files",
2888
- file_count="multiple",
2889
- interactive=False
2890
  )
2891
 
2892
- output_preview = gr.Image(
2893
- label="Output Preview",
2894
- type="filepath",
2895
- interactive=False
 
 
 
2896
  )
2897
 
 
 
 
 
2898
  use_output_btn = gr.Button(
2899
- "♻️ Use Output As Target"
 
 
 
2900
  )
2901
 
2902
  # ========================================================
2903
- # SOURCE EVENTS
2904
  # ========================================================
2905
 
2906
- source_files.change(
2907
- fn=update_source_image_selector,
2908
- inputs=source_files,
2909
- outputs=source_selector
2910
- )
2911
 
2912
- source_files.change(
2913
- fn=preview_first_source,
2914
- inputs=source_files,
2915
- outputs=[
2916
- source_preview,
2917
- source_face_selector
2918
- ]
2919
- )
2920
 
2921
- source_selector.change(
2922
- fn=show_selected_source,
2923
- inputs=[
2924
- source_files,
2925
- source_selector
2926
- ],
2927
- outputs=[
2928
- source_preview,
2929
- source_face_selector
2930
- ]
2931
  )
2932
 
2933
  # ========================================================
2934
- # TARGET EVENTS
2935
  # ========================================================
2936
 
2937
- target_files.change(
2938
- fn=update_target_selector,
2939
- inputs=target_files,
2940
- outputs=target_selector
2941
- )
2942
 
2943
- target_files.change(
2944
- fn=preview_first_target,
2945
- inputs=target_files,
2946
- outputs=[
2947
- target_preview,
2948
- target_face_selector
2949
- ]
2950
- )
2951
 
2952
- target_selector.change(
2953
- fn=show_selected_target,
2954
  inputs=[
2955
- target_files,
2956
- target_selector
2957
  ],
 
2958
  outputs=[
2959
- target_preview,
2960
- target_face_selector
 
 
 
 
2961
  ]
2962
  )
2963
 
2964
  # ========================================================
2965
- # ADD MAPPING
2966
  # ========================================================
2967
 
2968
- add_mapping_btn.click(
2969
- fn=add_mapping,
2970
- inputs=[
2971
- mapping_text,
2972
- source_face_selector,
2973
- target_face_selector,
2974
- target_selector
2975
- ],
2976
- outputs=mapping_text
2977
- )
2978
 
2979
- # ========================================================
2980
- # REMOVE LAST MAPPING
2981
- # ========================================================
2982
 
2983
- remove_mapping_btn.click(
2984
- fn=remove_last_mapping,
2985
- inputs=mapping_text,
2986
- outputs=mapping_text
2987
- )
2988
 
2989
- # ========================================================
2990
- # CLEAR MAPPING
2991
- # ========================================================
2992
 
2993
- clear_mapping_btn.click(
2994
- fn=clear_mapping,
2995
- inputs=None,
2996
- outputs=mapping_text
2997
  )
2998
 
2999
  # ========================================================
@@ -3001,87 +2615,113 @@ with gr.Blocks(
3001
  # ========================================================
3002
 
3003
  generate_btn.click(
 
3004
  fn=generate_image,
 
3005
  inputs=[
 
3006
  source_files,
 
3007
  target_files,
3008
- mapping_text,
 
 
3009
  swap_model,
 
3010
  face_restore_model,
 
3011
  restore_strength
3012
  ],
3013
- outputs=output_files
 
 
 
 
3014
  )
3015
 
3016
  # ========================================================
3017
- # OUTPUT PREVIEW
3018
  # ========================================================
3019
 
3020
- output_files.change(
3021
- fn=preview_output,
3022
- inputs=output_files,
3023
- outputs=output_preview
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3024
  )
3025
 
3026
  # ========================================================
3027
- # OUTPUT -> TARGET
3028
  # ========================================================
3029
 
3030
- use_output_btn.click(
3031
- fn=use_output_as_target,
3032
- inputs=output_files,
3033
- outputs=target_files
 
 
 
 
 
 
 
 
 
 
 
 
3034
  )
3035
 
3036
 
3037
  # ============================================================
3038
- # LAUNCH
3039
  # ============================================================
3040
 
3041
- if __name__ == "__main__":
3042
-
3043
- log("")
3044
- log("=" * 70)
3045
 
3046
- log(
3047
- "[APP]",
3048
- APP_TITLE
3049
- )
3050
 
3051
- log(
3052
- "[DEVICE]",
3053
- "CPU"
3054
- )
3055
 
3056
- log(
3057
- "[SWAP]",
3058
- INSWAPPER_PATH
3059
- )
3060
 
3061
- log(
3062
- "[RESTORE]",
3063
- GPEN_PATH
3064
- )
3065
 
3066
- log(
3067
- "[REACTOR]",
3068
- REACTOR_PATH
3069
- )
3070
 
3071
- log("=" * 70)
3072
- log("")
 
 
3073
 
3074
- app.queue(
3075
- max_size=1
3076
- )
3077
 
3078
- app.launch(
3079
- server_name="0.0.0.0",
3080
- server_port=int(
3081
- os.environ.get(
3082
- "PORT",
3083
- "7860"
3084
- )
3085
- ),
3086
- show_error=True
3087
- )
 
1
  import os
2
 
3
  # ============================================================
4
+ # FORCE CPU
5
+ # ============================================================
6
+ # MUST be before torch / onnxruntime imports
7
  # ============================================================
8
 
9
  os.environ["CUDA_VISIBLE_DEVICES"] = ""
10
  os.environ["PYTORCH_CUDA_ALLOC_CONF"] = ""
11
+ os.environ["ORT_DISABLE_CUDA"] = "1"
12
+
13
+ # ============================================================
14
+ # IMPORTS
15
+ # ============================================================
16
 
17
  import sys
18
  import asyncio
 
 
19
  import gc
 
 
 
20
  import imageio
21
+ import tempfile
22
+ from collections import OrderedDict
23
+
24
  import numpy as np
 
 
25
  import cv2
26
+ import gradio as gr
27
 
28
  from PIL import Image
29
  from huggingface_hub import hf_hub_download
 
33
  # CONFIG
34
  # ============================================================
35
 
36
+ BASE_DIR = os.path.dirname(
37
+ os.path.abspath(__file__)
38
+ )
39
+
40
+ MODEL_DIR = os.path.join(
41
+ BASE_DIR,
42
+ "models"
43
+ )
44
+
45
+ INSIGHTFACE_DIR = os.path.join(
46
+ MODEL_DIR,
47
+ "insightface"
48
+ )
49
+
50
+ HYPERSWAP_DIR = os.path.join(
51
+ MODEL_DIR,
52
+ "hyperswap"
53
+ )
54
 
55
+ FACE_RESTORE_DIR = os.path.join(
56
+ MODEL_DIR,
57
+ "facerestore_models"
58
+ )
59
 
60
+ OUTPUT_DIR = os.path.join(
61
+ BASE_DIR,
62
+ "output"
63
+ )
64
 
65
+ # ============================================================
66
+ # COMFYUI PATH
67
+ # ============================================================
68
+ #
69
+ # This Space contains ComfyUI DIRECTLY in the repository root:
70
+ #
71
+ # /app/
72
+ # comfy/
73
+ # comfy_extras/
74
+ # execution.py
75
+ # nodes.py
76
+ # server.py
77
+ # folder_paths.py
78
+ # comfyui_version.py
79
+ #
80
+ # Therefore DO NOT require:
81
+ #
82
+ # /app/ComfyUI
83
+ #
84
+ # ============================================================
85
 
86
+ COMFYUI_ROOT = BASE_DIR
87
 
88
+ # Possible external ComfyUI locations
89
+ COMFYUI_CANDIDATES = [
90
+ BASE_DIR,
91
 
92
+ "/app/ComfyUI",
93
 
94
+ os.path.join(
95
+ BASE_DIR,
96
+ "ComfyUI"
97
+ ),
98
 
99
+ os.path.join(
100
+ BASE_DIR,
101
+ "comfy"
102
+ ),
103
+ ]
104
 
105
  # ============================================================
106
+ # REACTOR PATH
107
  # ============================================================
108
 
109
+ REACTOR_CANDIDATES = [
 
 
110
  os.path.join(
111
+ BASE_DIR,
112
  "custom_nodes",
113
  "comfyui-reactor-node"
114
  ),
115
+
116
+ "/app/custom_nodes/comfyui-reactor-node",
117
+
118
  os.path.join(
119
  os.getcwd(),
120
  "custom_nodes",
121
+ "comfyui-reactor-node"
122
  ),
123
  ]
124
 
125
+ REACTOR_PATH = None
126
+
127
+
128
+ # ============================================================
129
+ # MODEL DEFINITIONS
130
+ # ============================================================
131
+
132
+ MODEL_REPOS = {
133
+
134
+ "inswapper_128.onnx": (
135
+ "ezioruan/inswapper_128.onnx",
136
+ "inswapper_128.onnx",
137
+ INSIGHTFACE_DIR
138
+ ),
139
+
140
+ "hyperswap_1a_256.onnx": (
141
+ "facefusion/models-3.3.0",
142
+ "hyperswap_1a_256.onnx",
143
+ HYPERSWAP_DIR
144
+ ),
145
+
146
+ "hyperswap_1b_256.onnx": (
147
+ "facefusion/models-3.3.0",
148
+ "hyperswap_1b_256.onnx",
149
+ HYPERSWAP_DIR
150
+ ),
151
+
152
+ "hyperswap_1c_256.onnx": (
153
+ "facefusion/models-3.3.0",
154
+ "hyperswap_1c_256.onnx",
155
+ HYPERSWAP_DIR
156
+ ),
157
+
158
+ "GPEN-BFR-512.onnx": (
159
+ "martintomov/comfy",
160
+ "facerestore_models/GPEN-BFR-512.onnx",
161
+ FACE_RESTORE_DIR
162
+ ),
163
+ }
164
+
165
 
166
  # ============================================================
167
+ # CREATE DIRECTORIES
168
  # ============================================================
169
 
170
+ os.makedirs(
171
+ MODEL_DIR,
172
+ exist_ok=True
173
+ )
174
+
175
  os.makedirs(
176
  OUTPUT_DIR,
177
  exist_ok=True
178
  )
179
 
180
  os.makedirs(
181
+ INSIGHTFACE_DIR,
182
+ exist_ok=True
183
+ )
184
+
185
+ os.makedirs(
186
+ HYPERSWAP_DIR,
187
+ exist_ok=True
188
+ )
189
+
190
+ os.makedirs(
191
+ FACE_RESTORE_DIR,
192
  exist_ok=True
193
  )
194
 
 
197
  # LOG
198
  # ============================================================
199
 
200
+ print(
201
+ "============================================================"
202
+ )
203
+
204
+ print(
205
+ "[APP] BASE DIR:",
206
+ BASE_DIR
207
+ )
208
+
209
+ print(
210
+ "[APP] MODEL DIR:",
211
+ MODEL_DIR
212
+ )
213
+
214
+ print(
215
+ "[APP] OUTPUT DIR:",
216
+ OUTPUT_DIR
217
+ )
218
+
219
+ print(
220
+ "============================================================"
221
+ )
222
 
223
 
224
  # ============================================================
225
  # MODEL DOWNLOAD
226
  # ============================================================
227
 
228
+ def download_model(
229
+ model_name
 
 
230
  ):
 
 
231
 
232
+ if model_name not in MODEL_REPOS:
 
233
 
234
+ raise RuntimeError(
235
+ f"Unknown model: {model_name}"
236
+ )
237
+
238
+ repo, filename, local_dir = (
239
+ MODEL_REPOS[
240
+ model_name
241
+ ]
242
  )
243
 
244
+ local_path = os.path.join(
245
+ local_dir,
246
+ os.path.basename(
247
  filename
248
  )
249
  )
250
 
251
+ # --------------------------------------------------------
252
+ # Already exists
253
+ # --------------------------------------------------------
254
+
255
+ if os.path.isfile(
256
+ local_path
257
  ):
258
+
259
+ print(
260
+ "[MODEL] Already exists:",
261
  local_path
262
  )
263
+
264
  return local_path
265
 
266
  os.makedirs(
267
+ local_dir,
268
  exist_ok=True
269
  )
270
 
271
+ print(
272
+ "============================================================"
 
 
 
 
 
 
 
 
273
  )
274
 
275
+ print(
276
+ "[MODEL] Downloading:",
277
+ filename
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
  )
279
 
280
+ print(
281
+ "[MODEL] Repository:",
282
+ repo
 
 
 
 
 
 
 
 
 
283
  )
 
 
 
 
 
 
 
284
 
285
+ print(
286
+ "[MODEL] Destination:",
287
+ local_path
288
+ )
289
 
290
+ print(
291
+ "============================================================"
292
+ )
 
293
 
294
+ downloaded_path = hf_hub_download(
295
+ repo_id=repo,
296
+ filename=filename,
297
+ local_dir=local_dir
298
+ )
299
 
300
+ if not os.path.isfile(
301
+ downloaded_path
302
+ ):
303
 
304
+ raise RuntimeError(
305
+ "Model download failed:\n"
306
+ f"{downloaded_path}"
307
+ )
 
 
 
 
308
 
309
+ # Some HF layouts can return a path
310
+ # different from the expected location.
311
+ #
312
+ # Make sure our expected path exists.
313
 
314
+ if not os.path.isfile(
315
+ local_path
316
+ ):
317
 
318
+ try:
 
 
 
319
 
320
+ if os.path.isfile(
321
+ downloaded_path
322
+ ):
323
 
324
+ import shutil
325
 
326
+ shutil.copy2(
327
+ downloaded_path,
328
+ local_path
329
+ )
330
 
331
+ except Exception:
332
+ pass
 
 
333
 
334
+ if not os.path.isfile(
335
+ local_path
336
+ ):
337
 
338
+ raise RuntimeError(
339
+ "Model downloaded nhưng không tìm thấy "
340
+ f"local file:\n{local_path}"
341
  )
342
 
343
+ print(
344
+ "[MODEL] Ready:",
345
+ local_path
346
+ )
347
 
348
+ return local_path
349
 
350
 
351
  # ============================================================
352
+ # MODEL CACHE
353
  # ============================================================
354
 
355
+ loaded_models = {}
356
 
 
 
 
 
 
 
 
 
357
 
358
+ def ensure_model(
359
+ model_name
360
+ ):
361
 
362
+ if model_name in loaded_models:
 
 
 
 
 
 
 
 
363
 
364
+ cached_path = (
365
+ loaded_models[
366
+ model_name
367
+ ]
368
+ )
369
 
370
+ if os.path.isfile(
371
+ cached_path
372
+ ):
 
373
 
374
+ return cached_path
375
 
376
+ path = download_model(
377
+ model_name
 
 
378
  )
379
 
380
+ if not os.path.isfile(
381
+ path
 
382
  ):
383
 
384
+ raise RuntimeError(
385
+ f"Model không tồn tại:\n{path}"
 
 
 
 
 
 
 
386
  )
387
 
388
+ loaded_models[
389
+ model_name
390
+ ] = path
 
 
 
391
 
392
+ return path
 
 
393
 
394
 
395
  # ============================================================
396
+ # FIND EMBEDDED COMFYUI
397
  # ============================================================
398
 
399
+ def is_comfyui_root(
400
+ path
401
+ ):
 
 
402
 
403
+ if not path:
404
+ return False
405
 
406
+ if not os.path.isdir(
407
+ path
408
+ ):
409
+ return False
410
 
411
+ required_any = [
412
+ os.path.join(
413
+ path,
414
+ "nodes.py"
415
+ ),
416
 
417
+ os.path.join(
418
+ path,
419
+ "execution.py"
420
+ ),
421
 
422
+ os.path.join(
423
+ path,
424
+ "server.py"
425
+ ),
426
 
427
+ os.path.join(
428
+ path,
429
+ "folder_paths.py"
430
+ ),
431
+ ]
432
 
433
+ comfy_folder = os.path.isdir(
434
+ os.path.join(
435
+ path,
436
+ "comfy"
437
+ )
438
  )
439
 
440
+ required_count = sum(
441
+ os.path.isfile(
442
+ item
443
+ )
444
+ for item in required_any
445
+ )
446
 
447
+ return (
448
+ comfy_folder
449
+ and required_count >= 2
450
+ )
451
 
 
 
 
452
 
453
+ def find_comfyui_root():
 
 
 
454
 
455
+ # --------------------------------------------------------
456
+ # 1. Direct embedded ComfyUI
457
+ # --------------------------------------------------------
458
 
459
+ if is_comfyui_root(
460
+ BASE_DIR
461
+ ):
 
462
 
463
+ return BASE_DIR
464
 
465
+ # --------------------------------------------------------
466
+ # 2. Known candidates
467
+ # --------------------------------------------------------
468
 
469
+ for candidate in COMFYUI_CANDIDATES:
470
 
471
+ if is_comfyui_root(
472
+ candidate
473
+ ):
474
 
475
+ return candidate
476
 
477
+ # --------------------------------------------------------
478
+ # 3. Search upward
479
+ # --------------------------------------------------------
480
 
481
+ current = BASE_DIR
482
 
483
+ while True:
484
 
485
+ if is_comfyui_root(
486
+ current
487
+ ):
488
 
489
+ return current
490
 
491
+ parent = os.path.dirname(
492
+ current
 
493
  )
494
 
495
+ if parent == current:
496
+ break
 
497
 
498
+ current = parent
499
 
500
+ return None
 
 
 
501
 
502
 
503
  # ============================================================
504
+ # ADD COMFYUI TO PYTHON PATH
505
  # ============================================================
506
 
507
+ COMFYUI_ROOT = find_comfyui_root()
 
 
508
 
509
+ if COMFYUI_ROOT is None:
510
 
511
+ raise RuntimeError(
512
+ "\n"
513
+ "Không tìm thấy ComfyUI.\n\n"
514
+ "App này yêu cầu ComfyUI embedded hoặc "
515
+ "thư mục ComfyUI hợp lệ.\n\n"
516
+ "Expected files:\n"
517
+ " comfy/\n"
518
+ " nodes.py\n"
519
+ " execution.py\n"
520
+ " server.py\n"
521
+ " folder_paths.py\n"
522
+ " comfyui_version.py\n"
523
  )
524
 
525
+ # Insert at FRONT
526
+ # so embedded ComfyUI modules are preferred.
 
527
 
528
+ if COMFYUI_ROOT not in sys.path:
529
 
530
+ sys.path.insert(
531
+ 0,
532
+ COMFYUI_ROOT
533
+ )
534
+
535
+ print(
536
+ "[COMFYUI] Root:",
537
+ COMFYUI_ROOT
538
+ )
539
 
540
+ print(
541
+ "[COMFYUI] Root files:",
542
+ [
543
+ x
544
+ for x in [
545
+ "comfy",
546
+ "nodes.py",
547
+ "execution.py",
548
+ "server.py",
549
+ "folder_paths.py",
550
+ "comfyui_version.py"
551
+ ]
552
+ if os.path.exists(
553
+ os.path.join(
554
+ COMFYUI_ROOT,
555
+ x
556
  )
557
+ )
558
+ ]
559
+ )
560
 
 
561
 
562
+ # ============================================================
563
+ # COMFYUI VERSION
564
+ # ============================================================
565
+
566
+ try:
567
+
568
+ import comfyui_version
569
 
570
+ print(
571
+ "[COMFYUI] Version:",
572
+ getattr(
573
+ comfyui_version,
574
+ "__version__",
575
+ "unknown"
576
  )
577
+ )
578
 
579
+ except Exception as e:
580
+
581
+ print(
582
+ "[COMFYUI] Version file unavailable:",
583
+ e
584
+ )
585
+
586
+
587
+ # ============================================================
588
+ # EXTRA MODEL PATHS
589
+ # ============================================================
590
+
591
+ def find_extra_model_paths():
592
+
593
+ candidates = [
594
+
595
+ os.path.join(
596
+ COMFYUI_ROOT,
597
+ "extra_model_paths.yaml"
598
+ ),
599
+
600
+ os.path.join(
601
+ COMFYUI_ROOT,
602
+ "extra_model_paths.yml"
603
+ ),
604
+
605
+ os.path.join(
606
+ BASE_DIR,
607
+ "extra_model_paths.yaml"
608
+ ),
609
 
610
+ os.path.join(
611
+ BASE_DIR,
612
+ "extra_model_paths.yml"
613
+ ),
614
+ ]
615
+
616
+ for path in candidates:
617
+
618
+ if os.path.isfile(
619
+ path
620
  ):
621
 
622
+ return path
623
+
624
+ return None
625
 
 
626
 
627
+ def add_extra_model_paths():
628
 
629
+ extra_model_paths = (
630
+ find_extra_model_paths()
631
+ )
632
 
633
+ if not extra_model_paths:
634
+
635
+ print(
636
+ "[COMFYUI] No extra_model_paths.yaml"
637
  )
638
 
639
+ return
640
 
641
+ print(
642
+ "[COMFYUI] Extra model paths:",
643
+ extra_model_paths
644
  )
645
 
646
+ try:
647
 
648
+ from main import (
649
+ load_extra_path_config
650
+ )
651
+
652
+ load_extra_path_config(
653
+ extra_model_paths
654
+ )
655
+
656
+ except ImportError:
657
+
658
+ try:
659
+
660
+ from utils.extra_config import (
661
+ load_extra_path_config
662
+ )
663
+
664
+ load_extra_path_config(
665
+ extra_model_paths
666
+ )
667
+
668
+ except Exception as e:
669
+
670
+ print(
671
+ "[COMFYUI] Could not load "
672
+ "extra model paths:",
673
+ e
674
+ )
675
+
676
+ except Exception as e:
677
+
678
+ print(
679
+ "[COMFYUI] Extra path error:",
680
+ e
681
+ )
682
+
683
+
684
+ add_extra_model_paths()
685
 
686
 
687
  # ============================================================
688
+ # TORCH / COMFY CPU
689
  # ============================================================
690
 
691
+ import torch
692
 
693
+ import comfy.model_management
694
 
695
+ from comfy.model_management import (
696
+ CPUState
697
+ )
698
 
699
+ # Force CPU state
700
+ comfy.model_management.cpu_state = (
701
+ CPUState.CPU
702
+ )
703
 
704
+ print(
705
+ "[DEVICE] Forced CPU"
706
+ )
707
 
708
+ print(
709
+ "[DEVICE] torch.cuda.is_available():",
710
+ torch.cuda.is_available()
 
711
  )
712
 
713
 
714
  # ============================================================
715
+ # IMPORT COMFY NODES
716
  # ============================================================
717
 
718
+ def import_custom_nodes():
719
 
720
+ import execution
721
 
722
+ from nodes import (
723
+ init_extra_nodes
724
+ )
725
 
726
+ import server
727
 
728
+ # --------------------------------------------------------
729
+ # Create isolated event loop
730
+ # --------------------------------------------------------
731
 
732
+ loop = asyncio.new_event_loop()
733
 
734
+ asyncio.set_event_loop(
735
+ loop
736
+ )
737
 
738
+ # --------------------------------------------------------
739
+ # PromptServer
740
+ # --------------------------------------------------------
741
+
742
+ server_instance = (
743
+ server.PromptServer(
744
+ loop
745
  )
746
  )
747
 
748
+ # --------------------------------------------------------
749
+ # PromptQueue
750
+ # --------------------------------------------------------
751
 
752
+ execution.PromptQueue(
753
+ server_instance
754
+ )
755
 
756
+ # --------------------------------------------------------
757
+ # Load ComfyUI custom nodes
758
+ # --------------------------------------------------------
759
+
760
+ loop.run_until_complete(
761
+ init_extra_nodes()
762
  )
763
 
764
+ # --------------------------------------------------------
765
+ # Cleanup loop
766
+ # --------------------------------------------------------
767
 
768
+ try:
769
+
770
+ loop.run_until_complete(
771
+ asyncio.sleep(0)
772
+ )
773
+
774
+ except Exception:
775
+
776
+ pass
777
+
778
+ try:
779
+
780
+ loop.close()
781
+
782
+ except Exception:
783
+
784
+ pass
785
+
786
+
787
+ print(
788
+ "[COMFYUI] Initializing nodes..."
789
+ )
790
+
791
+ import_custom_nodes()
792
+
793
+ print(
794
+ "[COMFYUI] Nodes initialized."
795
  )
796
 
797
 
798
  # ============================================================
799
+ # NODE CLASS MAPPINGS
800
  # ============================================================
801
 
802
+ from nodes import (
803
+ NODE_CLASS_MAPPINGS
 
804
  )
805
 
806
 
807
  # ============================================================
808
+ # COMFYUI VALUE HELPER
809
  # ============================================================
810
 
811
  def get_value_at_index(
812
  obj,
813
+ index
814
  ):
815
 
816
+ """
817
+ Safely extract ComfyUI node output.
818
+ """
 
 
 
 
 
 
 
 
 
 
 
819
 
820
+ try:
821
 
822
+ return obj[
823
+ index
824
+ ]
825
 
826
+ except (
827
+ IndexError,
828
+ KeyError,
829
+ TypeError
830
  ):
831
 
832
+ if isinstance(
833
+ obj,
834
+ dict
835
+ ):
 
 
836
 
837
+ values = list(
838
+ obj.values()
839
+ )
840
 
841
+ return values[
842
+ index
843
  ]
844
 
845
+ raise
 
 
 
 
846
 
847
 
848
  # ============================================================
849
+ # REACTOR PATH
850
  # ============================================================
851
 
852
+ for candidate in REACTOR_CANDIDATES:
 
 
 
 
 
853
 
854
+ if os.path.isdir(
855
+ candidate
 
856
  ):
857
 
858
+ REACTOR_PATH = (
859
+ candidate
860
+ )
 
 
 
861
 
862
+ break
863
 
 
 
 
 
864
 
865
+ if REACTOR_PATH is None:
866
 
867
+ raise RuntimeError(
868
+ "\n"
869
+ "Không tìm thấy ComfyUI-ReActor.\n\n"
870
+ "Đã kiểm tra:\n"
871
+ + "\n".join(
872
+ REACTOR_CANDIDATES
873
+ )
874
+ )
875
 
876
 
877
+ if REACTOR_PATH not in sys.path:
 
 
878
 
879
+ sys.path.insert(
880
+ 0,
881
+ REACTOR_PATH
882
+ )
883
 
 
 
 
 
884
 
885
+ print(
886
+ "[REACTOR] Path:",
887
+ REACTOR_PATH
888
+ )
889
 
 
890
 
891
+ # ============================================================
892
+ # LOAD LOADIMAGE
893
+ # ============================================================
894
 
895
+ try:
 
 
896
 
897
+ loadimage = (
898
+ NODE_CLASS_MAPPINGS[
899
+ "LoadImage"
900
+ ]()
901
+ )
902
 
903
+ except Exception as e:
 
 
904
 
905
+ raise RuntimeError(
906
+ "Không load được "
907
+ "ComfyUI LoadImage:\n"
908
+ f"{e}"
909
+ )
910
 
911
 
912
  # ============================================================
913
+ # LOAD REACTOR
 
 
914
  # ============================================================
915
 
916
+ try:
 
 
917
 
918
+ reactorfaceswap = (
919
+ NODE_CLASS_MAPPINGS[
920
+ "ReActorFaceSwap"
921
+ ]()
922
+ )
923
 
924
+ except Exception as e:
 
 
925
 
926
+ raise RuntimeError(
927
+ "Không load được "
928
+ "ReActorFaceSwap:\n"
929
+ f"{e}"
930
+ )
931
 
 
 
 
 
932
 
933
+ print(
934
+ "[REACTOR] ReActorFaceSwap loaded."
935
+ )
 
 
936
 
 
 
 
 
937
 
938
+ # ============================================================
939
+ # REACTOR FACE FUNCTIONS
940
+ # ============================================================
941
+
942
+ try:
943
 
944
+ from scripts.reactor_swapper import (
945
+ analyze_faces,
946
+ sort_by_order
947
  )
948
 
949
+ except Exception as e:
 
950
 
951
+ raise RuntimeError(
952
+ "Không import được "
953
+ "ReActor reactor_swapper:\n"
954
+ f"{e}"
955
  )
956
 
 
 
957
 
958
  # ============================================================
959
+ # FACE CACHE
960
  # ============================================================
961
 
962
+ FACE_CACHE_MAX = 32
963
+
964
+ face_cache = OrderedDict()
965
+
966
+
967
+ def clear_face_cache():
968
+
969
+ face_cache.clear()
970
+
971
+ gc.collect()
972
+
973
+
974
  def detect_reactor_faces(
975
  image_path
976
  ):
977
 
978
  if not image_path:
979
+
980
  return []
981
 
982
  if not os.path.isfile(
983
  image_path
984
  ):
985
+
986
  return []
987
 
988
  try:
 
993
 
994
  except Exception:
995
 
996
+ return []
997
 
998
  cache_key = (
999
+ image_path,
 
 
1000
  mtime
1001
  )
1002
 
1003
+ # --------------------------------------------------------
1004
+ # Cache hit
1005
+ # --------------------------------------------------------
1006
 
1007
+ if cache_key in face_cache:
1008
+
1009
+ faces = face_cache.pop(
1010
  cache_key
1011
+ )
1012
+
1013
+ face_cache[
1014
+ cache_key
1015
+ ] = faces
1016
+
1017
+ return faces
1018
+
1019
+ # --------------------------------------------------------
1020
+ # Read image
1021
+ # --------------------------------------------------------
1022
 
1023
  img = cv2.imread(
1024
  image_path
1025
  )
1026
 
1027
  if img is None:
1028
+
1029
  return []
1030
 
1031
+ # --------------------------------------------------------
1032
+ # ReActor detection
1033
+ # --------------------------------------------------------
1034
 
1035
+ faces = analyze_faces(
1036
+ img,
1037
+ det_size=(
1038
+ 640,
1039
+ 640
1040
  )
1041
+ )
1042
 
1043
+ if faces is None:
 
 
 
 
 
1044
 
1045
  faces = []
1046
 
1047
+ # --------------------------------------------------------
1048
+ # ReActor ordering
1049
+ # --------------------------------------------------------
1050
 
1051
+ faces = sort_by_order(
1052
+ faces,
1053
+ "large-small"
1054
+ )
1055
+
1056
+ # --------------------------------------------------------
1057
+ # Cache
1058
+ # --------------------------------------------------------
1059
+
1060
+ face_cache[
1061
+ cache_key
1062
+ ] = faces
1063
+
1064
+ while (
1065
+ len(face_cache)
1066
+ > FACE_CACHE_MAX
1067
+ ):
1068
 
1069
+ face_cache.popitem(
1070
+ last=False
 
1071
  )
1072
 
1073
+ return faces
1074
+
1075
+
1076
+ # ============================================================
1077
+ # FILE PATH HELPERS
1078
+ # ============================================================
1079
+
1080
+ def get_file_path(
1081
+ file
1082
+ ):
1083
+
1084
+ if file is None:
1085
+
1086
+ return None
1087
+
1088
+ if isinstance(
1089
+ file,
1090
+ str
1091
+ ):
1092
+
1093
+ return file
1094
+
1095
+ if hasattr(
1096
+ file,
1097
+ "path"
1098
+ ):
1099
+
1100
+ return file.path
1101
+
1102
+ if hasattr(
1103
+ file,
1104
+ "name"
1105
+ ):
1106
+
1107
+ return file.name
1108
+
1109
+ return str(
1110
+ file
1111
+ )
1112
+
1113
+
1114
+ def get_file_paths(
1115
+ files
1116
+ ):
1117
+
1118
+ if not files:
1119
+
1120
+ return []
1121
+
1122
+ if isinstance(
1123
+ files,
1124
+ (str, bytes)
1125
+ ):
1126
+
1127
+ files = [
1128
+ files
1129
+ ]
1130
+
1131
+ result = []
1132
+
1133
+ for file in files:
1134
 
1135
+ path = get_file_path(
1136
+ file
1137
  )
1138
 
1139
+ if (
1140
+ path
1141
+ and os.path.isfile(
1142
+ path
1143
+ )
1144
+ ):
1145
 
1146
+ result.append(
1147
+ path
1148
+ )
1149
+
1150
+ return result
1151
 
1152
 
1153
  # ============================================================
1154
+ # PREVIEW FACES
1155
  # ============================================================
1156
 
1157
+ def preview_faces(
1158
+ image_path
 
1159
  ):
1160
 
1161
  if not image_path:
 
1170
 
1171
  return None, []
1172
 
1173
+ height, width = (
1174
+ img.shape[:2]
1175
+ )
1176
 
1177
  faces = detect_reactor_faces(
1178
  image_path
 
1183
  return None, []
1184
 
1185
  previews = []
1186
+
1187
  boxes = []
1188
 
1189
  for index, face in enumerate(
1190
  faces
1191
  ):
1192
 
1193
+ x1, y1, x2, y2 = (
1194
+ face.bbox
1195
+ )
 
 
 
 
 
 
1196
 
1197
  x1 = max(
1198
  0,
 
1205
  )
1206
 
1207
  x2 = min(
1208
+ width,
1209
  int(x2)
1210
  )
1211
 
1212
  y2 = min(
1213
+ height,
1214
  int(y2)
1215
  )
1216
 
 
 
 
 
 
 
 
1217
  boxes.append(
1218
  [
1219
  x1,
 
1223
  ]
1224
  )
1225
 
1226
+ # ----------------------------------------------------
1227
+ # Padding
1228
+ # ----------------------------------------------------
1229
+
1230
  fw = max(
1231
  1,
1232
  x2 - x1
 
1256
  )
1257
 
1258
  cx2 = min(
1259
+ width,
1260
  x2 + px
1261
  )
1262
 
1263
  cy2 = min(
1264
+ height,
1265
  y2 + py
1266
  )
1267
 
 
1274
 
1275
  continue
1276
 
1277
+ # ----------------------------------------------------
1278
+ # Square
1279
+ # ----------------------------------------------------
1280
+
1281
  ch, cw = (
1282
  crop.shape[:2]
1283
  )
 
1309
  ox:ox + cw
1310
  ] = crop
1311
 
1312
+ # ----------------------------------------------------
1313
+ # Resize
1314
+ # ----------------------------------------------------
1315
+
1316
  crop = cv2.resize(
1317
  square,
1318
+ (
1319
+ 300,
1320
+ 300
1321
+ ),
1322
  interpolation=cv2.INTER_AREA
1323
  )
1324
 
1325
+ # ----------------------------------------------------
1326
+ # Face label
1327
+ # ----------------------------------------------------
1328
+
1329
  cv2.rectangle(
1330
  crop,
1331
+ (
1332
+ 0,
1333
+ 0
1334
+ ),
1335
+ (
1336
+ 300,
1337
+ 55
1338
+ ),
1339
+ (
1340
+ 0,
1341
+ 255,
1342
+ 0
1343
+ ),
1344
  -1
1345
  )
1346
 
1347
  cv2.putText(
1348
  crop,
1349
+ f"FACE {index}",
1350
+ (
1351
+ 15,
1352
+ 39
1353
+ ),
1354
  cv2.FONT_HERSHEY_SIMPLEX,
1355
+ 0.95,
1356
+ (
1357
+ 0,
1358
+ 0,
1359
+ 0
1360
+ ),
1361
  2,
1362
  cv2.LINE_AA
1363
  )
 
1375
 
1376
  return None, []
1377
 
1378
+ preview = np.hstack(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1379
  previews
1380
+ )
 
 
 
 
 
 
 
 
1381
 
1382
  return (
1383
+ preview,
1384
  boxes
1385
  )
1386
 
1387
 
1388
  # ============================================================
1389
+ # GIF FIRST FRAME PREVIEW
1390
  # ============================================================
1391
 
1392
  def get_preview_image(
 
1397
 
1398
  return None, []
1399
 
1400
+ # --------------------------------------------------------
1401
+ # GIF
1402
+ # --------------------------------------------------------
1403
+
1404
+ if target_path.lower().endswith(
1405
  ".gif"
1406
  ):
1407
 
1408
+ reader = imageio.get_reader(
1409
+ target_path
 
1410
  )
1411
 
1412
+ try:
 
 
 
 
 
 
 
 
 
 
1413
 
1414
+ frame = reader.get_data(
1415
+ 0
1416
+ )
1417
 
1418
+ finally:
1419
 
1420
+ reader.close()
1421
 
1422
  with tempfile.NamedTemporaryFile(
1423
  suffix=".png",
 
1426
 
1427
  temp_path = tmp.name
1428
 
1429
+ try:
 
 
 
 
 
 
 
 
 
 
 
1430
 
1431
+ Image.fromarray(
1432
+ frame
1433
+ ).save(
1434
+ temp_path
1435
+ )
1436
 
1437
+ return preview_faces(
 
 
1438
  temp_path
1439
  )
1440
+
1441
+ finally:
1442
 
1443
  try:
1444
 
 
1450
 
1451
  pass
1452
 
1453
+ # --------------------------------------------------------
1454
+ # Normal image
1455
+ # --------------------------------------------------------
1456
 
1457
+ return preview_faces(
1458
+ target_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1459
  )
1460
 
1461
 
1462
  # ============================================================
1463
+ # UPDATE FACE SELECTOR
1464
  # ============================================================
1465
 
1466
+ def update_face_selector(
1467
+ target_files
 
1468
  ):
1469
 
1470
  paths = get_file_paths(
1471
+ target_files
1472
  )
1473
 
1474
  if not paths:
1475
 
1476
  return (
1477
  None,
1478
+ [],
1479
  gr.update(
1480
  choices=[],
1481
  value=None
1482
  )
1483
  )
1484
 
1485
+ preview, boxes = (
1486
+ get_preview_image(
1487
+ paths[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1488
  )
1489
  )
1490
 
1491
+ if not boxes:
1492
+
1493
+ return (
1494
+ None,
1495
+ [],
1496
+ gr.update(
1497
+ choices=[],
1498
+ value=None
1499
+ )
1500
  )
 
1501
 
1502
  choices = [
1503
+ f"FACE {i}"
1504
  for i in range(
1505
  len(boxes)
1506
  )
 
1508
 
1509
  return (
1510
  preview,
1511
+ boxes,
1512
  gr.update(
1513
  choices=choices,
1514
+ value=choices[0]
 
 
 
 
1515
  )
1516
  )
1517
 
1518
 
1519
  # ============================================================
1520
+ # CONVERT RESULT
1521
  # ============================================================
1522
 
1523
+ def convert_result(
1524
+ image
1525
  ):
1526
 
1527
+ # Import torch lazily here
1528
+ # because torch is already initialized above.
 
1529
 
1530
+ if isinstance(
1531
+ image,
1532
+ torch.Tensor
1533
+ ):
 
 
1534
 
1535
+ image = (
1536
+ image
1537
+ .detach()
1538
+ .cpu()
1539
+ .float()
1540
+ .numpy()
1541
  )
1542
+
1543
+ image = np.asarray(
1544
+ image
1545
  )
1546
 
1547
+ if image.ndim == 4:
1548
 
1549
+ image = image[0]
 
 
1550
 
1551
+ if image.max() <= 1:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1552
 
1553
  image = (
1554
+ image * 255
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1555
  )
1556
 
1557
  image = np.clip(
 
1562
  np.uint8
1563
  )
1564
 
 
 
 
 
 
 
 
 
 
 
 
 
1565
  return image
1566
 
1567
 
1568
  # ============================================================
1569
+ # SWAP ONE IMAGE
1570
  # ============================================================
1571
 
1572
+ def swap_single_image(
1573
  source_tensor,
1574
+ target_path,
1575
+ selected_face_index,
 
1576
  swap_model,
1577
  face_restore_model,
1578
  restore_strength
1579
  ):
1580
 
1581
+ print(
1582
+ "============================================================"
1583
  )
1584
 
1585
+ print(
1586
+ "[SWAP]"
 
 
 
 
 
 
 
 
1587
  )
1588
 
1589
+ print(
1590
+ "TARGET:",
1591
+ target_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1592
  )
1593
 
1594
+ print(
1595
+ "FACE:",
1596
+ selected_face_index
1597
  )
1598
 
1599
+ print(
1600
+ "SWAP MODEL:",
1601
+ swap_model
 
 
 
 
 
1602
  )
1603
 
1604
+ print(
1605
+ "RESTORE MODEL:",
1606
+ face_restore_model
 
1607
  )
1608
 
1609
+ print(
1610
+ "RESTORE STRENGTH:",
1611
+ restore_strength
 
 
 
 
 
 
 
 
 
 
 
 
 
1612
  )
1613
 
1614
+ print(
1615
+ "============================================================"
 
 
 
 
 
 
 
 
1616
  )
1617
 
1618
+ # --------------------------------------------------------
1619
+ # Ensure models
1620
+ # --------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1621
 
1622
+ ensure_model(
1623
+ swap_model
1624
+ )
 
 
 
 
 
1625
 
1626
+ if (
1627
+ face_restore_model
1628
+ and face_restore_model != "none"
1629
+ ):
1630
 
1631
+ ensure_model(
1632
+ face_restore_model
 
1633
  )
1634
 
1635
+ # --------------------------------------------------------
1636
+ # Load target using ComfyUI
1637
+ # --------------------------------------------------------
 
 
 
 
 
 
1638
 
1639
+ target_data = (
1640
+ loadimage.load_image(
1641
+ image=target_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1642
  )
1643
+ )
1644
 
1645
+ target_tensor = (
1646
+ get_value_at_index(
1647
+ target_data,
1648
+ 0
 
 
 
 
1649
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1650
  )
1651
 
1652
+ # --------------------------------------------------------
1653
+ # Restore model
1654
+ # --------------------------------------------------------
1655
 
1656
+ restore_model = (
1657
+ face_restore_model
1658
+ if face_restore_model
1659
+ else "none"
1660
+ )
1661
 
1662
+ # --------------------------------------------------------
1663
+ # ReActor
1664
+ # --------------------------------------------------------
1665
 
1666
+ result = (
1667
+ reactorfaceswap.execute(
 
 
1668
 
1669
+ enabled=True,
 
 
1670
 
1671
+ swap_model=swap_model,
 
 
 
 
 
 
1672
 
1673
+ facedetection=(
1674
+ "retinaface_resnet50"
1675
+ ),
1676
 
1677
+ face_restore_model=(
1678
+ restore_model
1679
+ ),
 
 
1680
 
1681
+ face_restore_visibility=(
1682
+ float(
1683
+ restore_strength
1684
  )
1685
+ ),
1686
 
1687
+ codeformer_weight=0.5,
1688
 
1689
+ detect_gender_input="no",
1690
 
1691
+ detect_gender_source="no",
1692
 
1693
+ input_faces_index=str(
1694
+ selected_face_index
1695
+ ),
1696
 
1697
+ source_faces_index="0",
 
 
 
 
 
1698
 
1699
+ console_log_level=1,
1700
 
1701
+ input_image=target_tensor,
1702
+
1703
+ source_image=source_tensor
1704
+ )
1705
+ )
1706
+
1707
+ # --------------------------------------------------------
1708
+ # Output
1709
+ # --------------------------------------------------------
1710
+
1711
+ swapped = (
1712
+ get_value_at_index(
1713
+ result,
1714
+ 0
1715
+ )[0]
1716
+ )
1717
+
1718
+ swapped = convert_result(
1719
+ swapped
1720
+ )
1721
 
1722
  return (
1723
+ Image.fromarray(
1724
+ swapped
1725
+ ).convert(
1726
+ "RGB"
1727
+ )
1728
  )
1729
 
1730
 
1731
  # ============================================================
1732
+ # GIF PROCESSING
1733
  # ============================================================
1734
 
1735
  def process_gif(
1736
+ source_tensor,
1737
  target_path,
1738
+ selected_face_index,
1739
  swap_model,
1740
  face_restore_model,
1741
  restore_strength
1742
  ):
1743
 
1744
+ reader = imageio.get_reader(
1745
+ target_path
 
 
1746
  )
1747
 
1748
+ output_frames = []
1749
 
1750
+ durations = []
 
 
1751
 
1752
+ try:
1753
 
1754
+ try:
 
 
1755
 
1756
+ meta = (
1757
+ reader.get_meta_data()
1758
+ )
 
1759
 
1760
+ except Exception:
1761
+
1762
+ meta = {}
1763
 
1764
+ default_duration = (
1765
+ meta.get(
1766
+ "duration",
1767
+ 100
1768
+ )
1769
  )
1770
 
1771
+ for frame_number, frame in enumerate(
1772
+ reader
1773
+ ):
1774
+
1775
+ print(
1776
+ "[GIF FRAME]",
1777
+ frame_number + 1
1778
+ )
1779
 
1780
+ frame_image = (
1781
+ Image.fromarray(
1782
+ frame
1783
+ ).convert(
1784
+ "RGB"
1785
+ )
1786
+ )
1787
+
1788
+ # ------------------------------------------------
1789
+ # Temporary PNG
1790
+ # ------------------------------------------------
1791
 
1792
  with tempfile.NamedTemporaryFile(
1793
  suffix=".png",
1794
  delete=False
1795
  ) as tmp:
1796
 
1797
+ temp_path = tmp.name
1798
 
1799
+ try:
 
 
1800
 
1801
+ frame_image.save(
1802
+ temp_path
 
 
 
 
 
 
1803
  )
 
1804
 
1805
+ result_image = (
1806
+ swap_single_image(
 
1807
 
1808
+ source_tensor,
1809
+
1810
+ temp_path,
1811
+
1812
+ selected_face_index,
1813
 
1814
+ swap_model,
1815
+
1816
+ face_restore_model,
1817
+
1818
+ restore_strength
1819
+ )
1820
  )
1821
+
1822
+ output_frames.append(
1823
+ result_image
1824
+ )
1825
+
1826
+ durations.append(
1827
+ default_duration
1828
+ )
1829
+
1830
+ finally:
1831
 
1832
  try:
1833
 
1834
  os.remove(
1835
+ temp_path
1836
  )
1837
 
1838
  except Exception:
1839
 
1840
  pass
1841
 
1842
+ del frame
1843
+
1844
+ del frame_image
1845
+
1846
+ gc.collect()
1847
+
1848
+ finally:
1849
+
1850
+ reader.close()
1851
+
1852
  return (
1853
  output_frames,
1854
  durations
 
1856
 
1857
 
1858
  # ============================================================
1859
+ # OUTPUT PATH
1860
+ # ============================================================
1861
+
1862
+ def make_output_path(
1863
+ source_path,
1864
+ target_path
1865
+ ):
1866
+
1867
+ source_base = (
1868
+ os.path.splitext(
1869
+ os.path.basename(
1870
+ source_path
1871
+ )
1872
+ )[0]
1873
+ )
1874
+
1875
+ target_base = (
1876
+ os.path.splitext(
1877
+ os.path.basename(
1878
+ target_path
1879
+ )
1880
+ )[0]
1881
+ )
1882
+
1883
+ filename = (
1884
+ f"{source_base}"
1885
+ f"_to_"
1886
+ f"{target_base}"
1887
+ f".webp"
1888
+ )
1889
+
1890
+ return os.path.join(
1891
+ OUTPUT_DIR,
1892
+ filename
1893
+ )
1894
+
1895
+
1896
+ # ============================================================
1897
+ # MAIN GENERATE
1898
  # ============================================================
1899
 
1900
  def generate_image(
1901
  source_files,
1902
  target_files,
1903
+ selected_face_index,
1904
  swap_model,
1905
  face_restore_model,
1906
+ restore_strength
 
1907
  ):
1908
 
1909
  source_paths = get_file_paths(
 
1914
  target_files
1915
  )
1916
 
1917
+ # --------------------------------------------------------
1918
+ # Validation
1919
+ # --------------------------------------------------------
1920
+
1921
  if not source_paths:
1922
 
1923
  raise gr.Error(
 
1930
  "Chưa chọn Target."
1931
  )
1932
 
1933
+ if selected_face_index is None:
1934
+
1935
+ raise gr.Error(
1936
+ "Chưa chọn Face."
1937
+ )
1938
+
1939
+ # --------------------------------------------------------
1940
+ # FACE 0 -> 0
1941
+ # --------------------------------------------------------
1942
+
1943
+ if isinstance(
1944
+ selected_face_index,
1945
+ str
1946
+ ):
1947
+
1948
+ selected_face_index = (
1949
+ selected_face_index
1950
+ .replace(
1951
+ "FACE",
1952
+ ""
1953
+ )
1954
+ .strip()
1955
+ )
1956
+
1957
+ try:
1958
+
1959
+ selected_face_index = int(
1960
+ selected_face_index
1961
+ )
1962
+
1963
+ except Exception:
1964
+
1965
+ raise gr.Error(
1966
+ "Face index không hợp lệ."
1967
+ )
1968
+
1969
+ # --------------------------------------------------------
1970
+ # Defaults
1971
+ # --------------------------------------------------------
1972
+
1973
+ if not swap_model:
1974
+
1975
+ swap_model = (
1976
+ "inswapper_128.onnx"
1977
+ )
1978
+
1979
+ if not face_restore_model:
1980
+
1981
+ face_restore_model = (
1982
+ "GPEN-BFR-512.onnx"
1983
+ )
1984
+
1985
+ restore_strength = float(
1986
+ restore_strength
1987
+ if restore_strength is not None
1988
+ else 0.70
1989
  )
1990
 
1991
+ # --------------------------------------------------------
1992
+ # Log
1993
+ # --------------------------------------------------------
1994
+
1995
+ print(
1996
+ "============================================================"
1997
  )
1998
 
1999
+ print(
2000
+ "[GENERATE]"
2001
+ )
2002
 
2003
+ print(
2004
+ "SOURCE:",
2005
  len(source_paths)
2006
  )
2007
 
2008
+ print(
2009
+ "TARGET:",
2010
  len(target_paths)
2011
  )
2012
 
2013
+ print(
2014
+ "FACE:",
2015
+ selected_face_index
2016
+ )
2017
+
2018
+ print(
2019
+ "MODEL:",
2020
  swap_model
2021
  )
2022
 
2023
+ print(
2024
+ "RESTORE:",
2025
  face_restore_model
2026
  )
2027
 
2028
+ print(
2029
+ "STRENGTH:",
2030
  restore_strength
2031
  )
2032
 
2033
+ print(
2034
+ "============================================================"
 
2035
  )
2036
 
2037
+ os.makedirs(
2038
+ OUTPUT_DIR,
2039
+ exist_ok=True
2040
+ )
2041
 
2042
  output_paths = []
2043
 
2044
+ # --------------------------------------------------------
2045
+ # Download only selected models
2046
+ # --------------------------------------------------------
2047
+
2048
+ ensure_model(
2049
+ swap_model
2050
  )
2051
 
2052
+ if (
2053
+ face_restore_model
2054
+ and face_restore_model != "none"
2055
+ ):
2056
 
2057
+ ensure_model(
2058
+ face_restore_model
2059
+ )
2060
 
2061
+ # --------------------------------------------------------
2062
+ # CPU inference
2063
+ # --------------------------------------------------------
2064
 
2065
+ with torch.inference_mode():
 
 
 
 
 
 
 
 
 
 
2066
 
2067
+ for source_path in source_paths:
 
 
 
 
 
2068
 
2069
+ print(
2070
+ "[SOURCE]",
2071
+ source_path
2072
+ )
2073
 
2074
+ # ------------------------------------------------
2075
+ # Load source once
2076
+ # ------------------------------------------------
 
 
2077
 
2078
+ source_data = (
2079
+ loadimage.load_image(
2080
+ image=source_path
2081
+ )
2082
+ )
2083
 
2084
+ source_tensor = (
2085
+ get_value_at_index(
2086
+ source_data,
2087
+ 0
 
 
2088
  )
2089
+ )
2090
+
2091
+ # ------------------------------------------------
2092
+ # Process targets
2093
+ # ------------------------------------------------
2094
+
2095
+ for target_path in target_paths:
2096
 
2097
+ print(
 
2098
  "[TARGET]",
 
2099
  target_path
2100
  )
2101
 
2102
+ output_path = (
2103
+ make_output_path(
2104
+ source_path,
2105
+ target_path
2106
+ )
2107
+ )
2108
+
2109
+ # =============================================
2110
  # GIF
2111
+ # =============================================
2112
 
2113
  if target_path.lower().endswith(
2114
  ".gif"
 
2118
  output_frames,
2119
  durations
2120
  ) = process_gif(
2121
+
2122
+ source_tensor,
2123
+
2124
+ target_path,
2125
+
2126
+ selected_face_index,
2127
+
2128
+ swap_model,
2129
+
2130
+ face_restore_model,
2131
+
2132
+ restore_strength
2133
  )
2134
 
2135
  if not output_frames:
2136
 
2137
+ raise gr.Error(
2138
+ "GIF không có frame."
2139
  )
2140
 
 
 
 
 
 
2141
  output_frames[0].save(
2142
+
2143
  output_path,
2144
+
2145
  save_all=True,
2146
+
2147
+ append_images=(
2148
+ output_frames[1:]
2149
+ ),
2150
+
2151
  duration=durations,
2152
+
2153
  loop=0,
2154
+
2155
  format="WEBP",
2156
+
2157
  quality=90,
2158
+
2159
  method=6
2160
  )
2161
 
2162
+ del output_frames
2163
+
2164
+ del durations
2165
+
2166
+ # =============================================
2167
+ # NORMAL IMAGE
2168
+ # =============================================
2169
 
2170
  else:
2171
 
2172
  result_image = (
2173
+ swap_single_image(
2174
+
2175
+ source_tensor,
2176
+
2177
+ target_path,
2178
+
2179
+ selected_face_index,
 
 
2180
 
2181
+ swap_model,
2182
+
2183
+ face_restore_model,
2184
+
2185
+ restore_strength
2186
+ )
2187
  )
2188
 
2189
  result_image.save(
2190
+
2191
  output_path,
2192
+
2193
  format="WEBP",
2194
+
2195
  quality=90,
2196
+
2197
  method=6
2198
  )
2199
 
2200
+ del result_image
2201
+
2202
  output_paths.append(
2203
  output_path
2204
  )
2205
 
2206
+ del source_tensor
 
 
 
2207
 
2208
+ del source_data
2209
+
2210
+ gc.collect()
2211
+
2212
+ # --------------------------------------------------------
2213
+ # Cleanup
2214
+ # --------------------------------------------------------
2215
 
2216
  gc.collect()
2217
 
2218
+ try:
2219
 
2220
+ if torch.cuda.is_available():
2221
+
2222
+ torch.cuda.empty_cache()
2223
+
2224
+ except Exception:
2225
+
2226
+ pass
2227
+
2228
+ print(
2229
+ "[OUTPUT]",
2230
+ output_paths
2231
+ )
2232
 
2233
  return output_paths
2234
 
2235
 
2236
  # ============================================================
2237
+ # USE OUTPUT AS TARGET + PREVIEW
2238
  # ============================================================
2239
 
2240
+ def use_output_and_preview(
2241
  output_files
2242
  ):
2243
 
 
2254
  valid_paths = [
2255
  p
2256
  for p in paths
2257
+ if os.path.isfile(
2258
+ p
2259
+ )
2260
  ]
2261
 
2262
  if not valid_paths:
 
2264
  raise gr.Error(
2265
  "Không tìm thấy file kết quả."
2266
  )
2267
+
2268
+ preview, boxes = (
2269
+ get_preview_image(
2270
+ valid_paths[0]
2271
+ )
2272
+ )
2273
+
2274
+ choices = [
2275
+ f"FACE {i}"
2276
+ for i in range(
2277
+ len(boxes)
2278
+ )
2279
+ ]
2280
+
2281
+ return (
2282
+
2283
+ valid_paths,
2284
+
2285
+ preview,
2286
+
2287
+ boxes,
2288
+
2289
+ gr.update(
2290
+
2291
+ choices=choices,
2292
+
2293
+ value=(
2294
+ choices[0]
2295
+ if choices
2296
+ else None
2297
+ )
2298
+ )
2299
+ )
2300
 
2301
 
2302
  # ============================================================
2303
+ # CLEAR TARGET
2304
  # ============================================================
2305
 
2306
+ def clear_target():
2307
 
2308
+ clear_face_cache()
2309
 
2310
+ return (
2311
 
2312
+ [],
 
 
2313
 
2314
+ None,
 
 
2315
 
2316
+ [],
 
 
2317
 
2318
+ gr.update(
2319
 
2320
+ choices=[],
 
 
 
 
 
 
2321
 
2322
+ value=None
2323
+ )
 
2324
  )
2325
 
2326
 
2327
  # ============================================================
2328
+ # RESET FACE SELECTION
2329
  # ============================================================
2330
 
2331
+ def reset_face_selection():
 
 
 
 
 
 
 
 
2332
 
2333
+ return (
 
 
 
 
 
 
2334
 
2335
+ None,
 
 
 
2336
 
2337
+ [],
2338
 
2339
+ gr.update(
 
 
2340
 
2341
+ choices=[],
 
 
2342
 
2343
+ value=None
2344
+ )
2345
  )
2346
 
 
 
 
 
 
 
2347
 
2348
  # ============================================================
2349
  # UI
2350
  # ============================================================
2351
 
2352
  with gr.Blocks(
2353
+ title="CPU Face Swap"
 
2354
  ) as app:
2355
 
2356
  # ========================================================
2357
+ # TITLE
2358
  # ========================================================
2359
 
2360
  gr.Markdown(
2361
+ """
2362
+ # 🔄 CPU Face Swap
2363
+
2364
+ ### Quy trình
2365
+
2366
+ **Source → Target → Preview Face → Generate → Dùng kết quả làm Target → Swap tiếp**
2367
+
2368
+ ### CPU
2369
+
2370
+ - CPU-only
2371
+ - ComfyUI embedded
2372
+ - ComfyUI-ReActor
2373
+ - Không tải toàn bộ model khi startup
2374
+ - Chỉ tải model đang chọn
2375
+ - Face detection cache giới hạn
2376
+ - GIF xử lý từng frame
2377
+ - Giải phóng RAM sau batch
2378
+ - Queue chỉ chạy 1 job CPU
2379
+ """
2380
  )
2381
 
2382
+ # ========================================================
2383
+ # SOURCE
2384
+ # ========================================================
2385
+
2386
  source_files = gr.File(
 
 
 
 
 
 
 
 
 
 
2387
 
2388
+ label="① Source Faces",
 
 
 
 
 
2389
 
2390
+ file_count="multiple",
2391
+
2392
+ type="filepath",
 
 
2393
 
 
 
 
 
2394
  interactive=True
2395
  )
2396
 
 
2398
  # TARGET
2399
  # ========================================================
2400
 
 
 
 
 
2401
  target_files = gr.File(
2402
+
2403
+ label="② Target Images / GIFs",
2404
+
2405
  file_count="multiple",
 
 
 
 
 
 
 
 
 
2406
 
2407
+ type="filepath",
2408
+
 
 
2409
  interactive=True
2410
  )
2411
 
2412
+ # ========================================================
2413
+ # TARGET BUTTONS
2414
+ # ========================================================
2415
+
2416
+ with gr.Row():
2417
+
2418
+ preview_btn = gr.Button(
2419
+ "🔍 Preview Face Index"
2420
+ )
2421
+
2422
+ clear_target_btn = gr.Button(
2423
+ "🗑 Clear Target"
2424
+ )
2425
+
2426
+ # ========================================================
2427
+ # PREVIEW
2428
+ # ========================================================
2429
+
2430
+ preview_image = gr.Image(
2431
+
2432
+ label="③ Face Preview",
2433
+
2434
  type="numpy",
 
 
2435
 
2436
+ interactive=False,
2437
+
2438
+ height=330
 
 
2439
  )
2440
 
2441
  # ========================================================
2442
+ # STATE
2443
  # ========================================================
2444
 
2445
+ face_boxes = gr.State(
2446
+ []
2447
  )
2448
 
2449
+ # ========================================================
2450
+ # FACE SELECTOR
2451
+ # ========================================================
 
 
 
 
 
 
 
2452
 
2453
+ face_selector = gr.Dropdown(
2454
 
2455
+ choices=[],
 
 
 
2456
 
2457
+ value=None,
 
 
2458
 
2459
+ label="④ Select Face"
2460
+ )
 
2461
 
2462
  # ========================================================
2463
+ # SWAP MODEL
2464
  # ========================================================
2465
 
 
 
 
 
2466
  swap_model = gr.Dropdown(
2467
+
2468
  choices=[
2469
+
2470
+ "inswapper_128.onnx",
2471
+
2472
+ "hyperswap_1a_256.onnx",
2473
+
2474
+ "hyperswap_1b_256.onnx",
2475
+
2476
+ "hyperswap_1c_256.onnx"
2477
  ],
2478
+
2479
+ value=(
2480
+ "inswapper_128.onnx"
2481
+ ),
2482
+
2483
+ label="⑤ Swap Model"
2484
  )
2485
 
2486
+ # ========================================================
2487
+ # RESTORE MODEL
2488
+ # ========================================================
2489
+
2490
  face_restore_model = gr.Dropdown(
2491
+
2492
  choices=[
2493
+
2494
+ "none",
2495
+
2496
+ "GPEN-BFR-512.onnx"
2497
  ],
2498
+
2499
+ value=(
2500
+ "GPEN-BFR-512.onnx"
2501
+ ),
2502
+
2503
+ label="⑥ Face Restore Model"
2504
  )
2505
 
2506
+ # ========================================================
2507
+ # RESTORE STRENGTH
2508
+ # ========================================================
2509
+
2510
  restore_strength = gr.Slider(
2511
+
2512
+ minimum=0,
2513
+
2514
+ maximum=1,
2515
+
2516
+ value=0.70,
2517
+
2518
+ step=0.05,
2519
+
2520
+ label="Restore Strength"
2521
  )
2522
 
2523
  # ========================================================
2524
  # GENERATE
2525
  # ========================================================
2526
 
 
 
 
 
2527
  generate_btn = gr.Button(
2528
+
2529
  "🚀 GENERATE",
 
 
 
2530
 
2531
+ variant="primary"
 
 
 
2532
  )
2533
 
2534
+ # ========================================================
2535
+ # OUTPUT
2536
+ # ========================================================
2537
+
2538
+ output_files = gr.Files(
2539
+
2540
+ label="⑦ Swap Result"
2541
  )
2542
 
2543
+ # ========================================================
2544
+ # USE OUTPUT
2545
+ # ========================================================
2546
+
2547
  use_output_btn = gr.Button(
2548
+
2549
+ "↻ DÙNG KẾT QUẢ LÀM TARGET + PREVIEW",
2550
+
2551
+ variant="secondary"
2552
  )
2553
 
2554
  # ========================================================
2555
+ # INFO
2556
  # ========================================================
2557
 
2558
+ gr.Markdown(
2559
+ """
2560
+ ### 🔁 Swap nhiều lần
 
 
2561
 
2562
+ Sau khi Generate:
 
 
 
 
 
 
 
2563
 
2564
+ **Dùng kết quả làm Target + Preview → chọn Face mới → Generate**
2565
+
2566
+ Không cần tải ảnh xuống rồi upload lại.
2567
+ """
 
 
 
 
 
 
2568
  )
2569
 
2570
  # ========================================================
2571
+ # PREVIEW EVENT
2572
  # ========================================================
2573
 
2574
+ preview_btn.click(
 
 
 
 
2575
 
2576
+ fn=update_face_selector,
 
 
 
 
 
 
 
2577
 
 
 
2578
  inputs=[
2579
+
2580
+ target_files
2581
  ],
2582
+
2583
  outputs=[
2584
+
2585
+ preview_image,
2586
+
2587
+ face_boxes,
2588
+
2589
+ face_selector
2590
  ]
2591
  )
2592
 
2593
  # ========================================================
2594
+ # TARGET CHANGE
2595
  # ========================================================
2596
 
2597
+ target_files.change(
 
 
 
 
 
 
 
 
 
2598
 
2599
+ fn=reset_face_selection,
 
 
2600
 
2601
+ inputs=[],
 
 
 
 
2602
 
2603
+ outputs=[
2604
+
2605
+ preview_image,
2606
 
2607
+ face_boxes,
2608
+
2609
+ face_selector
2610
+ ]
2611
  )
2612
 
2613
  # ========================================================
 
2615
  # ========================================================
2616
 
2617
  generate_btn.click(
2618
+
2619
  fn=generate_image,
2620
+
2621
  inputs=[
2622
+
2623
  source_files,
2624
+
2625
  target_files,
2626
+
2627
+ face_selector,
2628
+
2629
  swap_model,
2630
+
2631
  face_restore_model,
2632
+
2633
  restore_strength
2634
  ],
2635
+
2636
+ outputs=[
2637
+
2638
+ output_files
2639
+ ]
2640
  )
2641
 
2642
  # ========================================================
2643
+ # OUTPUT -> TARGET + PREVIEW
2644
  # ========================================================
2645
 
2646
+ use_output_btn.click(
2647
+
2648
+ fn=use_output_and_preview,
2649
+
2650
+ inputs=[
2651
+
2652
+ output_files
2653
+ ],
2654
+
2655
+ outputs=[
2656
+
2657
+ target_files,
2658
+
2659
+ preview_image,
2660
+
2661
+ face_boxes,
2662
+
2663
+ face_selector
2664
+ ]
2665
  )
2666
 
2667
  # ========================================================
2668
+ # CLEAR TARGET
2669
  # ========================================================
2670
 
2671
+ clear_target_btn.click(
2672
+
2673
+ fn=clear_target,
2674
+
2675
+ inputs=[],
2676
+
2677
+ outputs=[
2678
+
2679
+ target_files,
2680
+
2681
+ preview_image,
2682
+
2683
+ face_boxes,
2684
+
2685
+ face_selector
2686
+ ]
2687
  )
2688
 
2689
 
2690
  # ============================================================
2691
+ # GRADIO QUEUE
2692
  # ============================================================
2693
 
2694
+ app.queue(
2695
+ default_concurrency_limit=1
2696
+ )
 
2697
 
 
 
 
 
2698
 
2699
+ # ============================================================
2700
+ # LAUNCH
2701
+ # ============================================================
 
2702
 
2703
+ print(
2704
+ "============================================================"
2705
+ )
 
2706
 
2707
+ print(
2708
+ "[APP] Starting Gradio..."
2709
+ )
 
2710
 
2711
+ print(
2712
+ "[APP] ComfyUI:",
2713
+ COMFYUI_ROOT
2714
+ )
2715
 
2716
+ print(
2717
+ "[APP] ReActor:",
2718
+ REACTOR_PATH
2719
+ )
2720
 
2721
+ print(
2722
+ "============================================================"
2723
+ )
2724
 
2725
+ app.launch(
2726
+ share=True
2727
+ )