"""RunPod serverless client for BFS face-swap (face-swap-runpod-worker). Posts to ``/run`` and polls ``/status/{id}`` using the worker input contract from ``Simzy420/face-swap-runpod-worker``: reference_face, target_image (raw base64), base_model, resolution, num_inference_steps, lora_scale, seed, prompt, output_format Env: ``RUNPOD_API_KEY``, ``RUNPOD_FACESWAP_ENDPOINT_ID`` (required; no default). Optional: ``RUNPOD_FACESWAP_ENDPOINT_URL``, ``RUNPOD_TIMEOUT_SECONDS``. """ from __future__ import annotations import base64 import io import json import os import time import urllib.error import urllib.parse import urllib.request from pathlib import Path from typing import Any, Callable from PIL import Image, ImageOps DEFAULT_TIMEOUT_S = 1500.0 DEFAULT_POLL_S = 3.0 MAX_IMAGE_SIDE = 2048 _TRUE = frozenset({"1", "true", "yes", "on"}) ProgressFn = Callable[[str, float], None] UrlOpenFn = Callable[..., Any] SleepFn = Callable[[float], None] NowFn = Callable[[], float] class FaceswapError(Exception): """User-facing face-swap failure. Must not contain the API key.""" FACE_SWAP_PROMPT = ( "head_swap: start with as the base image, keeping its lighting, environment, and background. " "remove the head from completely and replace it with the head from , strictly preserving " "the hair, eye color, nose structure from . copy the direction of the eye, head rotation, micro " "expressions from , high quality, sharp details, 4k" ) def _env(env: dict[str, str] | None) -> dict[str, str]: if env is None: return dict(os.environ) return env def _env_float(env: dict[str, str], name: str, default: float, minimum: float) -> float: raw = (env.get(name) or "").strip() if not raw: return default try: value = float(raw) except ValueError as exc: raise FaceswapError(f"{name} must be a number (got {raw!r}).") from exc if value < minimum: return minimum return value def require_api_key(env: dict[str, str] | None = None) -> str: env = _env(env) key = (env.get("RUNPOD_API_KEY") or "").strip() if not key: raise FaceswapError( "Face swap needs RUNPOD_API_KEY. " "Add it with RUNPOD_FACESWAP_ENDPOINT_ID as env / Space secrets, then rebuild. " "Deploy the face-swap-runpod-worker endpoint first — this app does not create it." ) return key def endpoint_id(env: dict[str, str] | None = None) -> str: env = _env(env) return (env.get("RUNPOD_FACESWAP_ENDPOINT_ID") or "").strip() def require_endpoint_id(env: dict[str, str] | None = None) -> str: value = endpoint_id(env) if not value: raise FaceswapError( "Face swap needs RUNPOD_FACESWAP_ENDPOINT_ID. " "Deploy ghcr.io/simzy420/face-swap-runpod-worker:latest as a RunPod serverless " "endpoint (48 GB+ GPU, workersMin=0, attach Qwen/Qwen-Image-2.1 cached model), " "then set that endpoint id as RUNPOD_FACESWAP_ENDPOINT_ID. " "This app does not create or bill RunPod endpoints." ) return value def normalize_base_url(url: str) -> str: parts = urllib.parse.urlsplit(url.strip()) path = parts.path.rstrip("/") for suffix in ("/runsync", "/run"): if path.endswith(suffix): path = path[: -len(suffix)] break return urllib.parse.urlunsplit((parts.scheme, parts.netloc, path.rstrip("/"), "", "")) def endpoint_base_url(env: dict[str, str] | None = None) -> str: env = _env(env) override = (env.get("RUNPOD_FACESWAP_ENDPOINT_URL") or "").strip() if override: return normalize_base_url(override) return f"https://api.runpod.ai/v2/{require_endpoint_id(env)}" def _redact(text: str, secret: str) -> str: if secret and secret in text: return text.replace(secret, "[redacted]") return text def _short(text: str, secret: str = "", limit: int = 500) -> str: text = _redact(text or "", secret) cleaned: list[str] = [] for token in text.split(): if len(token) > 80 and all(c.isalnum() or c in "+/=" for c in token): cleaned.append("[omitted]") else: cleaned.append(token) text = " ".join(cleaned).strip() if len(text) > limit: return text[:limit] + "…" return text def image_to_base64(image: Image.Image, max_side: int = MAX_IMAGE_SIDE) -> str: """JPEG q=95, thumbnail max side 2048, raw base64 (no data: prefix).""" image = ImageOps.exif_transpose(image).convert("RGB") image = image.copy() image.thumbnail((max_side, max_side)) buf = io.BytesIO() image.save(buf, format="JPEG", quality=95) return base64.b64encode(buf.getvalue()).decode("ascii") def decode_output_image(image_base64: str) -> Image.Image: value = image_base64 if value.startswith("data:"): value = value.split(",", 1)[1] return Image.open(io.BytesIO(base64.b64decode(value))).convert("RGB") def _read_http_error(exc: urllib.error.HTTPError, secret: str) -> str: try: raw = exc.read().decode("utf-8", errors="replace") except Exception: raw = str(exc) try: parsed = json.loads(raw) except Exception: parsed = None if isinstance(parsed, dict) and parsed.get("error"): return _short(str(parsed["error"]), secret) return _short(raw, secret) class FaceswapClient: def __init__( self, api_key: str, base_url: str, *, timeout_s: float = DEFAULT_TIMEOUT_S, poll_interval_s: float = DEFAULT_POLL_S, urlopen: UrlOpenFn | None = None, sleep: SleepFn | None = None, now: NowFn | None = None, ) -> None: self.api_key = api_key self.base_url = base_url.rstrip("/") self.timeout_s = float(timeout_s) self.poll_interval_s = float(poll_interval_s) self._urlopen = urlopen or urllib.request.urlopen self._sleep = sleep or time.sleep self._now = now or time.monotonic def _request(self, method: str, url: str, body: dict | None = None, timeout: float = 120.0) -> Any: data = json.dumps(body).encode("utf-8") if body is not None else None req = urllib.request.Request( url, data=data, method=method, headers={ "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json", "User-Agent": "wan22-extend-faceswap/1.0", }, ) try: with self._urlopen(req, timeout=timeout) as resp: raw = resp.read() or b"null" return json.loads(raw) except urllib.error.HTTPError as exc: detail = _read_http_error(exc, self.api_key) if exc.code in (401, 403): raise FaceswapError( f"RunPod face-swap auth failed (HTTP {exc.code}). " f"Check RUNPOD_API_KEY. {detail}" ) from exc if exc.code == 404: raise FaceswapError( f"RunPod face-swap endpoint not found (HTTP 404). " f"Check RUNPOD_FACESWAP_ENDPOINT_ID. {detail}" ) from exc if exc.code == 409 or "ENDPOINT_PAUSED" in detail: raise FaceswapError( "The face-swap endpoint is paused (max workers is 0). " "In Runpod open the face-swap endpoint and set Max workers to 1 or more, " f"then try again. {detail}" ) from exc raise FaceswapError(f"RunPod face-swap HTTP {exc.code}: {detail}") from exc except urllib.error.URLError as exc: raise FaceswapError( f"RunPod face-swap unreachable: {_short(str(exc.reason or exc), self.api_key)}" ) from exc def swap( self, reference_face: Image.Image, target_image: Image.Image, *, base_model: str = "turbo", resolution: int = 1536, num_inference_steps: int | None = None, lora_scale: float = 1.0, seed: int = -1, prompt: str = "", output_format: str = "png", on_progress: ProgressFn | None = None, ) -> tuple[Image.Image, dict[str, Any]]: turbo = str(base_model or "turbo").lower().startswith("turbo") if num_inference_steps is None: num_inference_steps = 6 if turbo else 30 if resolution not in (1024, 1536, 2048): resolution = 1536 payload = { "input": { "reference_face": image_to_base64(reference_face), "target_image": image_to_base64(target_image), "base_model": "turbo" if turbo else "base", "resolution": int(resolution), "num_inference_steps": int(num_inference_steps), "lora_scale": float(lora_scale), "seed": int(seed), "prompt": (prompt or "").strip() or FACE_SWAP_PROMPT, "output_format": "jpeg" if str(output_format).lower() in ("jpg", "jpeg") else "png", } } if on_progress: on_progress("submit", 0.0) job = self._request("POST", f"{self.base_url}/run", payload, timeout=120.0) job_id = (job or {}).get("id") if not job_id: raise FaceswapError( f"RunPod face-swap did not return a job id: {_short(str(job), self.api_key)}" ) started = self._now() status: dict[str, Any] = {} while True: elapsed = self._now() - started if elapsed > self.timeout_s: try: self._request("POST", f"{self.base_url}/cancel/{job_id}", timeout=30.0) except FaceswapError: pass raise FaceswapError( f"RunPod face-swap timed out after {int(elapsed)}s (cancelled job {job_id})." ) status = self._request("GET", f"{self.base_url}/status/{job_id}", timeout=60.0) or {} state = str(status.get("status") or "").upper() if state == "COMPLETED": break if state in ("FAILED", "CANCELLED", "TIMED_OUT"): detail = status.get("error") or status.get("output") or status raise FaceswapError( f"RunPod face-swap job {state}: {_short(str(detail), self.api_key)}" ) if on_progress: on_progress(state or "IN_QUEUE", elapsed) self._sleep(self.poll_interval_s) out = status.get("output") or {} if isinstance(out, dict) and out.get("error"): raise FaceswapError(f"Worker error: {_short(str(out['error']), self.api_key)}") if not isinstance(out, dict) or not out.get("image_base64"): raise FaceswapError("RunPod face-swap finished but returned no image_base64.") if on_progress: on_progress("save", self._now() - started) image = decode_output_image(out["image_base64"]) return image, out def face_swap( reference_face: Image.Image, target_image: Image.Image, *, base_model: str = "turbo", resolution: int = 1536, num_inference_steps: int | None = None, lora_scale: float = 1.0, seed: int = -1, prompt: str = "", output_format: str = "png", dest: Path | None = None, env: dict[str, str] | None = None, on_progress: ProgressFn | None = None, urlopen: UrlOpenFn | None = None, sleep: SleepFn | None = None, now: NowFn | None = None, timeout_s: float | None = None, poll_interval_s: float | None = None, ) -> tuple[Image.Image, dict[str, Any]]: """Run one BFS head-swap job. Optionally save PNG/JPEG to ``dest``.""" env_map = _env(env) api_key = require_api_key(env_map) require_endpoint_id(env_map) if timeout_s is None: timeout_s = _env_float(env_map, "RUNPOD_TIMEOUT_SECONDS", DEFAULT_TIMEOUT_S, 1.0) if poll_interval_s is None: poll_interval_s = _env_float(env_map, "RUNPOD_POLL_INTERVAL_SECONDS", DEFAULT_POLL_S, 1.0) client = FaceswapClient( api_key, endpoint_base_url(env_map), timeout_s=timeout_s, poll_interval_s=poll_interval_s, urlopen=urlopen, sleep=sleep, now=now, ) image, meta = client.swap( reference_face, target_image, base_model=base_model, resolution=resolution, num_inference_steps=num_inference_steps, lora_scale=lora_scale, seed=seed, prompt=prompt, output_format=output_format, on_progress=on_progress, ) if dest is not None: dest = Path(dest) fmt = "JPEG" if dest.suffix.lower() in (".jpg", ".jpeg") else "PNG" if fmt == "JPEG": image.save(dest, format=fmt, quality=95) else: image.save(dest, format=fmt) return image, meta