Spaces:
Running
Running
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485#!/usr/bin/env python3import osimport tempfileimport subprocessimport loggingimport shutilimport uuidimport timefrom fastapi import FastAPI, File, UploadFile, HTTPExceptionfrom fastapi.responses import Responselogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)app = FastAPI(title="FaceFusion API")FACEFUSION_DIR = "/facefusion"FACEFUSION_SCRIPT = os.path.join(FACEFUSION_DIR, "facefusion.py")# Используем проверенную модель, которая точно есть в словареMODEL_NAME = "inswapper_128"EXECUTION_PROVIDERS = ["cpu"]@app.get("/health")async def health():return {"status": "ok"}@app.post("/swap")async def swap_face(source: UploadFile = File(...), target: UploadFile = File(...)):temp_dir = tempfile.mkdtemp()source_path = os.path.join(temp_dir, f"source_{uuid.uuid4().hex}.jpg")target_path = os.path.join(temp_dir, f"target_{uuid.uuid4().hex}.jpg")output_path = os.path.join(temp_dir, f"output_{uuid.uuid4().hex}.jpg")try:with open(source_path, "wb") as f:f.write(await source.read())with open(target_path, "wb") as f:f.write(await target.read())cmd = ["python", FACEFUSION_SCRIPT,"headless-run","--source", source_path,"--target", target_path,"--output-path", output_path,"--processors", "face_swapper","--face-swapper-model", MODEL_NAME,"--execution-providers", *EXECUTION_PROVIDERS,]logger.info(f"Running command: {' '.join(cmd)}")start = time.time()process = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)stdout, stderr = process.communicate(timeout=180)elapsed = time.time() - startlogger.info(f"Processing took {elapsed:.2f} seconds")if process.returncode != 0:logger.error(f"FaceFusion error: {stderr}")raise HTTPException(status_code=500, detail=f"FaceFusion error: {stderr}")if not os.path.exists(output_path):raise HTTPException(status_code=500, detail="Output file not created")with open(output_path, "rb") as f:image_data = f.read()return Response(content=image_data, media_type="image/jpeg")except subprocess.TimeoutExpired:logger.error("Process timed out")raise HTTPException(status_code=504, detail="Processing timeout")except Exception as e:logger.exception("Unhandled exception")raise HTTPException(status_code=500, detail=str(e))finally:shutil.rmtree(temp_dir, ignore_errors=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319#!/usr/bin/env python3"""🎨 FaceFusion API для Hugging Face Spaces✅ CPU оптимизация + высокое качество замены лица✅ inswapper_128 + gfpgan + proper masking✅ Таймаут 10 минут для CPU"""import os, sys, tempfile, subprocess, logging, shutil, uuid, time, jsonfrom pathlib import Pathfrom fastapi import FastAPI, File, UploadFile, HTTPException, BackgroundTasksfrom fastapi.responses import Response, JSONResponse# 🔥 Настройка логированияlogging.basicConfig(level=logging.INFO,format='%(asctime)s [%(levelname)s] %(message)s',handlers=[logging.StreamHandler(sys.stdout)])logger = logging.getLogger(__name__)app = FastAPI(title="FaceFusion CPU API", version="1.0")# 🔥 ПутиFACEFUSION_DIR = Path("/facefusion")FACEFUSION_PY = FACEFUSION_DIR / "facefusion.py"CACHE_DIR = Path("/tmp/facefusion_cache")CACHE_DIR.mkdir(parents=True, exist_ok=True)# 🔥 Проверка установкиif not FACEFUSION_PY.exists():logger.error(f"❌ FaceFusion not found at {FACEFUSION_PY}")raise RuntimeError("FaceFusion not installed — check Dockerfile")# 🔥 ОПТИМАЛЬНЫЕ НАСТРОЙКИ ДЛЯ CPU + КАЧЕСТВОCONFIG = {# Модель замены лица (единственная стабильная для CPU)"face_swapper": "inswapper_128",# Улучшение лица (gfpgan легче codeformer, но даёт хорошее качество)"face_enhancer": "gfpgan","face_enhancer_blend": 75, # 75% blending для естественного вида# Маски для лучшего blending"face_mask_types": ["box", "occlusion"],"face_mask_blur": 0.6, # Мягкие края маски"face_mask_padding": [10, 10, 10, 10], # Отступы маски [top, right, bottom, left]# Разрешение (512-768 оптимально для CPU, 1024 слишком медленно)"output_image_resolution": 768,# CPU оптимизация"execution_providers": ["cpu"],"cpu_threads": 4, # 4 потока — баланс скорости/RAM"cpu_thread_count": 4,# Прочее"skip_download": True, # Не качать модели каждый раз"log_level": "error", # Меньше логов = быстрее"timeout_seconds": 600, # 10 минут для CPU}# 🔥 Кэширование моделейos.environ["FACEFUSION_CACHE"] = str(CACHE_DIR)os.environ["OMP_NUM_THREADS"] = str(CONFIG["cpu_threads"])@app.get("/")async def root():return {"service": "FaceFusion CPU API","status": "running","config": {k: v for k, v in CONFIG.items() if k != "face_mask_padding"}}@app.get("/health")async def health():"""Health check для Render/HF"""return {"status": "ok", "cache_size_mb": sum(f.stat().st_size for f in CACHE_DIR.rglob('*')) / 1024 / 1024}@app.get("/debug/cli")async def debug_cli():"""Показывает доступные CLI аргументы FaceFusion"""try:result = subprocess.run(["python", str(FACEFUSION_PY), "headless-run", "--help"],capture_output=True, text=True, cwd=FACEFUSION_DIR, timeout=30)# Извлекаем только аргументы связанные с face_swapperlines = result.stdout.split('\n')relevant = [l.strip() for l in lines if 'face-swapper' in l.lower() or 'processor' in l.lower() or 'execution' in l.lower()]return {"available_args": relevant[:20], "full_help_available": True}except Exception as e:return {"error": str(e)}@app.post("/swap")async def swap_face(source: UploadFile = File(..., description="Фото лица (источник)"),target: UploadFile = File(..., description="Целевое изображение"),enhance: bool = True # Параметр: включать ли улучшение лица):"""Замена лица с высоким качеством на CPUArgs:source: Фото лица для замены (анфас, хорошее освещение)target: Изображение куда вставить лицоenhance: Включить GFPGAN улучшение (True = лучше качество, но медленнее)"""temp_dir = Nonestart_time = time.time()try:# 🔥 Создаём временную директориюtemp_dir = tempfile.mkdtemp(prefix="ff_")source_path = Path(temp_dir) / "source.jpg"target_path = Path(temp_dir) / "target.jpg"output_path = Path(temp_dir) / "output.png"logger.info(f"📥 New request: source={source.filename}, target={target.filename}, enhance={enhance}")# Сохраняем файлыsource_path.write_bytes(await source.read())target_path.write_bytes(await target.read())logger.info(f"📁 Files saved: {source_path.stat().st_size}b + {target_path.stat().st_size}b")# 🔥 Формируем CLI команду с ОПТИМАЛЬНЫМИ аргументами для CPU+качествоcmd = ["python", str(FACEFUSION_PY),"headless-run",# Файлы"--sources", str(source_path),"--targets", str(target_path),"--output-path", str(output_path),# Процессоры"--processors", "face_swapper" + (f" face_enhancer" if enhance else ""),# Модель замены лица"--face-swapper-model", CONFIG["face_swapper"],# Модель улучшения (если включено)*(["--face-enhancer-model", CONFIG["face_enhancer"],"--face-enhancer-blend", str(CONFIG["face_enhancer_blend"])] if enhance else []),# Маски для качественного blending"--face-mask-types", *CONFIG["face_mask_types"],"--face-mask-blur", str(CONFIG["face_mask_blur"]),"--face-mask-padding", *map(str, CONFIG["face_mask_padding"]),# Разрешение"--output-image-resolution", str(CONFIG["output_image_resolution"]),# CPU оптимизация"--execution-providers", *CONFIG["execution_providers"],"--execution-thread-count", str(CONFIG["cpu_thread_count"]),# Прочее"--skip-download" if CONFIG["skip_download"] else None,"--log-level", CONFIG["log_level"],]# Убираем None значенияcmd = [arg for arg in cmd if arg is not None]logger.info(f"🚀 Running FaceFusion (enhance={enhance})...")logger.info(f" Command: {' '.join(cmd)}")# 🔥 Запускаем процессprocess = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,cwd=str(FACEFUSION_DIR),env={**os.environ, "OMP_NUM_THREADS": str(CONFIG["cpu_threads"])})# Ждём с таймаутомtry:stdout, stderr = process.communicate(timeout=CONFIG["timeout_seconds"])except subprocess.TimeoutExpired:process.kill()process.communicate()logger.error(f"⏱️ Timeout after {CONFIG['timeout_seconds']}s")raise HTTPException(504, f"⏱️ Timeout: обработка заняла больше {CONFIG['timeout_seconds']} секунд")elapsed = time.time() - start_timelogger.info(f"⏱️ Processing time: {elapsed:.1f}s")# Логируем выводif stdout and CONFIG["log_level"] == "debug":logger.debug(f"📋 STDOUT: {stdout[-500:]}")if stderr:logger.info(f"📋 STDERR: {stderr[-300:]}")# 🔥 Проверяем результатif process.returncode != 0:error_msg = stderr.strip()[-400:] if stderr else "Unknown error"logger.error(f"❌ FaceFusion failed (code {process.returncode}): {error_msg}")raise HTTPException(500, f"FaceFusion error: {error_msg}")# Ищем выходной файл (может быть с другим расширением)result_file = Nonefor ext in [".png", ".jpg", ".jpeg", ".webp"]:candidate = output_path.with_suffix(ext)if candidate.exists():result_file = candidatebreakif not result_file or not result_file.exists():# Попробуем найти любой image в output директорииfor f in Path(temp_dir).glob("output*"):if f.suffix.lower() in [".png", ".jpg", ".jpeg", ".webp"]:result_file = fbreakif not result_file:raise HTTPException(500, "Output image not created")# 🔥 Читаем и возвращаем результатimage_data = result_file.read_bytes()result_size = len(image_data)logger.info(f"✅ Success! Returned {result_size / 1024:.1f}KB in {elapsed:.1f}s")return Response(content=image_data,media_type="image/png",headers={"X-Processing-Time": f"{elapsed:.1f}","X-Result-Size": str(result_size),"Cache-Control": "no-store"})except HTTPException:raiseexcept Exception as e:logger.exception(f"💥 Unexpected error: {type(e).__name__}: {e}")raise HTTPException(500, f"Internal error: {str(e)[:200]}")finally:# 🔥 Очистка временных файловif temp_dir and Path(temp_dir).exists():try:shutil.rmtree(temp_dir, ignore_errors=True)logger.debug(f"🧹 Cleaned temp dir: {temp_dir}")except Exception as e:logger.warning(f"⚠️ Could not clean temp dir: {e}")@app.post("/swap/batch")async def swap_batch(source: UploadFile = File(...),targets: list[UploadFile] = File(...),enhance: bool = True):"""Обработка нескольких целевых изображений за один запрос(полезно для генерации нескольких вариантов)"""if len(targets) > 5:raise HTTPException(400, "Maximum 5 target images per batch")results = []for i, target in enumerate(targets):try:# Создаём fake Request для повторного использования swap_facefrom starlette.datastructures import UploadFile as SFUploadFileresult = await swap_face(source=source,target=target,enhance=enhance)results.append({"index": i, "status": "ok", "size": len(result.body)})except Exception as e:results.append({"index": i, "status": "error", "error": str(e)[:100]})return JSONResponse(content={"batch_results": results})# 🔥 Pre-warm: загрузка моделей при старте (опционально)@app.on_event("startup")async def startup():logger.info("🚀 FaceFusion CPU API starting...")logger.info(f"📁 Cache dir: {CACHE_DIR}")logger.info(f"⚙️ Config: swapper={CONFIG['face_swapper']}, enhancer={CONFIG['face_enhancer']}, resolution={CONFIG['output_image_resolution']}")# 🔥 Предзагрузка моделей (чтобы первый запрос не таймаутил)try:logger.info("📦 Pre-downloading models...")preload_cmd = ["python", str(FACEFUSION_PY),"force-download","--execution-providers", "cpu"]result = subprocess.run(preload_cmd,capture_output=True, text=True,cwd=FACEFUSION_DIR, timeout=120)if result.returncode == 0:logger.info("✅ Models pre-downloaded")else:logger.warning(f"⚠️ Pre-download warning: {result.stderr[-200:]}")except Exception as e:logger.warning(f"⚠️ Could not pre-download models: {e}")logger.info("✅ API ready!")if __name__ == "__main__":import uvicorn# 🔥 Запуск на порту 7860 (требование HF Spaces)uvicorn.run(app,host="0.0.0.0",port=7860,log_level="info",timeout_keep_alive=300 # 5 минут keep-alive для долгих запросов)
app.py+295-61