Dmitry1313 commited on
Commit
ca3d46f
·
verified ·
1 Parent(s): 1b5ef7b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +139 -224
app.py CHANGED
@@ -1,17 +1,17 @@
1
  #!/usr/bin/env python3
2
  """
3
- 🎨 FaceFusion API для Hugging Face Spaces — FINAL VERSION
4
- ✅ Output всегда JPEG независимо от входного формата
5
- ✅ Read UploadFile once and reuse bytes
6
- ✅ NSFW disabled via ENV
7
- ✅ ghost_3_256 maximum quality
8
- ✅ Fallback на inswapper_128 если ghost не работает
9
  """
10
 
11
  import os, sys, tempfile, subprocess, logging, shutil, time
12
  from pathlib import Path
13
  from contextlib import asynccontextmanager
14
- from fastapi import FastAPI, File, UploadFile, HTTPException, Query
15
  from fastapi.responses import Response
16
 
17
  # 🔥 Настройка логирования
@@ -24,23 +24,16 @@ logger = logging.getLogger(__name__)
24
 
25
  @asynccontextmanager
26
  async def lifespan(app: FastAPI):
27
- """Startup/Shutdown события"""
28
- logger.info("🚀 FaceFusion CPU API (ghost_3_256) starting...")
29
- logger.info("📁 Cache: /tmp/facefusion_cache")
30
- logger.info("⚙️ Default: ghost_3_256 + gfpgan_1.4")
31
- logger.info("🔕 NSFW filter: disabled via ENV")
32
- logger.info("🔄 Model re-download: enabled")
33
- logger.info("📐 Output format: always JPEG")
34
- logger.info("⏱️ Timeout: 900s")
35
- logger.info("✅ API ready!")
36
  yield
37
- logger.info("👋 API shutting down...")
38
 
39
- app = FastAPI(
40
- title="FaceFusion CPU API — High Quality",
41
- version="2.4",
42
- lifespan=lifespan
43
- )
44
 
45
  # 🔥 Пути
46
  FACEFUSION_DIR = Path("/facefusion")
@@ -51,179 +44,121 @@ CACHE_DIR.mkdir(parents=True, exist_ok=True)
51
  # 🔥 Проверка установки
52
  if not FACEFUSION_PY.exists():
53
  logger.error(f"❌ FaceFusion not found at {FACEFUSION_PY}")
54
- raise RuntimeError("FaceFusion not installed — check Dockerfile")
55
 
56
- # 🔥 КОНФИГУРАЦИЯ
57
  CONFIG = {
58
- "face_swapper": "ghost_3_256",
59
- "face_swapper_fallback": "inswapper_128",
60
- "face_enhancer": "gfpgan_1.4",
61
- "face_enhancer_blend": 75,
62
- "face_mask_types": ["box", "occlusion"],
63
- "face_mask_blur": 0.6,
64
- "face_mask_padding": [10, 10, 10, 10],
65
- "output_image_quality": "90",
66
- "timeout_high_quality": 900,
67
- "timeout_standard": 600,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  "skip_download": False,
69
  "log_level": "error",
70
  }
71
 
72
- # 🔥 Отключаем NSFW фильтр через ENV переменную
73
  os.environ["FACEFUSION_CONTENT_ANALYSER"] = "none"
74
 
75
- # 🔥 Доступные модели
76
- AVAILABLE_SWAPPERS = ["ghost_3_256", "ghost_2_256", "ghost_1_256", "inswapper_128", "simswap_256"]
77
-
78
  # ============================================
79
- # 🔥 ЭНДПОИНТЫ
80
  # ============================================
81
 
82
  @app.get("/")
83
  async def root():
84
  """Информация о с��рвисе"""
85
  return {
86
- "service": "FaceFusion CPU API — High Quality",
87
- "version": "2.4",
88
- "default_swapper": CONFIG["face_swapper"],
89
- "default_enhancer": CONFIG["face_enhancer"],
90
- "output_format": "jpeg (always)",
91
- "nsfw_disabled": os.environ.get("FACEFUSION_CONTENT_ANALYSER") == "none",
92
- "available_swappers": AVAILABLE_SWAPPERS,
93
  "status": "running"
94
  }
95
 
96
  @app.get("/health")
97
  async def health():
