bb676 commited on
Commit
e4d812d
·
verified ·
1 Parent(s): 4c18b61

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +328 -86
  2. requirements.txt +3 -0
app.py CHANGED
@@ -15,6 +15,7 @@ HF_TOKEN = os.getenv("HF_TOKEN") or os.getenv("HUGGINGFACEHUB_API_TOKEN")
15
 
16
  OUTPUT_DIR = os.path.join(os.path.dirname(__file__), "outputs")
17
  EXAMPLES_DIR = os.path.join(os.path.dirname(__file__), "assets", "examples")
 
18
 
19
 
20
  @dataclass
@@ -27,6 +28,7 @@ class SwapResult:
27
  def _ensure_dirs() -> None:
28
  os.makedirs(OUTPUT_DIR, exist_ok=True)
29
  os.makedirs(EXAMPLES_DIR, exist_ok=True)
 
30
 
31
 
32
  def _pil_from_any(img: Any) -> Image.Image:
@@ -71,6 +73,155 @@ def _detect_faces_haar(pil_img: Image.Image) -> int:
71
  return 1
72
 
73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  def _watermark(pil_img: Image.Image, text: str = "FaceSwap AI • demo") -> Image.Image:
75
  img = pil_img.copy().convert("RGBA")
76
  w, h = img.size
@@ -358,96 +509,187 @@ def build_demo() -> gr.Blocks:
358
  f"""
359
  <div class="fsai-wrap">
360
  <div class="fsai-hero">{APP_NAME}</div>
361
- <p class="fsai-sub">Cloud face swapping with safety-first UX. Use only with consent.</p>
362
  </div>
363
  """
364
  )
365
 
