# FaceIntegrator - Current Project Documentation ## 1. Purpose FaceIntegrator is a public-facing image backend that: - accepts `source` and `target` images, - runs face swap using InsightFace (`inswapper_128.onnx`), - optionally enhances the result with GFPGAN (`GFPGANv1.4.pth`), - returns a generated output image. Core runtime is Gradio + roop pipeline modules. ## 2. High-Level Request Flow 1. User submits request in Gradio UI (`app.py`). 2. Request enters Gradio queue (`max_size=20`, `default_concurrency_limit=1`). 3. App validates input arrays (`None`, type, empty checks). 4. App creates per-request unique temp paths (`create_request_paths`). 5. Images are converted to RGB, resized if too large (max 1500px), saved, then decode-validated with `cv2.imread`. 6. Runtime globals are set for this request (`source_path`, `target_path`, `output_path`, processors, execution settings). 7. Model pre-check runs: - model files are downloaded if missing, - SHA256 is verified, - mismatch triggers delete + re-download + re-verify. 8. `roop.core.start()` executes pipeline: - `pre_start` checks, - NSFW check on target (fail-closed), - face swap, - optional enhancement, - output write. 9. Output image is loaded and returned to client. 10. `finally` block always runs: - timeout deadline cleared, - temp request folder deleted, - `gc.collect()`, - `torch.cuda.empty_cache()` if CUDA available. ## 3. Current Architecture by File ### `app.py` Responsibilities: - Gradio interface definition - Queue and traffic control - Input validation and size limiting - Request temp path creation - Runtime initialization - Startup warmup - Final cleanup and memory stabilization Important constants: - `MAX_IMAGE_DIMENSION = 1500` - `PROCESS_TIMEOUT_SECONDS = 45` - `QUEUE_MAX_SIZE = 20` - `QUEUE_CONCURRENCY_LIMIT = 1` Queue behavior: - `app.queue(max_size=20, default_concurrency_limit=1).launch()` - allows waiting users, one active inference at a time. Startup warmup: - `_warmup_models()` runs before `launch()`. - triggers pre-check/download/verification and initializes swapper + enhancer once. ### `roop/core.py` Responsibilities: - Main orchestration (`start()`) - NSFW gating - Frame-processor execution order - Resource limiting utilities (`limit_resources`, `release_resources`) - Cooperative timeout checks via `ensure_not_timed_out()` Timeout model: - checks deadline at key boundaries in `start()`. - raises `TimeoutError` when limit is exceeded. ### `roop/predicter.py` Responsibilities: - NSFW detection for image and video - logging of NSFW outcomes - fail-closed behavior: - if NSFW predictor errors, returns `True` (block). ### `roop/utilities.py` Responsibilities: - ffmpeg/video helpers - path and temp helpers - model downloader with integrity validation - request path generator - dependency audit helper `conditional_download(...)` behavior: - accepts `expected_sha256` map by filename, - downloads missing files, - verifies hash, - logs safe/mismatch/info states, - on mismatch: delete -> re-download -> re-verify -> fail if still mismatch. `create_request_paths(...)` behavior: - creates unique request directory under `temp_requests/` - returns unique `source`, `target`, `output` paths. ### `roop/processors/frame/face_swapper.py` Responsibilities: - lazy load singleton swapper model (`FACE_SWAPPER`) with thread lock - model pre-check (URL + SHA256) - face swap processing functions Lifecycle note: - `post_process()` no longer destroys singleton. - model remains loaded across requests. ### `roop/processors/frame/face_enhancer.py` Responsibilities: - lazy load singleton enhancer (`FACE_ENHANCER`) with thread lock - model pre-check (URL + SHA256) - enhancement processing functions Lifecycle note: - `post_process()` no longer destroys singleton. - enhancer remains loaded across requests. ## 4. Security and Safety Controls Currently Implemented - SHA256 model integrity verification for swapper and enhancer. - Mismatch handling with forced re-download and re-check. - NSFW detection before processing output path; fail-closed on predictor errors. - Per-request isolated temp files/directories. - Always-clean temp directory in `finally`. - Input validation (basic ndarray checks + decode validation). - Image dimension cap and safe downscale before inference. - Queue-based admission control to avoid concurrent overload. - Optional dependency audit helper (`run_dependency_audit`). ## 5. Concurrency Strategy (Current) - Primary concurrency guard is Gradio queue. - Active inference concurrency is fixed to 1. - This avoids GPU/CPU memory spikes from simultaneous heavy jobs. - Model initialization remains thread-safe via per-model locks. - Old global `REQUEST_LOCK` is not used. ## 6. Runtime Stability Controls - `limit_resources()` is applied once at runtime init. - Per-request timeout deadline is enforced in core pipeline. - Post-request memory cleanup: - Python GC, - CUDA cache clear (when available). - Startup warmup removes first-request cold-start penalty. ## 7. Model Files and Verification Models: - `inswapper_128.onnx` - `GFPGANv1.4.pth` Validation: - checksums are defined in each processor `pre_check()`. - downloads occur from configured source URLs. - verification is automatic before use. Operational log patterns (from code): - `[DOWNLOAD] Fetching from ` - `[SAFE] ...` / `[MISMATCH] ...` / `[INFO] ...` style checksum messages - `[ROOP.PREDICTER] NSFW ...` messages ## 8. Dependencies Pinned in `requirements.txt`: - `numpy==1.26.4` - `opencv-python==4.7.0.72` - `onnx==1.14.0` - `insightface==0.7.3` - `torch==2.0.1` - `onnxruntime==1.20.1` - `gfpgan==1.3.8` - `opennsfw2==0.10.2` - `pip-audit==2.7.3` - and related runtime libs. ## 9. Deployment Notes Recommended: - Python 3.10 or 3.11 for compatibility with pinned ML stack. - Keep queue concurrency conservative unless hardware is profiled and validated. - Keep model checksums updated if source artifacts change. - Monitor temp storage, request latency, and timeout rates. ## 10. Known Operational Constraints - Current app path is image-focused; video path exists in core but not exposed in app inputs. - Timeout is cooperative (checked at pipeline boundaries, not hard process kill). - Global `roop.globals` state means the app is designed for controlled concurrency (currently set to 1). ## 11. Quick Run ```cmd py -3.11 -m venv .venv .venv\Scripts\activate python -m pip install --upgrade pip setuptools wheel python -m pip install -r requirements.txt python app.py ``` Then open the local Gradio URL.