98
- """Health check для мониторинга"""
99
  return {"status": "ok"}
100
 
101
  @app.post("/swap")
102
  async def swap_face(
103
- source: UploadFile = File(..., description="Фото лица для замены (анфас, хорошее освещение)"),
104
- target: UploadFile = File(..., description="Целевое изображение"),
105
- swapper_model: str = Query(
106
- default="ghost_3_256",
107
- description="Модель замены лица",
108
- enum=AVAILABLE_SWAPPERS
109
- ),
110
- enhancer_model: str = Query(
111
- default="gfpgan_1.4",
112
- description="Модель улучшения лица (или 'none')"
113
- ),
114
- enhance_blend: int = Query(
115
- default=75,
116
- ge=0, le=100,
117
- description="Сила blending улучшения (0-100)"
118
- ),
119
- use_fallback: bool = Query(
120
- default=True,
121
- description="Использовать fallback модель если основная не работает"
122
- )
123
  ):
124
  """
125
- 🎨 Замена лица с высоким качеством
126
 
127
- **Модели:**
128
- - `ghost_3_256` — лучшее качество (256px, рекомендуется)
129
- - `inswapper_128` — стандартное (128px, быстрее)
 
 
130
 
131
- **Улучшение лица:**
132
- - `gfpgan_1.4` — хороший баланс качества/скорости
133
- - `none` — без улучшения
134
-
135
- **Время обработки:**
136
- - ghost_3_256: 60-120 сек
137
- - inswapper_128: 30-60 сек
138
- - +enhancer: +20-40 сек
139
-
140
- **Выход:** Всегда JPEG независимо от входного формата
141
  """
142
- # 🔥 ЧИТАЕМ ФАЙЛЫ ОДИН РАЗ И СОХРАНЯЕМ В ПАМЯТЬ
 
143
  try:
144
  source_bytes = await source.read()
145
  target_bytes = await target.read()
146
  except Exception as e:
147
- raise HTTPException(400, f"Failed to read uploaded files: {str(e)[:100]}")
148
 
149
  if not source_bytes or not target_bytes:
150
  raise HTTPException(400, "Empty file uploaded")
151
 
152
- logger.info(f"📥 Request: source={len(source_bytes)}b, target={len(target_bytes)}b")
153
-
154
- # Нормализуем enhancer_model
155
- if enhancer_model and enhancer_model.lower() == "none":
156
- enhancer_model = None
157
-
158
- # Формируем список моделей для попытки
159
- models_to_try = [swapper_model]
160
- if use_fallback and swapper_model != CONFIG["face_swapper_fallback"]:
161
- models_to_try.append(CONFIG["face_swapper_fallback"])
162
-
163
- last_error = None
164
-
165
- for attempt, model in enumerate(models_to_try, 1):
166
- logger.info(f"🔄 Attempt {attempt}/{len(models_to_try)}: {model}")
167
-
168
- try:
169
- result = await _process_face_swap(
170
- source_bytes=source_bytes,
171
- target_bytes=target_bytes,
172
- target_filename=target.filename,
173
- swapper_model=model,
174
- enhancer_model=enhancer_model if attempt == 1 else None, # Без enhancer для fallback
175
- enhance_blend=enhance_blend,
176
- timeout=CONFIG["timeout_high_quality"] if model.startswith("ghost") else CONFIG["timeout_standard"]
177
- )
178
- logger.info(f"✅ Success with {model} on attempt {attempt}")
179
- return result
180
- except Exception as e:
181
- last_error = str(e)
182
- logger.warning(f"⚠️ Attempt {attempt} failed with {model}: {last_error[:200]}")
183
- if attempt >= len(models_to_try):
184
- logger.error(f"❌ All attempts failed")
185
- raise HTTPException(500, f"Face swap failed: {last_error[:300]}")
186
 
187
- raise HTTPException(500, "Unexpected error")
188
-
189
- # ============================================
190
- # 🔥 ВНУТРЕННЯЯ ФУНКЦИЯ ОБРАБОТКИ
191
- # ============================================
192
-
193
- async def _process_face_swap(
194
- source_bytes: bytes,
195
- target_bytes: bytes,
196
- target_filename: str,
197
- swapper_model: str,
198
- enhancer_model: str,
199
- enhance_blend: int,
200
- timeout: int
201
- ):
202
- """Обработка замены лица"""
203
  temp_dir = None