366
- with gr.Accordion("Consent & Safety (required)", open=True):
367
- gr.Markdown(
368
- """
369
- **Important:** Only upload photos you own or have explicit permission to edit.
370
-
371
- - **Consent**: You confirm you have consent from any person depicted.
372
- - **No misuse**: Do not use for harassment, impersonation, fraud, or sexual content.
373
- - **Watermark**: Outputs are watermarked to discourage misuse.
374
- """
375
- )
376
- consent = gr.Checkbox(label="I confirm I have consent and will use this responsibly.")
377
-
378
- with gr.Row():
379
- with gr.Column(scale=1):
380
- source = gr.Image(label="Source Face", type="pil", height=320)
381
- with gr.Column(scale=1):
382
- target = gr.Image(label="Target Photo", type="pil", height=320)
383
-
384
- with gr.Row():
385
- backend = gr.Radio(
386
- choices=["Cloud (FaceDancer Space)", "Custom Endpoint (HF Inference Endpoint / your API)"],
387
- value="Cloud (FaceDancer Space)",
388
- label="Inference backend",
389
- )
390
-
391
- with gr.Accordion("Advanced options", open=False):
392
- strength = gr.Slider(
393
- 0.0,
394
- 1.0,
395
- value=0.8,
396
- step=0.05,
397
- label="Swap strength",
398
- info="Higher = stronger identity transfer. (Cloud backend maps this to blend ratio.)",
399
- )
400
- steps = gr.Slider(10, 60, value=30, step=1, label="Steps", info="Used by Custom Endpoint backends.")
401
- guidance = gr.Slider(
402
- 1.0, 10.0, value=4.5, step=0.5, label="Guidance scale", info="Used by Custom Endpoint backends."
403
- )
404
-
405
- swap_btn = gr.Button("Swap Faces", variant="primary", size="lg")
406
- status = gr.Markdown(value="", elem_classes=["fsai-wrap"])
407
-
408
- with gr.Row():
409
- before = gr.Image(label="Before (Target)", type="pil", height=360)
410
- after = gr.Image(label="After (Result)", type="pil", height=360)
411
-
412
- with gr.Row():
413
- download = gr.File(label="Download result", file_types=[".png"])
414
-
415
- history_state = gr.State([]) # list[dict] with paths
416
- gallery = gr.Gallery(label="History (this session)", columns=4, height=260, preview=True)
417
-
418
- def _history_to_gallery(items: List[Dict[str, str]]) -> List[str]:
419
- return [it["result"] for it in items if "result" in it and os.path.exists(it["result"])]
420
-
421
- def _swap_and_gallery(*args):
422
- b, a, f, hist, msg = swap_faces(*args)
423
- return b, a, f, hist, _history_to_gallery(hist), msg
424
-
425
- swap_btn.click(
426
- _swap_and_gallery,
427
- inputs=[source, target, consent, strength, steps, guidance, backend, history_state],
428
- outputs=[before, after, download, history_state, gallery, status],
429
- )
430
-
431
- if examples:
432
- gr.Examples(
433
- examples=examples,
434
- inputs=[source, target],
435
- label="Examples",
436
- examples_per_page=4,
437
- )
438
-
439
- with gr.Accordion("Setup notes", open=False):
440
- gr.Markdown(
441
- f"""
442
- **Default cloud backend:** `{DEFAULT_REMOTE_SPACE_ID}` via Gradio Spaces API.
443
-
444
- To use a custom backend, set:
445
- - `HF_INFERENCE_ENDPOINT_URL` (your endpoint URL)
446
- - optional `HF_ENDPOINT_TOKEN` (Bearer token)
447
-
448
- See `README.md` for a 5-minute deploy guide.
449
- """
450
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
451
 
452
  return demo
453
 
 
15
 
16
  OUTPUT_DIR = os.path.join(os.path.dirname(__file__), "outputs")
17
  EXAMPLES_DIR = os.path.join(os.path.dirname(__file__), "assets", "examples")
18
+ MODELS_DIR = os.path.join(os.path.dirname(__file__), "models")
19
 
20
 
21
  @dataclass
 
28
  def _ensure_dirs() -> None:
29
  os.makedirs(OUTPUT_DIR, exist_ok=True)
30
  os.makedirs(EXAMPLES_DIR, exist_ok=True)
31
+ os.makedirs(MODELS_DIR, exist_ok=True)
32
 
33
 
34
  def _pil_from_any(img: Any) -> Image.Image:
 
73
  return 1
74
 
75
 
76
+ def _onnx_providers() -> List[str]:
77
+ """
78
+ Best-effort provider selection for ONNXRuntime / InsightFace.
79
+ Set `FORCE_CPU=1` to disable CUDA even if available.
80
+ """
81
+ force_cpu = os.getenv("FORCE_CPU", "").strip().lower() in {"1", "true", "yes", "y"}
82
+ if force_cpu:
83
+ return ["CPUExecutionProvider"]
84
+
85
+ try:
86
+ import onnxruntime as ort # type: ignore
87
+
88
+ available = set(ort.get_available_providers())
89
+ if "CUDAExecutionProvider" in available:
90
+ return ["CUDAExecutionProvider", "CPUExecutionProvider"]
91
+ except Exception:
92
+ pass
93
+
94
+ return ["CPUExecutionProvider"]
95
+
96
+
97
+ def _ensure_inswapper_onnx() -> str:
98
+ """
99
+ Ensures `inswapper_128.onnx` exists locally and returns its path.
100
+
101
+ You can override with:
102
+ - `INSWAPPER_ONNX_PATH` (absolute/relative path)
103
+ - `INSWAPPER_REPO_ID` and `INSWAPPER_FILENAME` for HF download
104
+ """
105
+ override = os.getenv("INSWAPPER_ONNX_PATH", "").strip()
106
+ if override:
107
+ p = override
108
+ if not os.path.isabs(p):
109
+ p = os.path.join(os.path.dirname(__file__), p)
110
+ if not os.path.exists(p):
111
+ raise FileNotFoundError(f"INSWAPPER_ONNX_PATH not found: {p}")
112
+ return p
113
+
114
+ _ensure_dirs()
115
+ local_path = os.path.join(MODELS_DIR, "inswapper_128.onnx")
116
+ if os.path.exists(local_path):
117
+ return local_path
118
+
119
+ # Default to a small community HF repo that hosts the file.
120
+ repo_id = os.getenv("INSWAPPER_REPO_ID", "ezioruan/inswapper_128.onnx").strip()
121
+ filename = os.getenv("INSWAPPER_FILENAME", "inswapper_128.onnx").strip()
122
+
123
+ try:
124
+ from huggingface_hub import hf_hub_download # type: ignore
125
+
126
+ downloaded = hf_hub_download(
127
+ repo_id=repo_id,
128
+ filename=filename,
129
+ token=HF_TOKEN,
130
+ )
131
+ # Copy to our local models dir so users can find it easily.
132
+ # (Avoid importing shutil at module import time.)
133
+ import shutil
134
+
135
+ shutil.copyfile(downloaded, local_path)
136
+ return local_path
137
+ except Exception as e:
138
+ raise RuntimeError(
139
+ "Could not download inswapper ONNX model.\n"
140
+ f"- Tried repo `{repo_id}` file `{filename}`\n"
141
+ f"- You can also set `INSWAPPER_ONNX_PATH` to a local file.\n"
142
+ f"Error: {e}"
143
+ )
144
+
145
+
146
+ _IFACE_ANALYZER = None
147
+ _IFACE_SWAPPER = None
148
+
149
+
150
+ def _load_local_faceswap_models():
151
+ """
152
+ Lazy-load InsightFace analyzer + inswapper ONNX swapper.
153
+ Returns (analyzer, swapper).
154
+ """
155
+ global _IFACE_ANALYZER, _IFACE_SWAPPER
156
+ if _IFACE_ANALYZER is not None and _IFACE_SWAPPER is not None:
157
+ return _IFACE_ANALYZER, _IFACE_SWAPPER
158
+
159
+ try:
160
+ import insightface # type: ignore
161
+ from insightface.app import FaceAnalysis # type: ignore
162
+ except Exception as e:
163
+ raise RuntimeError(
164
+ "Missing dependency for local live swap. Install `insightface`.\n"
165
+ f"Error: {e}"
166
+ )
167
+
168
+ providers = _onnx_providers()
169
+ # buffalo_l includes detection + recognition (needed to build embeddings for swapper).
170
+ analyzer = FaceAnalysis(name="buffalo_l", providers=providers)
171
+ analyzer.prepare(ctx_id=0 if providers[0] != "CPUExecutionProvider" else -1, det_size=(640, 640))
172
+
173
+ onnx_path = _ensure_inswapper_onnx()
174
+ swapper = insightface.model_zoo.get_model(onnx_path, providers=providers)
175
+
176
+ _IFACE_ANALYZER, _IFACE_SWAPPER = analyzer, swapper
177
+ return analyzer, swapper
178
+
179
+
180
+ def _largest_face(faces: List[Any]) -> Optional[Any]:
181
+ if not faces:
182
+ return None
183
+ best = None
184
+ best_area = -1
185
+ for f in faces:
186
+ try:
187
+ x1, y1, x2, y2 = f.bbox.astype(int).tolist()
188
+ area = max(0, x2 - x1) * max(0, y2 - y1)
189
+ except Exception:
190
+ area = -1
191
+ if area > best_area:
192
+ best_area = area
193
+ best = f
194
+ return best
195
+
196
+
197
+ def _np_rgb_to_bgr(img: np.ndarray) -> np.ndarray:
198
+ # Gradio gives RGB; InsightFace expects BGR.
199
+ if img is None:
200
+ raise ValueError("No image provided.")
201
+ if img.ndim != 3 or img.shape[2] < 3:
202
+ raise ValueError("Expected a 3-channel color image.")
203
+
204
+ rgb = img[:, :, :3]
205
+ if rgb.dtype != np.uint8:
206
+ # Gradio can emit float images (0..1 or 0..255). Normalize to uint8.
207
+ mx = float(np.max(rgb)) if rgb.size else 255.0
208
+ if mx <= 1.5:
209
+ rgb = np.clip(rgb, 0.0, 1.0) * 255.0
210
+ else:
211
+ rgb = np.clip(rgb, 0.0, 255.0)
212
+ rgb = rgb.astype(np.uint8)
213
+
214
+ return rgb[:, :, ::-1].copy()
215
+
216
+
217
+ def _np_bgr_to_rgb(img: np.ndarray) -> np.ndarray:
218
+ if img is None:
219
+ raise ValueError("No image provided.")
220
+ if img.ndim != 3 or img.shape[2] < 3:
221
+ return img
222
+ return img[:, :, :3][:, :, ::-1].copy()
223
+
224
+
225
  def _watermark(pil_img: Image.Image, text: str = "FaceSwap AI • demo") -> Image.Image:
226
  img = pil_img.copy().convert("RGBA")
227
  w, h = img.size
 
509
  f"""
510
  <div class="fsai-wrap">
511
  <div class="fsai-hero">{APP_NAME}</div>
512
+ <p class="fsai-sub">Swap faces in photos (cloud) or live webcam (local ONNX). Use only with consent.</p>
513
  </div>
514
  """
515
  )
