Spaces:
Sleeping

File size: 6,641 Bytes
bbb3afa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# 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/<uuid>`
- 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 <file> from <url>`
- `[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.