204
 
205
  try:
206
- temp_dir = tempfile.mkdtemp(prefix="ff_")
207
 
208
- # 🔥 Входные файлы (любой формат)
209
  source_path = Path(temp_dir) / "source.jpg"
210
  target_path = Path(temp_dir) / "target.jpg"
 
211
 
212
- # 🔥 ВЫХОД ВСЕГДА .jpg
213
- output_path = Path(temp_dir) / "output.jpg"
214
-
215
- logger.info(f"🔧 Processing: swapper={swapper_model}, enhancer={enhancer_model}, output=jpg")
216
-
217
- # Записываем байты
218
  source_path.write_bytes(source_bytes)
219
  target_path.write_bytes(target_bytes)
220
 
221
- # Формируем список процессоров
222
- processors = ["face_swapper"]
223
- if enhancer_model:
224
- processors.append("face_enhancer")
225
 
226
- # 🔥 CLI команда
227
  cmd = [
228
  "python", str(FACEFUSION_PY),
229
  "headless-run",
@@ -231,21 +166,36 @@ async def _process_face_swap(
231
  # Файлы
232
  "-s", str(source_path),
233
  "-t", str(target_path),
234
- "-o", str(output_path), # 🔥 Всегда .jpg!
 
 
 
 
 
 
 
 
 
 
 
 
235
 
236
- # Процессоры и модель
237
- "--processors", *processors,
238
- "--face-swapper-model", swapper_model,
 
 
239
 
240
- # Маски для качественного blending
241
  "--face-mask-types", *CONFIG["face_mask_types"],
242
- "--face-mask-blur", str(CONFIG["face_mask_blur"]),
243
- "--face-mask-padding", *map(str, CONFIG["face_mask_padding"]),
244
 
245
- # Качество
246
  "--output-image-quality", CONFIG["output_image_quality"],
 
247
 
248
- # Логирование
249
  "--log-level", CONFIG["log_level"],
250
  ]
251
 
@@ -253,22 +203,20 @@ async def _process_face_swap(
253
  if CONFIG["skip_download"]:
254
  cmd.append("--skip-download")
255
 
256
- # Enhancer если указан
257
- if enhancer_model:
258
- cmd.extend([
259
- "--face-enhancer-model", enhancer_model,
260
- "--face-enhancer-blend", str(enhance_blend),
261
- ])
262
-
263
- # Убираем None значения
264
  cmd = [arg for arg in cmd if arg is not None]
265
 
266
  logger.info(f"🚀 Running: {' '.join(cmd)}")
267
  process_start = time.time()
268
 
269
- # 🔥 Передаём ENV с отключённым NSFW
270
- env = {**os.environ, "OMP_NUM_THREADS": "4", "FACEFUSION_CONTENT_ANALYSER": "none"}
 
 
 
 
271
 
 
272
  process = subprocess.Popen(
273
  cmd,
274
  stdout=subprocess.PIPE,
@@ -279,35 +227,38 @@ async def _process_face_swap(
279
  )
280
 
281
  try:
282
- stdout, stderr = process.communicate(timeout=timeout)
283
  except subprocess.TimeoutExpired:
284
  process.kill()
285
  process.communicate()
286
- logger.error(f"⏱️ Timeout after {timeout}s")
287
- raise HTTPException(504, f"⏱️ Timeout: обработка заняла больше {timeout} секунд")
 
 
 
 
288
 
289
  elapsed = time.time() - process_start
290
  logger.info(f"⏱️ Done in {elapsed:.1f}s, code={process.returncode}")
291
 
292
- # 🔥 Фильтруем harmless warnings из stderr
293
  if stderr:
294
  stderr_clean = '\n'.join(
295
- l for l in stderr.split('\n')
296
  if 'iCCP' not in l and 'libpng' not in l.lower()
297
  ).strip()
298
  if stderr_clean:
299
- logger.info(f"📋 STDERR: {stderr_clean[-400:]}")
300
 
301
  # 🔥 Проверяем результат
302
  if process.returncode != 0:
303
- error_msg = stderr.strip()[-400:] if stderr else "Unknown error"
304
  logger.error(f"❌ FaceFusion failed: {error_msg}")
305
  raise RuntimeError(f"FaceFusion error: {error_msg}")
306
 
307
  # 🔥 Ищем выходной файл
308
  result_file = output_path if output_path.exists() else None
309
  if not result_file:
310
- # Fallback: ищем любой output*.jpg
311
  for f in Path(temp_dir).glob("output*.jpg"):
312
  result_file = f
313
  break
@@ -315,19 +266,25 @@ async def _process_face_swap(
315
  if not result_file or not result_file.exists():
316
  raise RuntimeError("Output image not created")
317
 
318
- # 🔥 Читаем и возвращаем результат
319
  image_data = result_file.read_bytes()
320
 
321
- logger.info(f"✅ Success: {len(image_data)/1024:.1f}KB in {elapsed:.1f}s")
 
 
 
322
 
 
323
  return Response(
324
  content=image_data,
325
- media_type="image/jpeg", # 🔥 ВСЕГДА JPEG!
326
  headers={
327
  "X-Processing-Time": f"{elapsed:.1f}",
328
- "X-Swapper-Model": swapper_model,
329
- "X-Enhancer-Model": enhancer_model or "none",
330
- "X-Output-Format": "jpeg",
 
 
331
  "Cache-Control": "no-store"
332
  }
333
  )
@@ -336,9 +293,9 @@ async def _process_face_swap(
336
  raise
337
  except Exception as e:
338
  logger.exception(f"💥 Error: {e}")
339
- raise
340
  finally:
341
- # 🔥 Очистка временных файлов
342
  if temp_dir and Path(temp_dir).exists():
343
  try:
344
  shutil.rmtree(temp_dir, ignore_errors=True)
@@ -346,48 +303,6 @@ async def _process_face_swap(
346
  except Exception as e:
347
  logger.warning(f"⚠️ Could not clean: {e}")
348
 
349
- # ============================================
350
- # 🔥 УПРОЩЁННЫЕ ЭНДПОИНТЫ
351
- # ============================================
352
-
353
- @app.post("/swap/quick")
354
- async def swap_quick(
355
- source: UploadFile = File(..., description="Фото лица"),
356
- target: UploadFile = File(..., description="Целевое изображение")
357
- ):
358
- """
359
- ⚡ Быстрая замена лица (inswapper_128 без enhancer)
360
- Время: ~30-60 секунд
361
- Выход: JPEG
362
- """
363
- return await swap_face(
364
- source=source,
365
- target=target,
366
- swapper_model="inswapper_128",
367
- enhancer_model="none",
368
- use_fallback=False
369
- )
370
-
371
- @app.post("/swap/hq")
372
- async def swap_hq(
373
- source: UploadFile = File(..., description="Фото лица"),
374
- target: UploadFile = File(..., description="Целевое изображение"),
375
- with_enhancer: bool = Query(default=True, description="Включить улучшение лица GFPGAN")
376
- ):
377
- """
378
- ⭐ Максимальное качество (ghost_3_256 + gfpgan_1.4)
379
- Время: ~90-180 секунд
380
- Выход: JPEG
381
- """
382
- return await swap_face(
383
- source=source,
384
- target=target,
385
- swapper_model="ghost_3_256",
386
- enhancer_model="gfpgan_1.4" if with_enhancer else "none",
387
- enhance_blend=80,
388
- use_fallback=True
389
- )
390
-
391
  # ============================================
392
  # 🔥 ЗАПУСК
393
  # ============================================
@@ -399,5 +314,5 @@ if __name__ == "__main__":
399
  host="0.0.0.0",
400
  port=7860,
401
  log_level="info",
402
- timeout_keep_alive=900 # 15 минут keep-alive
403
  )
 
1
  #!/usr/bin/env python3
2
  """
3
+ 🔥 FaceFusion API — MAXIMUM QUALITY ONLY
4
+ ✅ ghost_3_256 + CodeFormer@90
5
+ ✅ RetinaFace 640px детекция
6
+ ✅ Чёткие границы маски
7
+ ✅ JPEG quality 95
8
+ ✅ Один эндпоинт: /swap
9
  """
10
 
11
  import os, sys, tempfile, subprocess, logging, shutil, time
12
  from pathlib import Path
13
  from contextlib import asynccontextmanager
14
+ from fastapi import FastAPI, File, UploadFile, HTTPException
15
  from fastapi.responses import Response
16
 
17
  # 🔥 Настройка логирования
 
24
 
25
  @asynccontextmanager
26
  async def lifespan(app: FastAPI):
27
+ """Startup/Shutdown"""
28
+ logger.info("🚀 FaceFusion MAX QUALITY starting...")
29
+ logger.info("🔥 ghost_3_256 + CodeFormer@90 + RetinaFace")
30
+ logger.info("📐 Output: JPEG quality 95")
31
+ logger.info("⏱️ Timeout: 300s")
32
+ logger.info("✅ Ready!")
 
 
 
33
  yield
34
+ logger.info("👋 Shutting down...")
35
 
36
+ app = FastAPI(title="FaceFusion MAX QUALITY", version="1.0", lifespan=lifespan)
 
 
 
 
37
 
38
  # 🔥 Пути
39
  FACEFUSION_DIR = Path("/facefusion")
 
44
  # 🔥 Проверка установки
45
  if not FACEFUSION_PY.exists():
46
  logger.error(f"❌ FaceFusion not found at {FACEFUSION_PY}")
47
+ raise RuntimeError("FaceFusion not installed")
48
 
49
+ # 🔥 🔥 🔥 МАКСИМАЛЬНОЕ КАЧЕСТВО — ЖЁСТКИЕ НАСТРОЙКИ
50
  CONFIG = {
51
+ # 🔹 МОДЕЛИ (только лучшие)
52
+ "face_swapper": "ghost_3_256", # 🔥 Лучшая модель замены
53
+ "face_enhancer": "codeformer", # 🔥 Лучшее восстановление
54
+
55
+ # 🔹 ПАРАМЕТРЫ CODEFORMER
56
+ "codeformer_weight": "0.7", # Сила восстановления
57
+ "codeformer_skip_weight": "0.5", # Баланс естественности
58
+ "enhance_blend": "90", # 🔥 Сильное улучшение
59
+
60
+ # 🔹 ДЕТЕКЦИЯ ЛИЦА
61
+ "face_detector_model": "retinaface", # 🔥 Точнее чем yunet
62
+ "face_detector_size": "640", # 🔥 Больше разрешение
63
+ "face_landmarker_model": "2dfan4",
64
+ "face_landmarker_score": "0.75",
65
+
66
+ # 🔹 МАСКА (чёткие границы + контекст)
67
+ "face_mask_types": ["box", "occlusion"], # Двойная точность
68
+ "face_mask_blur": "0.4", # 🔥 Чётче чем 0.6
69
+ "face_mask_padding": ["15", "15", "15", "15"], # 🔥 Больше контекста
70
+
71
+ # 🔹 ВЫВОД
72
+ "output_image_quality": "95", # 🔥 Максимум качества
73
+ "output_image_format": "jpg",
74
+
75
+ # 🔥 ТАЙМАУТ (ghost_3_256 + codeformer = медленно)
76
+ "timeout": 300, # 5 минут
77
+
78
+ # 🔹 ПРОЧЕЕ
79
  "skip_download": False,
80
  "log_level": "error",
81
  }
82
 
83
+ # 🔥 Отключаем NSFW фильтр
84
  os.environ["FACEFUSION_CONTENT_ANALYSER"] = "none"
85
 
 
 
 
86
  # ============================================
87
+ # 🔥 ЕДИНСТВЕННЫЙ ЭНДПОИНТ
88
  # ============================================
89
 
90
  @app.get("/")
91
  async def root():
92
  """Информация о с��рвисе"""
93
  return {
94
+ "service": "FaceFusion MAX QUALITY",
95
+ "version": "1.0",
96
+ "swapper": CONFIG["face_swapper"],
97
+ "enhancer": CONFIG["face_enhancer"],
98
+ "output": f"JPEG quality {CONFIG['output_image_quality']}",
99
+ "detector": f"{CONFIG['face_detector_model']}@{CONFIG['face_detector_size']}",
100
+ "timeout": f"{CONFIG['timeout']}s",
101
  "status": "running"
102
  }
103
 
104
  @app.get("/health")
105
  async def health():
106
+ """Health check"""
107
  return {"status": "ok"}
108
 
109
  @app.post("/swap")
110
  async def swap_face(
111
+ source: UploadFile = File(..., description="Фото лица для замены"),
112
+ target: UploadFile = File(..., description="Целевое изображение")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  ):
114
  """
115
+ 🔥🔥🔥 ЗАМЕНА ЛИЦА — МАКСИМАЛЬНОЕ КАЧЕСТВО
116
 
117
+ 🔹 Модель: ghost_3_256 (лучшая)
118
+ 🔹 Enhancer: CodeFormer@90 (восстановление деталей)
119
+ 🔹 Детектор: RetinaFace 640px (точная посадка)
120
+ 🔹 Маска: blur=0.4, padding=15% (чёткие границы)
121
+ 🔹 Вывод: JPEG quality 95
122
 
123
+ ⏱️ Время: 90-180 секунд
124
+ 🎯 Результат: 🔥🔥🔥🔥🔥
 
 
 
 
 
 
 
 
125
  """
126
+
127
+ # 🔥 Читаем файлы
128
  try:
129
  source_bytes = await source.read()
130
  target_bytes = await target.read()
131
  except Exception as e:
132
+ raise HTTPException(400, f"Failed to read files: {str(e)[:100]}")
133
 
134
  if not source_bytes or not target_bytes:
135
  raise HTTPException(400, "Empty file uploaded")
136
 
137
+ logger.info(
138
+ f"🔥 MAX QUALITY request: "
139
+ f"source={len(source_bytes)}b, target={len(target_bytes)}b"
140
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  temp_dir = None
143
 
144
  try:
145
+ temp_dir = tempfile.mkdtemp(prefix="ff_max_")
146
 
147
+ # 🔥 Пути файлов
148
  source_path = Path(temp_dir) / "source.jpg"
149
  target_path = Path(temp_dir) / "target.jpg"
150
+ output_path = Path(temp_dir) / "output.jpg" # Всегда .jpg
151
 
152
+ # 🔥 Записываем байты
 
 
 
 
 
153
  source_path.write_bytes(source_bytes)
154
  target_path.write_bytes(target_bytes)
155
 
156
+ logger.info(
157
+ f"🔥 Processing: ghost_3_256 + codeformer@90, "
158
+ f"retinaface@640, mask_blur=0.4, output=jpg@95"
159
+ )
160
 
161
+ # 🔥 🔥 🔥 CLI КОМАНДА С МАКСИМАЛЬНЫМИ НАСТРОЙКАМИ
162
  cmd = [
163
  "python", str(FACEFUSION_PY),
164
  "headless-run",
 
166
  # Файлы
167
  "-s", str(source_path),
168
  "-t", str(target_path),
169
+ "-o", str(output_path),
170
+
171
+ # 🔥 Процессоры
172
+ "--processors", "face_swapper", "face_enhancer",
173
+
174
+ # 🔥 МОДЕЛИ (только лучшие)
175
+ "--face-swapper-model", CONFIG["face_swapper"],
176
+ "--face-enhancer-model", CONFIG["face_enhancer"],
177
+
178
+ # 🔥 CodeFormer параметры
179
+ "--codeformer-weight", CONFIG["codeformer_weight"],
180
+ "--codeformer-skip-weight", CONFIG["codeformer_skip_weight"],
181
+ "--face-enhancer-blend", CONFIG["enhance_blend"],
182
 
183
+ # 🔥 ДЕТЕКЦИЯ (максимальная точность)
184
+ "--face-detector-model", CONFIG["face_detector_model"],
185
+ "--face-detector-size", CONFIG["face_detector_size"],
186
+ "--face-landmarker-model", CONFIG["face_landmarker_model"],
187
+ "--face-landmarker-score", CONFIG["face_landmarker_score"],
188
 
189
+ # 🔥 МАСКА (чёткие границы + контекст)
190
  "--face-mask-types", *CONFIG["face_mask_types"],
191
+ "--face-mask-blur", CONFIG["face_mask_blur"],
192
+ "--face-mask-padding", *CONFIG["face_mask_padding"],
193
 
194
+ # 🔥 ВЫВОД (максимум качества)
195
  "--output-image-quality", CONFIG["output_image_quality"],
196
+ "--output-image-format", CONFIG["output_image_format"],
197
 
198
+ # 🔥 Логирование
199
  "--log-level", CONFIG["log_level"],
200
  ]
201
 
 
203
  if CONFIG["skip_download"]:
204
  cmd.append("--skip-download")
205
 
206
+ # Убираем None
 
 
 
 
 
 
 
207
  cmd = [arg for arg in cmd if arg is not None]
208
 
209
  logger.info(f"🚀 Running: {' '.join(cmd)}")
210
  process_start = time.time()
211
 
212
+ # 🔥 ENV переменные
213
+ env = {
214
+ **os.environ,
215
+ "OMP_NUM_THREADS": "4",
216
+ "FACEFUSION_CONTENT_ANALYSER": "none"
217
+ }
218
 
219
+ # 🔥 Запускаем процесс
220
  process = subprocess.Popen(
221
  cmd,
222
  stdout=subprocess.PIPE,
 
227
  )
228
 
229
  try:
230
+ stdout, stderr = process.communicate(timeout=CONFIG["timeout"])
231
  except subprocess.TimeoutExpired:
232
  process.kill()
233
  process.communicate()
234
+ logger.error(f"⏱️ Timeout after {CONFIG['timeout']}s")
235
+ raise HTTPException(
236
+ 504,
237
+ f"⏱️ Timeout: обработка заняла больше {CONFIG['timeout']} секунд. "
238
+ f"ghost_3_256 + CodeFormer требуют времени для максимального качества."
239
+ )
240
 
241
  elapsed = time.time() - process_start
242
  logger.info(f"⏱️ Done in {elapsed:.1f}s, code={process.returncode}")
243
 
244
+ # 🔥 Фильтруем шумные warnings
245
  if stderr:
246
  stderr_clean = '\n'.join(
247
+ l for l in stderr.split('\n')
248
  if 'iCCP' not in l and 'libpng' not in l.lower()
249
  ).strip()
250
  if stderr_clean:
251
+ logger.info(f"📋 STDERR: {stderr_clean[-300:]}")
252
 
253
  # 🔥 Проверяем результат
254
  if process.returncode != 0:
255
+ error_msg = stderr.strip()[-300:] if stderr else "Unknown error"
256
  logger.error(f"❌ FaceFusion failed: {error_msg}")
257
  raise RuntimeError(f"FaceFusion error: {error_msg}")
258
 
259
  # 🔥 Ищем выходной файл
260
  result_file = output_path if output_path.exists() else None
261
  if not result_file:
 
262
  for f in Path(temp_dir).glob("output*.jpg"):
263
  result_file = f
264
  break
 
266
  if not result_file or not result_file.exists():
267
  raise RuntimeError("Output image not created")
268
 
269
+ # 🔥 Читаем результат
270
  image_data = result_file.read_bytes()
271
 
272
+ logger.info(
273
+ f"✅ MAX QUALITY success: "
274
+ f"{len(image_data)/1024:.1f}KB in {elapsed:.1f}s"
275
+ )
276
 
277
+ # 🔥 Возвращаем с заголовками для отладки
278
  return Response(
279
  content=image_data,
280
+ media_type="image/jpeg",
281
  headers={
282
  "X-Processing-Time": f"{elapsed:.1f}",
283
+ "X-Swapper": CONFIG["face_swapper"],
284
+ "X-Enhancer": f"{CONFIG['face_enhancer']}@{CONFIG['enhance_blend']}",
285
+ "X-Detector": f"{CONFIG['face_detector_model']}@{CONFIG['face_detector_size']}",
286
+ "X-Mask-Blur": CONFIG["face_mask_blur"],
287
+ "X-Output-Quality": CONFIG["output_image_quality"],
288
  "Cache-Control": "no-store"
289
  }
290
  )
 
293
  raise
294
  except Exception as e:
295
  logger.exception(f"💥 Error: {e}")
296
+ raise HTTPException(500, f"Internal error: {str(e)[:300]}")
297
  finally:
298
+ # 🔥 Очистка temp файлов
299
  if temp_dir and Path(temp_dir).exists():
300
  try:
301
  shutil.rmtree(temp_dir, ignore_errors=True)
 
303
  except Exception as e:
304
  logger.warning(f"⚠️ Could not clean: {e}")
305
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
306
  # ============================================
307
  # 🔥 ЗАПУСК
308
  # ============================================
 
314
  host="0.0.0.0",
315
  port=7860,
316
  log_level="info",
317
+ timeout_keep_alive=CONFIG["timeout"]
318
  )