516
 
517
+ with gr.Tabs():
518
+ with gr.Tab("Photo Swap (Cloud)"):
519
+ with gr.Accordion("Consent & Safety (required)", open=True):
520
+ gr.Markdown(
521
+ """
522
+ **Important:** Only upload photos you own or have explicit permission to edit.
523
+
524
+ - **Consent**: You confirm you have consent from any person depicted.
525
+ - **No misuse**: Do not use for harassment, impersonation, fraud, or sexual content.
526
+ - **Watermark**: Outputs are watermarked to discourage misuse.
527
+ """
528
+ )
529
+ consent = gr.Checkbox(label="I confirm I have consent and will use this responsibly.")
530
+
531
+ with gr.Row():
532
+ with gr.Column(scale=1):
533
+ source = gr.Image(label="Source Face", type="pil", height=320)
534
+ with gr.Column(scale=1):
535
+ target = gr.Image(label="Target Photo", type="pil", height=320)
536
+
537
+ with gr.Row():
538
+ backend = gr.Radio(
539
+ choices=["Cloud (FaceDancer Space)", "Custom Endpoint (HF Inference Endpoint / your API)"],
540
+ value="Cloud (FaceDancer Space)",
541
+ label="Inference backend",
542
+ )
543
+
544
+ with gr.Accordion("Advanced options", open=False):
545
+ strength = gr.Slider(
546
+ 0.0,
547
+ 1.0,
548
+ value=0.8,
549
+ step=0.05,
550
+ label="Swap strength",
551
+ info="Higher = stronger identity transfer. (Cloud backend maps this to blend ratio.)",
552
+ )
553
+ steps = gr.Slider(
554
+ 10, 60, value=30, step=1, label="Steps", info="Used by Custom Endpoint backends."
555
+ )
556
+ guidance = gr.Slider(
557
+ 1.0,
558
+ 10.0,
559
+ value=4.5,
560
+ step=0.5,
561
+ label="Guidance scale",
562
+ info="Used by Custom Endpoint backends.",
563
+ )
564
+
565
+ swap_btn = gr.Button("Swap Faces", variant="primary", size="lg")
566
+ status = gr.Markdown(value="", elem_classes=["fsai-wrap"])
567
+
568
+ with gr.Row():
569
+ before = gr.Image(label="Before (Target)", type="pil", height=360)
570
+ after = gr.Image(label="After (Result)", type="pil", height=360)
571
+
572
+ with gr.Row():
573
+ download = gr.File(label="Download result", file_types=[".png"])
574
+
575
+ history_state = gr.State([]) # list[dict] with paths
576
+ gallery = gr.Gallery(label="History (this session)", columns=4, height=260, preview=True)
577
+
578
+ def _history_to_gallery(items: List[Dict[str, str]]) -> List[str]:
579
+ return [it["result"] for it in items if "result" in it and os.path.exists(it["result"])]
580
+
581
+ def _swap_and_gallery(*args):
582
+ b, a, f, hist, msg = swap_faces(*args)
583
+ return b, a, f, hist, _history_to_gallery(hist), msg
584
+
585
+ swap_btn.click(
586
+ _swap_and_gallery,
587
+ inputs=[source, target, consent, strength, steps, guidance, backend, history_state],
588
+ outputs=[before, after, download, history_state, gallery, status],
589
+ )
590
+
591
+ if examples:
592
+ gr.Examples(
593
+ examples=examples,
594
+ inputs=[source, target],
595
+ label="Examples",
596
+ examples_per_page=4,
597
+ )
598
+
599
+ with gr.Accordion("Setup notes", open=False):
600
+ gr.Markdown(
601
+ f"""
602
+ **Default cloud backend:** `{DEFAULT_REMOTE_SPACE_ID}` via Gradio Spaces API.
603
+
604
+ To use a custom backend, set:
605
+ - `HF_INFERENCE_ENDPOINT_URL` (your endpoint URL)
606
+ - optional `HF_ENDPOINT_TOKEN` (Bearer token)
607
+
608
+ See `README.md` for a 5-minute deploy guide.
609
+ """
610
+ )
611
+
612
+ with gr.Tab("Live Swap (Local ONNX)"):
613
+ gr.Markdown(
614
+ """
615
+ Upload a **source face** once, then enable your **webcam**.
616
+ This runs locally using **InsightFace + ONNXRuntime** with `inswapper_128.onnx`.
617
+
618
+ Tip: For best results, use a clear, front-facing source photo and good lighting.
619
+ """
620
+ )
621
+
622
+ live_consent = gr.Checkbox(
623
+ label="I confirm I have consent and will use this responsibly.",
624
+ value=False,
625
+ )
626
+
627
+ with gr.Row():
628
+ live_source = gr.Image(label="Source Face (identity to use)", type="numpy", height=260)
629
+ live_source_status = gr.Markdown(value="")
630
+
631
+ source_face_state = gr.State(None) # cached InsightFace Face object
632
+
633
+ def _set_live_source(source_np: Any, consent_ok: bool):
634
+ if not consent_ok:
635
+ return None, "Please confirm consent to enable live swap."
636
+ if source_np is None:
637
+ return None, "Upload a source face image."
638
+
639
+ analyzer, _ = _load_local_faceswap_models()
640
+ src_bgr = _np_rgb_to_bgr(np.array(source_np))
641
+ faces = analyzer.get(src_bgr)
642
+ src_face = _largest_face(faces)
643
+ if src_face is None:
644
+ return None, "No face detected in source image."
645
+ return src_face, "Source face locked. Now enable the webcam."
646
+
647
+ live_set_btn = gr.Button("Lock source face", variant="primary")
648
+ live_set_btn.click(
649
+ _set_live_source,
650
+ inputs=[live_source, live_consent],
651
+ outputs=[source_face_state, live_source_status],
652
+ )
653
+
654
+ with gr.Row():
655
+ webcam = gr.Image(
656
+ label="Webcam",
657
+ sources=["webcam"],
658
+ streaming=True,
659
+ type="numpy",
660
+ height=420,
661
+ )
662
+ live_out = gr.Image(label="Live swapped output", type="numpy", height=420)
663
+
664
+ live_status = gr.Markdown(value="")
665
+
666
+ def _live_swap(frame_np: Any, src_face: Any, consent_ok: bool):
667
+ if not consent_ok:
668
+ return frame_np, "Consent not confirmed."
669
+ if frame_np is None:
670
+ return None, ""
671
+ if src_face is None:
672
+ return frame_np, "Lock a source face first."
673
+
674
+ analyzer, swapper = _load_local_faceswap_models()
675
+ frame_bgr = _np_rgb_to_bgr(np.array(frame_np))
676
+ faces = analyzer.get(frame_bgr)
677
+ tgt_face = _largest_face(faces)
678
+ if tgt_face is None:
679
+ return _np_bgr_to_rgb(frame_bgr), "No face detected in webcam frame."
680
+
681
+ try:
682
+ swapped_bgr = swapper.get(frame_bgr, tgt_face, src_face, paste_back=True)
683
+ except Exception as e:
684
+ return _np_bgr_to_rgb(frame_bgr), f"Swap error: {e}"
685
+
686
+ return _np_bgr_to_rgb(swapped_bgr), ""
687
+
688
+ webcam.stream(
689
+ _live_swap,
690
+ inputs=[webcam, source_face_state, live_consent],
691
+ outputs=[live_out, live_status],
692
+ )
693
 
694
  return demo
695
 
requirements.txt CHANGED
@@ -4,3 +4,6 @@ pillow>=10.0.0
4
  numpy>=1.24.0
5
  opencv-python-headless>=4.8.0.74
6
  requests>=2.31.0
 
 
 
 
4
  numpy>=1.24.0
5
  opencv-python-headless>=4.8.0.74
6
  requests>=2.31.0
7
+ onnxruntime
8
+ insightface
9
+ huggingface_hub