Spaces:
Sleeping
Sleeping
Delete main.py
Browse files
main.py
DELETED
|
@@ -1,351 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Face Swap + Gemini API
|
| 3 |
-
======================
|
| 4 |
-
Merged from python-api/main.py + python-api/python-api/main.py
|
| 5 |
-
All Railway deployment fixes applied.
|
| 6 |
-
|
| 7 |
-
Endpoints
|
| 8 |
-
─────────
|
| 9 |
-
GET / → health check
|
| 10 |
-
GET /health → health check (alias)
|
| 11 |
-
POST /swap → InsightFace face-swap (lazy-loaded, won't block startup)
|
| 12 |
-
POST /gemini/generate → Gemini multimodal generation (legacy SDK)
|
| 13 |
-
POST /ai → Gemini text generation (new SDK, from ai_service)
|
| 14 |
-
POST /face → face detection stub (from face_service)
|
| 15 |
-
"""
|
| 16 |
-
|
| 17 |
-
from __future__ import annotations
|
| 18 |
-
|
| 19 |
-
import base64
|
| 20 |
-
import os
|
| 21 |
-
import sys
|
| 22 |
-
import gc
|
| 23 |
-
|
| 24 |
-
# Silence chatty libraries BEFORE imports
|
| 25 |
-
os.environ["ORT_LOGGING_LEVEL"] = "3"
|
| 26 |
-
os.environ["KMP_WARNINGS"] = "0"
|
| 27 |
-
os.environ["INSIGHTFACE_HOME"] = "/app/models"
|
| 28 |
-
os.environ["PYTHONUNBUFFERED"] = "1"
|
| 29 |
-
|
| 30 |
-
import traceback
|
| 31 |
-
import logging
|
| 32 |
-
import warnings
|
| 33 |
-
from pathlib import Path
|
| 34 |
-
from typing import Optional
|
| 35 |
-
|
| 36 |
-
logging.getLogger("onnxruntime").setLevel(logging.ERROR)
|
| 37 |
-
logging.getLogger("insightface").setLevel(logging.ERROR)
|
| 38 |
-
warnings.filterwarnings("ignore")
|
| 39 |
-
|
| 40 |
-
# print(">>> NEW VERSION DEPLOYED - Python AI API starting up", flush=True)
|
| 41 |
-
|
| 42 |
-
import numpy as np
|
| 43 |
-
from fastapi import FastAPI, HTTPException, Request
|
| 44 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 45 |
-
from fastapi.responses import JSONResponse
|
| 46 |
-
from pydantic import BaseModel
|
| 47 |
-
|
| 48 |
-
# Service modules (your original files, also fixed)
|
| 49 |
-
from ai_service import generate_ai_response
|
| 50 |
-
from face_service import process_face
|
| 51 |
-
|
| 52 |
-
# ── App ───────────────────────────────────────────────────────────────────────
|
| 53 |
-
|
| 54 |
-
app = FastAPI(title="Face Swap + Gemini API", version="2.0.0")
|
| 55 |
-
|
| 56 |
-
# Allow requests from any origin (Netlify, localhost, etc.)
|
| 57 |
-
app.add_middleware(
|
| 58 |
-
CORSMiddleware,
|
| 59 |
-
allow_origins=["*"],
|
| 60 |
-
allow_credentials=True,
|
| 61 |
-
allow_methods=["*"],
|
| 62 |
-
allow_headers=["*"],
|
| 63 |
-
)
|
| 64 |
-
|
| 65 |
-
# Global exception handler — always return JSON, never bare HTML 500 pages
|
| 66 |
-
@app.exception_handler(Exception)
|
| 67 |
-
async def _global_exc_handler(request: Request, exc: Exception) -> JSONResponse:
|
| 68 |
-
# traceback.print_exc(file=sys.stderr)
|
| 69 |
-
return JSONResponse(
|
| 70 |
-
status_code=500,
|
| 71 |
-
content={"error": str(exc) or "Internal server error"},
|
| 72 |
-
)
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 76 |
-
# InsightFace — optional, guarded import
|
| 77 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 78 |
-
|
| 79 |
-
MODEL_DIR = Path(__file__).parent / "models"
|
| 80 |
-
SWAPPER_PATH = MODEL_DIR / "inswapper_128.onnx"
|
| 81 |
-
|
| 82 |
-
# Module-level handles — populated at startup
|
| 83 |
-
_face_analyser = None
|
| 84 |
-
_face_swapper = None
|
| 85 |
-
_celeb_cache: dict[str, object] = {}
|
| 86 |
-
|
| 87 |
-
try:
|
| 88 |
-
import cv2 # noqa: F401 — import check only
|
| 89 |
-
import insightface # noqa: F401
|
| 90 |
-
_INSIGHTFACE_AVAILABLE = True
|
| 91 |
-
|
| 92 |
-
from insightface.app import FaceAnalysis
|
| 93 |
-
from insightface.model_zoo import get_model
|
| 94 |
-
|
| 95 |
-
# print("⏳ Loading FaceAnalysis (buffalo_sc) once globally...", flush=True)
|
| 96 |
-
os.environ["INSIGHTFACE_HOME"] = "/app/models"
|
| 97 |
-
_face_analyser = FaceAnalysis(
|
| 98 |
-
name="buffalo_sc",
|
| 99 |
-
root="/app/models",
|
| 100 |
-
providers=["CPUExecutionProvider"]
|
| 101 |
-
)
|
| 102 |
-
_face_analyser.prepare(
|
| 103 |
-
ctx_id=-1,
|
| 104 |
-
det_size=(192, 192)
|
| 105 |
-
)
|
| 106 |
-
# print("✅ FaceAnalysis ready", flush=True)
|
| 107 |
-
|
| 108 |
-
except ImportError:
|
| 109 |
-
_INSIGHTFACE_AVAILABLE = False
|
| 110 |
-
print("⚠️ insightface/cv2 not installed — /swap will return 503", file=sys.stderr)
|
| 111 |
-
except Exception as e:
|
| 112 |
-
print(f"❌ Error loading models at startup: {e}", flush=True)
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
def _load_inswapper():
|
| 116 |
-
"""Lazily load inswapper model if not already loaded."""
|
| 117 |
-
global _face_swapper
|
| 118 |
-
if _face_swapper is not None:
|
| 119 |
-
return _face_swapper
|
| 120 |
-
|
| 121 |
-
from insightface.model_zoo import get_model
|
| 122 |
-
swapper_path = "/app/models/inswapper_128.onnx"
|
| 123 |
-
if not os.path.exists(swapper_path):
|
| 124 |
-
swapper_path = str(MODEL_DIR / "inswapper_128.onnx")
|
| 125 |
-
|
| 126 |
-
# print(f"⏳ Loading inswapper lazily from: {swapper_path}", flush=True)
|
| 127 |
-
_face_swapper = get_model(
|
| 128 |
-
swapper_path,
|
| 129 |
-
providers=["CPUExecutionProvider"]
|
| 130 |
-
)
|
| 131 |
-
# if _face_swapper:
|
| 132 |
-
# print("✅ Inswapper ready", flush=True)
|
| 133 |
-
# else:
|
| 134 |
-
# print("❌ Inswapper failed to load (returned None)", flush=True)
|
| 135 |
-
# raise HTTPException(500, "Failed to load inswapper model")
|
| 136 |
-
|
| 137 |
-
return _face_swapper
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
# ── Image helpers (your original code, unchanged) ─────────────────────────────
|
| 141 |
-
|
| 142 |
-
def b64_to_img(b64: str) -> "np.ndarray":
|
| 143 |
-
import cv2
|
| 144 |
-
if "," in b64:
|
| 145 |
-
b64 = b64.split(",", 1)[1]
|
| 146 |
-
data = base64.b64decode(b64)
|
| 147 |
-
arr = np.frombuffer(data, np.uint8)
|
| 148 |
-
img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
|
| 149 |
-
if img is None:
|
| 150 |
-
raise ValueError("Could not decode image")
|
| 151 |
-
|
| 152 |
-
# Optimization: shrink incoming images to prevent OOM
|
| 153 |
-
h, w = img.shape[:2]
|
| 154 |
-
max_size = 720
|
| 155 |
-
if max(h, w) > max_size:
|
| 156 |
-
scale = max_size / max(h, w)
|
| 157 |
-
img = cv2.resize(
|
| 158 |
-
img,
|
| 159 |
-
(int(w * scale), int(h * scale))
|
| 160 |
-
)
|
| 161 |
-
|
| 162 |
-
return img
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
def img_to_b64(img: "np.ndarray", quality: int = 85) -> str:
|
| 166 |
-
import cv2
|
| 167 |
-
_, buf = cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, quality])
|
| 168 |
-
return base64.b64encode(buf).decode()
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
def best_face(analyser, img: "np.ndarray"):
|
| 172 |
-
faces = analyser.get(img)
|
| 173 |
-
if not faces:
|
| 174 |
-
return None
|
| 175 |
-
return max(faces, key=lambda f: (f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1]))
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
# ── Pydantic models ───────────────────────────────────────────────────────────
|
| 179 |
-
|
| 180 |
-
class SwapRequest(BaseModel):
|
| 181 |
-
source_key: str
|
| 182 |
-
source_b64: Optional[str] = None
|
| 183 |
-
target_b64: str
|
| 184 |
-
quality: int = 55
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
class AIRequest(BaseModel):
|
| 188 |
-
prompt: str
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
class GeminiPart(BaseModel):
|
| 192 |
-
text: Optional[str] = None
|
| 193 |
-
inlineData: Optional[dict] = None
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
class GeminiRequest(BaseModel):
|
| 197 |
-
systemInstruction: str
|
| 198 |
-
parts: list[GeminiPart]
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 202 |
-
# Routes
|
| 203 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 204 |
-
|
| 205 |
-
# ── Health ────────────────────────────────────────────────────────────────────
|
| 206 |
-
|
| 207 |
-
@app.get("/")
|
| 208 |
-
@app.get("/health")
|
| 209 |
-
def health():
|
| 210 |
-
face_models_in_memory = _face_analyser is not None and _face_swapper is not None
|
| 211 |
-
return {
|
| 212 |
-
"status": "ok",
|
| 213 |
-
# NOTE: models are lazy-loaded on first /swap POST, so this is False
|
| 214 |
-
# until the first swap request. We separately expose server_ready=True
|
| 215 |
-
# so the frontend can distinguish "server up but models not yet warm"
|
| 216 |
-
# from "server unreachable".
|
| 217 |
-
"models_loaded": face_models_in_memory,
|
| 218 |
-
# Always True while the server is running — frontend uses this for the
|
| 219 |
-
# reachability check instead of models_loaded.
|
| 220 |
-
"server_ready": True,
|
| 221 |
-
"insightface_available": _INSIGHTFACE_AVAILABLE,
|
| 222 |
-
"cached_faces": list(_celeb_cache.keys()),
|
| 223 |
-
"gemini_configured": bool(os.getenv("GEMINI_API_KEY")),
|
| 224 |
-
}
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
@app.get("/debug")
|
| 228 |
-
def debug():
|
| 229 |
-
return {
|
| 230 |
-
"models_folder_exists": os.path.exists("/app/models"),
|
| 231 |
-
"models": os.listdir("/app/models") if os.path.exists("/app/models") else "not found",
|
| 232 |
-
"inswapper_exists": os.path.exists("/app/models/inswapper_128.onnx")
|
| 233 |
-
}
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
# ── Face swap (your original logic, now loaded globally) ─────────────────────
|
| 237 |
-
|
| 238 |
-
@app.post("/swap")
|
| 239 |
-
async def swap(req: SwapRequest):
|
| 240 |
-
global _face_analyser
|
| 241 |
-
if _face_analyser is None:
|
| 242 |
-
raise HTTPException(503, "FaceAnalysis model is not loaded on this server.")
|
| 243 |
-
|
| 244 |
-
# Lazy load swapper
|
| 245 |
-
swapper = _load_inswapper()
|
| 246 |
-
|
| 247 |
-
# 1. Cache celebrity face if not already done
|
| 248 |
-
if req.source_key not in _celeb_cache:
|
| 249 |
-
if not req.source_b64:
|
| 250 |
-
raise HTTPException(400, "source_b64 required for first call with this key")
|
| 251 |
-
src_img = b64_to_img(req.source_b64)
|
| 252 |
-
face = best_face(_face_analyser, src_img)
|
| 253 |
-
if face is None:
|
| 254 |
-
raise HTTPException(422, "No face detected in source image")
|
| 255 |
-
_celeb_cache[req.source_key] = face
|
| 256 |
-
|
| 257 |
-
source_face = _celeb_cache[req.source_key]
|
| 258 |
-
|
| 259 |
-
# 2. Decode target frame
|
| 260 |
-
if not req.target_b64:
|
| 261 |
-
raise HTTPException(400, "target_b64 required")
|
| 262 |
-
target_img = b64_to_img(req.target_b64)
|
| 263 |
-
target_faces = _face_analyser.get(target_img)
|
| 264 |
-
|
| 265 |
-
# 3. No face in target → return original unchanged
|
| 266 |
-
if not target_faces:
|
| 267 |
-
return {"swapped": False, "frame": img_to_b64(target_img, req.quality)}
|
| 268 |
-
|
| 269 |
-
# 4. Swap the largest detected face
|
| 270 |
-
target_face = max(
|
| 271 |
-
target_faces,
|
| 272 |
-
key=lambda f: (f.bbox[2] - f.bbox[0]) * (f.bbox[3] - f.bbox[1]),
|
| 273 |
-
)
|
| 274 |
-
result = swapper.get(target_img, target_face, source_face, paste_back=True)
|
| 275 |
-
|
| 276 |
-
# Free memory after heavy processing
|
| 277 |
-
gc.collect()
|
| 278 |
-
|
| 279 |
-
return {"swapped": True, "frame": img_to_b64(result, req.quality)}
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
# ── Gemini multimodal (your original /gemini/generate endpoint, fixed) ────────
|
| 283 |
-
|
| 284 |
-
@app.post("/gemini/generate")
|
| 285 |
-
async def generate_gemini(req: GeminiRequest):
|
| 286 |
-
# Guard: package must be installed
|
| 287 |
-
try:
|
| 288 |
-
import google.generativeai as genai
|
| 289 |
-
except ImportError:
|
| 290 |
-
raise HTTPException(503, "google-generativeai is not installed.")
|
| 291 |
-
|
| 292 |
-
api_key = os.getenv("GEMINI_API_KEY")
|
| 293 |
-
if not api_key:
|
| 294 |
-
raise HTTPException(500, "GEMINI_API_KEY is not configured on Railway.")
|
| 295 |
-
|
| 296 |
-
genai.configure(api_key=api_key)
|
| 297 |
-
|
| 298 |
-
# FIX: gemini-3.1-pro-preview does not exist — use env var or safe default
|
| 299 |
-
model_name = os.getenv("GEMINI_MODEL", "gemini-1.5-pro")
|
| 300 |
-
model = genai.GenerativeModel(model_name)
|
| 301 |
-
|
| 302 |
-
try:
|
| 303 |
-
# Build content parts (your original logic, unchanged)
|
| 304 |
-
from google.generativeai import types
|
| 305 |
-
content_parts = []
|
| 306 |
-
for p in req.parts:
|
| 307 |
-
if p.text:
|
| 308 |
-
content_parts.append(types.Part(text=p.text))
|
| 309 |
-
elif p.inlineData:
|
| 310 |
-
m_type = p.inlineData.get("mimeType") or p.inlineData.get("mime_type")
|
| 311 |
-
m_data = p.inlineData.get("data")
|
| 312 |
-
if m_type and m_data:
|
| 313 |
-
content_parts.append(
|
| 314 |
-
types.Part(
|
| 315 |
-
inline_data=types.Blob(
|
| 316 |
-
mime_type=m_type,
|
| 317 |
-
data=m_data,
|
| 318 |
-
)
|
| 319 |
-
)
|
| 320 |
-
)
|
| 321 |
-
|
| 322 |
-
response = model.generate_content(
|
| 323 |
-
contents=content_parts,
|
| 324 |
-
generation_config=genai.GenerationConfig(temperature=0.1),
|
| 325 |
-
system_instruction=req.systemInstruction,
|
| 326 |
-
)
|
| 327 |
-
return {"text": getattr(response, "text", str(response))}
|
| 328 |
-
|
| 329 |
-
except Exception as exc:
|
| 330 |
-
raise HTTPException(500, str(exc)) from exc
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
# ── Simple AI text endpoint (from your original python-api/main.py) ───────────
|
| 334 |
-
|
| 335 |
-
@app.post("/ai")
|
| 336 |
-
def ai(req: AIRequest):
|
| 337 |
-
"""Thin wrapper around ai_service.generate_ai_response."""
|
| 338 |
-
return {"result": generate_ai_response(req.prompt)}
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
# ── Face stub endpoint (from your original python-api/main.py) ───────────────
|
| 342 |
-
@app.post("/face")
|
| 343 |
-
def face(data: dict):
|
| 344 |
-
"""Thin wrapper around face_service.process_face."""
|
| 345 |
-
return {"result": process_face(data)}
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
if __name__ == "__main__":
|
| 349 |
-
import uvicorn
|
| 350 |
-
port = int(os.environ.get("PORT", 7860))
|
| 351 |
-
uvicorn.run(app, host="0.0.0.0", port=port, access_log=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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