Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- index (46).html +0 -0
- server (31).py +539 -0
index (46).html
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
server (31).py
ADDED
|
@@ -0,0 +1,539 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
server.py β μΌκ΅΄ μΌκ΄ κ΅μ²΄ (HF Space β Comfy Cloud)
|
| 3 |
+
|
| 4 |
+
POST /api/swap/jobs μ΄λ―Έμ§ 1μ₯ + μ±λ³ β μμ
μμ± (μ¦μ {jobId} λ°ν)
|
| 5 |
+
GET /api/swap/jobs/{id} μν μ‘°ν
|
| 6 |
+
POST /api/swap/cancel μμ
μ·¨μ (λκΈ°Β·μ§ν μ€μΈ μμ
μ Comfy Cloud μμλ λ©μΆ€)
|
| 7 |
+
GET /api/swap/jobs/{id}/thumb 결과 미리보기(JPEG)
|
| 8 |
+
GET /api/swap/jobs/{id}/view κ²°κ³Ό μλ³Έ ν¬κΈ°(미리보기μ©, νμΌλͺ
Β·νμ₯μ μ μ§ νμ)
|
| 9 |
+
GET /api/swap/jobs/{id}/download κ²°κ³Ό λ€μ΄λ‘λ β μ
λ‘λν νμΌλͺ
Β·νμ₯μ κ·Έλλ‘
|
| 10 |
+
POST /api/swap/zip μ νν μμ
ZIP β ν΄λ ꡬ쑰·νμΌλͺ
κ·Έλλ‘
|
| 11 |
+
POST /api/swap/regen μ§λ κ²°κ³Όμ μλ³ΈμΌλ‘ μ κ²°κ³Ό νλ λ (μλ³Έ μ¬μ
λ‘λ μμ΄)
|
| 12 |
+
GET /api/swap/faces μ½μ
ν μΌκ΅΄(λ¨μ/μ¬μ) κΈ°λ³Έ μ 보
|
| 13 |
+
POST /api/swap/faces/{gender} μΌκ΅΄ κ΅μ²΄ μ
λ‘λ
|
| 14 |
+
GET /api/swap/defaults μν¬νλ‘μ° κΈ°λ³Έκ°(κ³ κΈ μ€μ )
|
| 15 |
+
GET /api/history μ§λ κ²°κ³Ό λͺ©λ‘ (μꡬ μ μ₯λΆ ν¬ν¨)
|
| 16 |
+
POST /api/history/hide λͺ©λ‘μμ μ§μ°κΈ° (μ μ₯μ νμΌμ λ¨κΉ)
|
| 17 |
+
GET /api/history/status μꡬ μ μ₯ μν
|
| 18 |
+
GET /api/health μν¬νλ‘μ°Β·API ν€ μν
|
| 19 |
+
"""
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import hashlib
|
| 23 |
+
import io
|
| 24 |
+
import json
|
| 25 |
+
import os
|
| 26 |
+
import re
|
| 27 |
+
import tempfile
|
| 28 |
+
import threading
|
| 29 |
+
import time
|
| 30 |
+
import traceback
|
| 31 |
+
import unicodedata
|
| 32 |
+
import uuid
|
| 33 |
+
import zipfile
|
| 34 |
+
from typing import Any, Dict, List, Optional
|
| 35 |
+
from urllib.parse import quote
|
| 36 |
+
|
| 37 |
+
from fastapi import Body, FastAPI, File, Form, HTTPException, UploadFile
|
| 38 |
+
from fastapi.responses import FileResponse, Response, StreamingResponse
|
| 39 |
+
from PIL import Image
|
| 40 |
+
|
| 41 |
+
import comfy_client as cc
|
| 42 |
+
import history
|
| 43 |
+
|
| 44 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 45 |
+
FACE_DIR = os.path.join(BASE_DIR, "assets", "faces")
|
| 46 |
+
|
| 47 |
+
MAX_CONCURRENT = int(os.environ.get("COMFY_MAX_CONCURRENT", "4"))
|
| 48 |
+
JOB_TTL_SEC = int(os.environ.get("JOB_TTL_SEC", str(6 * 3600)))
|
| 49 |
+
GENDERS = ("male", "female")
|
| 50 |
+
|
| 51 |
+
app = FastAPI(title="Face swap batch")
|
| 52 |
+
|
| 53 |
+
history.init()
|
| 54 |
+
|
| 55 |
+
_SEM = threading.Semaphore(MAX_CONCURRENT)
|
| 56 |
+
_JOBS: Dict[str, Dict[str, Any]] = {}
|
| 57 |
+
_LOCK = threading.Lock()
|
| 58 |
+
_FACES: Dict[str, bytes] = {} # faceId β μλ³Έ λ°μ΄νΈ (κΈ°λ³Έ μΌκ΅΄ + μ¬μ©μκ° κ΅μ²΄ν μΌκ΅΄)
|
| 59 |
+
|
| 60 |
+
STAGE_LABEL = {
|
| 61 |
+
"queued_local": "λκΈ° μ€",
|
| 62 |
+
"uploading": "μ΄λ―Έμ§ μ
λ‘λ μ€",
|
| 63 |
+
"submitting": "μν¬νλ‘μ° μ μΆ μ€",
|
| 64 |
+
"queued_waiting": "Comfy λκΈ°μ΄",
|
| 65 |
+
"queued_limited": "Comfy λκΈ°μ΄ (λμ μ€ν μ ν)",
|
| 66 |
+
"pending": "Comfy λκΈ°μ΄",
|
| 67 |
+
"preparing": "GPU μ€λΉ μ€",
|
| 68 |
+
"executing": "μμ± μ€",
|
| 69 |
+
"running": "μμ± μ€",
|
| 70 |
+
"downloading": "κ²°κ³Ό λ°λ μ€",
|
| 71 |
+
"done": "μλ£",
|
| 72 |
+
"error": "μ€ν¨",
|
| 73 |
+
"cancelled": "μ·¨μλ¨",
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# ββ μΌκ΅΄ ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 78 |
+
def _load_default_faces() -> None:
|
| 79 |
+
for g in GENDERS:
|
| 80 |
+
path = os.path.join(FACE_DIR, f"{g}.jpg")
|
| 81 |
+
if os.path.exists(path):
|
| 82 |
+
with open(path, "rb") as f:
|
| 83 |
+
_FACES[f"default-{g}"] = f.read()
|
| 84 |
+
else:
|
| 85 |
+
print(f"[FACE] κΈ°λ³Έ μΌκ΅΄μ΄ μμ΅λλ€: {path}")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
_load_default_faces()
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _jpeg_thumb(data: bytes, max_side: int, quality: int = 85) -> bytes:
|
| 92 |
+
img = Image.open(io.BytesIO(data))
|
| 93 |
+
img.load()
|
| 94 |
+
from PIL import ImageOps
|
| 95 |
+
img = ImageOps.exif_transpose(img).convert("RGB")
|
| 96 |
+
img.thumbnail((max_side, max_side), Image.LANCZOS)
|
| 97 |
+
out = io.BytesIO()
|
| 98 |
+
img.save(out, "JPEG", quality=quality)
|
| 99 |
+
return out.getvalue()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@app.get("/api/swap/faces")
|
| 103 |
+
def faces_info():
|
| 104 |
+
return {g: {"id": f"default-{g}", "available": f"default-{g}" in _FACES} for g in GENDERS}
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@app.post("/api/swap/faces/{gender}")
|
| 108 |
+
async def upload_face(gender: str, file: UploadFile = File(...)):
|
| 109 |
+
if gender not in GENDERS:
|
| 110 |
+
raise HTTPException(400, "gender λ male λλ female μ΄μ΄μΌ ν©λλ€.")
|
| 111 |
+
data = await file.read()
|
| 112 |
+
try:
|
| 113 |
+
Image.open(io.BytesIO(data)).verify()
|
| 114 |
+
except Exception: # noqa: BLE001
|
| 115 |
+
raise HTTPException(400, "μ΄λ―Έμ§ νμΌμ΄ μλλλ€.")
|
| 116 |
+
fid = f"up-{hashlib.sha256(data).hexdigest()[:16]}"
|
| 117 |
+
_FACES[fid] = data
|
| 118 |
+
return {"id": fid}
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@app.get("/api/swap/face-img/{face_id}")
|
| 122 |
+
def face_img(face_id: str):
|
| 123 |
+
data = _FACES.get(face_id)
|
| 124 |
+
if not data:
|
| 125 |
+
raise HTTPException(404, "μΌκ΅΄ μ΄λ―Έμ§λ₯Ό μ°Ύμ μ μμ΅λλ€.")
|
| 126 |
+
return Response(_jpeg_thumb(data, 520), media_type="image/jpeg", headers={"Cache-Control": "no-cache"})
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
# ββ μμ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½βββββββββββββ
|
| 130 |
+
def _update(job_id: str, **kw: Any) -> None:
|
| 131 |
+
with _LOCK:
|
| 132 |
+
if job_id in _JOBS:
|
| 133 |
+
_JOBS[job_id].update(kw)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _gc() -> None:
|
| 137 |
+
"""λλ μμ
μ 'μ§ν μν' νλͺ©λ§ μ 리νλ€. κ²°κ³Ό νμΌμ history κ° κ³μ 보κ΄νλ€."""
|
| 138 |
+
now = time.time()
|
| 139 |
+
with _LOCK:
|
| 140 |
+
for j in [j for j, v in _JOBS.items() if v.get("finished_at") and now - v["finished_at"] > JOB_TTL_SEC]:
|
| 141 |
+
_JOBS.pop(j, None)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _clean_rel(rel: str, fallback: str) -> str:
|
| 145 |
+
"""μ
λ‘λλ μλκ²½λ‘ β μμ ν 'a/b/c.jpg' νν. νμΌλͺ
μ κ·Έλλ‘ μ μ§."""
|
| 146 |
+
rel = (rel or fallback or "image.png").replace("\\", "/")
|
| 147 |
+
parts = [p for p in rel.split("/") if p not in ("", ".", "..")]
|
| 148 |
+
return "/".join(parts) or "image.png"
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
_ORPHANS: set = set() # κ²°κ³Όλ λ²λ Έμ§λ§ Cloud μμ μμ§ λκ³ μμ μ μλ 'μ°λ¦¬' μμ
(μ€ν μ€μ΄λΌ μ€λ¨νμ§ λͺ»ν κ²)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def _remote_cancel(prompt_ids: set) -> None:
|
| 155 |
+
"""Comfy Cloud μͺ½ μ·¨μ (λ€νΈμν¬ νΈμΆμ΄λΌ λ€μμ μ²λ¦¬).
|
| 156 |
+
|
| 157 |
+
interrupt λ κ³μ μ μ€ν μ€ μμ
μ λΆλ₯Ό λ©μΆλ―λ‘, Cloud μμ λλ μμ
μ΄ μ λΆ 'μ°λ¦¬ κ²'μΌ λλ§ μ΄λ€.
|
| 158 |
+
μμ μ μ·¨μνμ§λ§ μ€λ¨νμ§ λͺ»ν΄ κ³μ λλ μ°λ¦¬ μμ
(_ORPHANS)λ μ°λ¦¬ κ²μΌλ‘ λ³Έλ€.
|
| 159 |
+
"""
|
| 160 |
+
own = set(prompt_ids) | set(_ORPHANS)
|
| 161 |
+
for pid in prompt_ids:
|
| 162 |
+
try:
|
| 163 |
+
res = cc.cancel_job(pid, allowed_running=own)
|
| 164 |
+
except Exception as e: # noqa: BLE001
|
| 165 |
+
print(f"[CANCEL] {pid} μ·¨μ μμ² μ€ν¨: {e}")
|
| 166 |
+
res = "soft"
|
| 167 |
+
if res == "soft":
|
| 168 |
+
_ORPHANS.add(pid)
|
| 169 |
+
else:
|
| 170 |
+
_ORPHANS.discard(pid)
|
| 171 |
+
if res == "interrupted":
|
| 172 |
+
_ORPHANS.clear() # interrupt λ μ€ν μ€μ΄λ μ°λ¦¬ μμ
μ λͺ¨λ λ©μ·λ€
|
| 173 |
+
with _LOCK:
|
| 174 |
+
for j in _JOBS.values():
|
| 175 |
+
if j.get("promptId") == pid:
|
| 176 |
+
j["remoteCancel"] = res
|
| 177 |
+
print(f"[CANCEL] prompt {pid} β {res}")
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _input_gone(msg: str) -> bool:
|
| 181 |
+
"""Comfy Cloud μ μ¬λ € λ μ
λ ₯ νμΌμ΄ μμ΄μ‘μ λμ μ€λ₯μΈμ§ (μ€μ Cloud λ μ μΆμ λ°μ μ£Όκ³ μ€ν λ¨κ³μμ ImageDownloadError λ‘ μ€ν¨μν¨λ€)."""
|
| 182 |
+
m = (msg or "").lower()
|
| 183 |
+
return any(k in m for k in ("imagedownloaderror", "doesn't exist", "does not exist", "value_not_in_list", "not in list", "input file"))
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _run_job(job_id: str, image_bytes: Optional[bytes], face_bytes: bytes, settings: Dict[str, Any],
|
| 187 |
+
main_name: Optional[str] = None, source_bytes: Optional[bytes] = None) -> None:
|
| 188 |
+
"""image_bytes: μλ‘ μ¬λ¦° μλ³Έ. μ¬μμ±(regen)μΌ λλ None μ΄κ³ , λμ μ΄μ μ Comfy Cloud μ μ¬λ € λ μ
λ ₯ νμΌ μ΄λ¦(main_name)μ μ΄λ€."""
|
| 189 |
+
started = time.time()
|
| 190 |
+
reused = main_name is not None
|
| 191 |
+
with _LOCK:
|
| 192 |
+
ev: threading.Event = _JOBS[job_id]["cancel"]
|
| 193 |
+
cancelled = ev.is_set
|
| 194 |
+
with _SEM:
|
| 195 |
+
try:
|
| 196 |
+
if cancelled():
|
| 197 |
+
raise cc.ComfyCancelled()
|
| 198 |
+
_update(job_id, stage="uploading")
|
| 199 |
+
if main_name is None:
|
| 200 |
+
main_name = cc.ensure_uploaded(image_bytes, "main")
|
| 201 |
+
face_name = cc.ensure_uploaded(face_bytes, "face")
|
| 202 |
+
if cancelled():
|
| 203 |
+
raise cc.ComfyCancelled()
|
| 204 |
+
|
| 205 |
+
_update(job_id, stage="submitting")
|
| 206 |
+
wf = cc.build_workflow(main_name, face_name, settings)
|
| 207 |
+
prompt_id = cc.submit(wf)
|
| 208 |
+
_update(job_id, promptId=prompt_id, stage="queued_waiting")
|
| 209 |
+
print(f"[JOB] {job_id} β prompt {prompt_id}")
|
| 210 |
+
if cancelled(): # μ μΆνλ μ¬μ΄μ μ·¨μκ° λ€μ΄μ¨ κ²½μ°
|
| 211 |
+
_remote_cancel({prompt_id})
|
| 212 |
+
raise cc.ComfyCancelled()
|
| 213 |
+
|
| 214 |
+
STATUS_TO_STAGE = {"waiting_to_dispatch": "queued_waiting", "pending": "queued_waiting",
|
| 215 |
+
"in_progress": "executing", "running": "executing"}
|
| 216 |
+
|
| 217 |
+
def on_status(st: str) -> None:
|
| 218 |
+
_update(job_id, stage=STATUS_TO_STAGE.get(st) or (st if st in STAGE_LABEL else "executing"))
|
| 219 |
+
|
| 220 |
+
result = cc.wait_for_result(prompt_id, on_status=on_status, should_cancel=cancelled)
|
| 221 |
+
_update(job_id, stage="downloading")
|
| 222 |
+
Image.open(io.BytesIO(result)).verify() # μ΄λ―Έμ§μΈμ§ νμΈ
|
| 223 |
+
elapsed = round(time.time() - started, 1)
|
| 224 |
+
with _LOCK:
|
| 225 |
+
j = dict(_JOBS.get(job_id) or {})
|
| 226 |
+
history.record(job_id, {
|
| 227 |
+
"rel_path": j.get("rel_path", ""), "filename": j.get("filename", ""), "gender": j.get("gender", ""),
|
| 228 |
+
"elapsedSec": elapsed, "comfy_image": main_name, # μ¬μμ±μ μ°λ €κ³ Comfy Cloud μ
λ ₯ νμΌ μ΄λ¦μ κΈ°μ΅
|
| 229 |
+
"settings": {k: settings.get(k) for k in ("denoise", "prompt", "mask_main", "mask_ref") if settings.get(k) is not None},
|
| 230 |
+
}, result, image_bytes or source_bytes)
|
| 231 |
+
_update(job_id, status="done", stage="done", elapsedSec=elapsed, finished_at=time.time())
|
| 232 |
+
print(f"[JOB] {job_id} done in {elapsed}s")
|
| 233 |
+
except cc.ComfyCancelled:
|
| 234 |
+
if ev.is_set(): # μ¬μ©μκ° μ·¨μν κ²½μ°: Comfy Cloud μͺ½ μ·¨μ κ²°κ³Όκ° λμ¨ λ€μ 'μ·¨μλ¨'μΌλ‘ μλ¦°λ€
|
| 235 |
+
for _ in range(60):
|
| 236 |
+
with _LOCK:
|
| 237 |
+
j = _JOBS.get(job_id) or {}
|
| 238 |
+
if j.get("remoteCancel") or not j.get("promptId"):
|
| 239 |
+
break
|
| 240 |
+
time.sleep(0.25)
|
| 241 |
+
print(f"[JOB] {job_id} cancelled")
|
| 242 |
+
_update(job_id, status="cancelled", stage="cancelled", finished_at=time.time())
|
| 243 |
+
except cc.ComfyError as e:
|
| 244 |
+
print(f"[JOB] {job_id} error: {e}")
|
| 245 |
+
gone = reused and _input_gone(str(e))
|
| 246 |
+
_update(job_id, status="error", stage="error", finished_at=time.time(), errorCode="input_gone" if gone else None,
|
| 247 |
+
error="μ΄μ μ μ¬λ € λ μλ³Έμ Comfy Cloud μμ μ°Ύμ§ λͺ»νμ΄μ(λ³΄κ΄ κΈ°κ°μ΄ μ§λ¬μ μ μμ΄μ)." if gone else str(e))
|
| 248 |
+
except Exception as e: # noqa: BLE001
|
| 249 |
+
traceback.print_exc()
|
| 250 |
+
_update(job_id, status="error", stage="error", error=f"μκΈ°μΉ λͺ»ν μ€λ₯: {str(e)[:200]}", finished_at=time.time())
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
@app.post("/api/swap/jobs")
|
| 254 |
+
async def create_job(
|
| 255 |
+
image: UploadFile = File(...),
|
| 256 |
+
rel_path: str = Form(""),
|
| 257 |
+
gender: str = Form(...),
|
| 258 |
+
face_id: str = Form(""),
|
| 259 |
+
settings: str = Form("{}"),
|
| 260 |
+
):
|
| 261 |
+
if gender not in GENDERS:
|
| 262 |
+
raise HTTPException(400, "gender λ male λλ female μ΄μ΄μΌ ν©λλ€.")
|
| 263 |
+
st = cc.status()
|
| 264 |
+
if not st["ok"]:
|
| 265 |
+
raise HTTPException(500, st["error"])
|
| 266 |
+
data = await image.read()
|
| 267 |
+
if not data:
|
| 268 |
+
raise HTTPException(400, "λΉ νμΌμ
λλ€.")
|
| 269 |
+
face = _FACES.get(face_id or f"default-{gender}")
|
| 270 |
+
if not face:
|
| 271 |
+
raise HTTPException(400, f"{'λ¨μ' if gender == 'male' else 'μ¬μ'} μΌκ΅΄ μ΄λ―Έμ§κ° μμ΅λλ€. μΌκ΅΄μ λ¨Όμ μ¬λ €μ£ΌμΈμ.")
|
| 272 |
+
try:
|
| 273 |
+
opts = json.loads(settings or "{}")
|
| 274 |
+
if not isinstance(opts, dict):
|
| 275 |
+
opts = {}
|
| 276 |
+
except json.JSONDecodeError:
|
| 277 |
+
opts = {}
|
| 278 |
+
|
| 279 |
+
_gc()
|
| 280 |
+
rel = _clean_rel(rel_path, image.filename or "")
|
| 281 |
+
job_id = uuid.uuid4().hex[:12]
|
| 282 |
+
with _LOCK:
|
| 283 |
+
_JOBS[job_id] = {
|
| 284 |
+
"status": "running", "stage": "queued_local", "created_at": time.time(),
|
| 285 |
+
"rel_path": rel, "filename": rel.split("/")[-1], "gender": gender,
|
| 286 |
+
"cancel": threading.Event(),
|
| 287 |
+
}
|
| 288 |
+
threading.Thread(target=_run_job, args=(job_id, data, face, opts), daemon=True).start()
|
| 289 |
+
return {"jobId": job_id}
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
@app.post("/api/swap/regen")
|
| 293 |
+
def regen_job(from_id: str = Form(...), face_id: str = Form(""), settings: str = Form("{}")):
|
| 294 |
+
"""μ§λ κ²°κ³Ό(from_id)μ κ°μ μλ³ΈμΌλ‘ μ κ²°κ³Όλ₯Ό νλ λ λ§λ λ€.
|
| 295 |
+
μλ³Έμ λ€μ μ¬λ¦¬μ§ μκ³ , κ·Έλ Comfy Cloud μ μ¬λ € λ μ
λ ₯ νμΌμ κ·Έλλ‘ μ΄λ€ β μλ³Έ νμ§ μ μ§, μλ‘κ³ μΉ¨ νμλ λμ."""
|
| 296 |
+
st = cc.status()
|
| 297 |
+
if not st["ok"]:
|
| 298 |
+
raise HTTPException(500, st["error"])
|
| 299 |
+
e = history.entry(from_id)
|
| 300 |
+
if not e:
|
| 301 |
+
raise HTTPException(404, "μ§λ κ²°κ³Όλ₯Ό μ°Ύμ μ μμ΅λλ€.")
|
| 302 |
+
comfy_image = e.get("comfy_image")
|
| 303 |
+
if not comfy_image:
|
| 304 |
+
raise HTTPException(409, "μ΄ κ²°κ³Όλ μλ³Έ μ λ³΄κ° μ μ₯λμ§ μμμ΄μ(μ΄μ λ²μ μΌλ‘ λ§λ κ²°κ³Ό).")
|
| 305 |
+
gender = e.get("gender")
|
| 306 |
+
if gender not in GENDERS:
|
| 307 |
+
raise HTTPException(400, "μ±λ³ μ λ³΄κ° μλ κ²°κ³Όμμ.")
|
| 308 |
+
face = _FACES.get(face_id or f"default-{gender}")
|
| 309 |
+
if not face:
|
| 310 |
+
raise HTTPException(400, f"{'λ¨μ' if gender == 'male' else 'μ¬μ'} μΌκ΅΄ μ΄λ―Έμ§κ° μμ΅λλ€.")
|
| 311 |
+
try:
|
| 312 |
+
opts = json.loads(settings or "{}")
|
| 313 |
+
if not isinstance(opts, dict):
|
| 314 |
+
opts = {}
|
| 315 |
+
except json.JSONDecodeError:
|
| 316 |
+
opts = {}
|
| 317 |
+
src_path = history.path(from_id, "source") # λͺ©λ‘ λΉκ΅μ© λ―Έλ¦¬λ³΄κΈ°λ§ μ΄μ΄λ°λλ€
|
| 318 |
+
src = None
|
| 319 |
+
if src_path:
|
| 320 |
+
with open(src_path, "rb") as f:
|
| 321 |
+
src = f.read()
|
| 322 |
+
_gc()
|
| 323 |
+
job_id = uuid.uuid4().hex[:12]
|
| 324 |
+
rel = e.get("rel_path", "")
|
| 325 |
+
with _LOCK:
|
| 326 |
+
_JOBS[job_id] = {
|
| 327 |
+
"status": "running", "stage": "queued_local", "created_at": time.time(),
|
| 328 |
+
"rel_path": rel, "filename": e.get("filename") or rel.split("/")[-1], "gender": gender,
|
| 329 |
+
"cancel": threading.Event(), "regenOf": from_id,
|
| 330 |
+
}
|
| 331 |
+
threading.Thread(target=_run_job, args=(job_id, None, face, opts, comfy_image, src), daemon=True).start()
|
| 332 |
+
return {"jobId": job_id}
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
@app.post("/api/swap/cancel")
|
| 336 |
+
def cancel_jobs(payload: Dict[str, Any] = Body(...)):
|
| 337 |
+
"""μ§νΒ·λκΈ° μ€μΈ μμ
μ μ·¨μνλ€. Comfy Cloud μͺ½ μ·¨μλ λ€μμ μ²λ¦¬νλ€."""
|
| 338 |
+
ids = [str(i) for i in payload.get("ids", [])]
|
| 339 |
+
prompt_ids = set()
|
| 340 |
+
n = 0
|
| 341 |
+
with _LOCK:
|
| 342 |
+
for i in ids:
|
| 343 |
+
j = _JOBS.get(i)
|
| 344 |
+
if j and j.get("status") == "running":
|
| 345 |
+
j["cancel"].set()
|
| 346 |
+
n += 1
|
| 347 |
+
if j.get("promptId"):
|
| 348 |
+
prompt_ids.add(j["promptId"])
|
| 349 |
+
if prompt_ids:
|
| 350 |
+
threading.Thread(target=_remote_cancel, args=(prompt_ids,), daemon=True).start()
|
| 351 |
+
return {"cancelled": n}
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
@app.get("/api/swap/jobs/{job_id}")
|
| 355 |
+
def job_info(job_id: str):
|
| 356 |
+
with _LOCK:
|
| 357 |
+
job = _JOBS.get(job_id)
|
| 358 |
+
snap = dict(job) if job else None
|
| 359 |
+
if snap is None:
|
| 360 |
+
e = history.entry(job_id) # μ¬μμ νμλ λλ μμ
μ κΈ°λ‘μ λ¨μ μλ€
|
| 361 |
+
if e:
|
| 362 |
+
return {"status": "done", "stage": "done", "stageLabel": STAGE_LABEL["done"], "error": None, "elapsedSec": e.get("elapsedSec", 0)}
|
| 363 |
+
raise HTTPException(404, "μμ
μ μ°Ύμ μ μμ΅λλ€ (μλ²κ° μ¬μμλμμ μ μμ΅λλ€).")
|
| 364 |
+
stage = snap.get("stage", "")
|
| 365 |
+
return {
|
| 366 |
+
"status": snap["status"],
|
| 367 |
+
"stage": stage,
|
| 368 |
+
"stageLabel": STAGE_LABEL.get(stage, stage),
|
| 369 |
+
"error": snap.get("error"),
|
| 370 |
+
"errorCode": snap.get("errorCode"),
|
| 371 |
+
"cancelMode": snap.get("remoteCancel"), # removed | interrupted | soft(Cloud μμλ μ΄λ―Έ μ€ν μ€μ΄λΌ λκΉμ§ μ§ν)
|
| 372 |
+
"elapsedSec": round((snap.get("finished_at") or time.time()) - snap["created_at"], 1),
|
| 373 |
+
}
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
# ββ κ²°κ³Ό νμΌ (μλ³Έ νμΌλͺ
Β·νμ₯μ μ μ§) βββββββββββββββββββββββββββββββββββββββ
|
| 377 |
+
def _done_job(job_id: str) -> Dict[str, Any]:
|
| 378 |
+
e = history.entry(job_id)
|
| 379 |
+
path = history.path(job_id, "result") if e else None
|
| 380 |
+
if not e or not path:
|
| 381 |
+
raise HTTPException(404, "μ μ₯λ κ²°κ³Όκ° μμ΅λλ€.")
|
| 382 |
+
return {**e, "path": path}
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def _encode_like_original(job: Dict[str, Any]) -> tuple[bytes, str, str]:
|
| 386 |
+
"""κ²°κ³Όλ₯Ό μλ³Έκ³Ό κ°μ νμΌλͺ
Β·νμ₯μλ‘ μΈμ½λ©. (bytes, filename, media_type)
|
| 387 |
+
|
| 388 |
+
jpg/jpeg β JPEG(q95) Β· png β PNG Β· webp β WEBP.
|
| 389 |
+
κ·Έ μΈ νμ₯μ(bmp λ±)λ νμΌλͺ
μ€κΈ°λ₯Ό μ μ§νκ³ .png λ‘ μ μ₯νλ€.
|
| 390 |
+
"""
|
| 391 |
+
name = job["filename"]
|
| 392 |
+
stem, ext = os.path.splitext(name)
|
| 393 |
+
low = ext.lower()
|
| 394 |
+
img = Image.open(job["path"])
|
| 395 |
+
img.load()
|
| 396 |
+
img = img.convert("RGB")
|
| 397 |
+
out = io.BytesIO()
|
| 398 |
+
if low in (".jpg", ".jpeg"):
|
| 399 |
+
img.save(out, "JPEG", quality=95, subsampling=0, optimize=True)
|
| 400 |
+
return out.getvalue(), name, "image/jpeg"
|
| 401 |
+
if low == ".webp":
|
| 402 |
+
img.save(out, "WEBP", quality=95)
|
| 403 |
+
return out.getvalue(), name, "image/webp"
|
| 404 |
+
img.save(out, "PNG", compress_level=6)
|
| 405 |
+
return out.getvalue(), (name if low == ".png" else f"{stem}.png"), "image/png"
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
def _content_disposition(kind: str, filename: str) -> str:
|
| 409 |
+
ascii_fallback = re.sub(r"[^A-Za-z0-9._-]", "_", unicodedata.normalize("NFKD", filename).encode("ascii", "ignore").decode()) or "result"
|
| 410 |
+
return f"{kind}; filename=\"{ascii_fallback}\"; filename*=UTF-8''{quote(filename)}"
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
@app.get("/api/swap/jobs/{job_id}/thumb")
|
| 414 |
+
def job_thumb(job_id: str):
|
| 415 |
+
p = history.path(job_id, "thumb")
|
| 416 |
+
if not p:
|
| 417 |
+
raise HTTPException(404, "μΈλ€μΌμ΄ μμ΅λλ€.")
|
| 418 |
+
return FileResponse(p, media_type="image/jpeg", headers={"Cache-Control": "max-age=3600"})
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
@app.get("/api/swap/jobs/{job_id}/source")
|
| 422 |
+
def job_source(job_id: str):
|
| 423 |
+
p = history.path(job_id, "source")
|
| 424 |
+
if not p:
|
| 425 |
+
raise HTTPException(404, "μλ³Έ λ―Έλ¦¬λ³΄κΈ°κ° μμ΅λλ€.")
|
| 426 |
+
return FileResponse(p, media_type="image/jpeg", headers={"Cache-Control": "max-age=3600"})
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
@app.get("/api/swap/jobs/{job_id}/view")
|
| 430 |
+
def job_view(job_id: str):
|
| 431 |
+
job = _done_job(job_id)
|
| 432 |
+
data, name, mt = _encode_like_original(job)
|
| 433 |
+
return Response(data, media_type=mt, headers={"Content-Disposition": _content_disposition("inline", name)})
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
@app.get("/api/swap/jobs/{job_id}/download")
|
| 437 |
+
def job_download(job_id: str):
|
| 438 |
+
job = _done_job(job_id)
|
| 439 |
+
data, name, mt = _encode_like_original(job)
|
| 440 |
+
return Response(data, media_type=mt, headers={"Content-Disposition": _content_disposition("attachment", name)})
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
@app.post("/api/swap/zip")
|
| 444 |
+
def zip_download(ids: str = Form(...), name: str = Form("faceswap_results")):
|
| 445 |
+
"""μ νν μλ£ μμ
μ ZIP μΌλ‘. ν΄λ ꡬ쑰μ νμΌλͺ
μ μ
λ‘λν κ·Έλλ‘ μ μ§νλ€."""
|
| 446 |
+
wanted = [i for i in re.split(r"[,\s]+", ids) if i]
|
| 447 |
+
if not wanted:
|
| 448 |
+
raise HTTPException(400, "λ€μ΄λ‘λν μμ
μ΄ μμ΅λλ€.")
|
| 449 |
+
tmp = tempfile.TemporaryFile()
|
| 450 |
+
used: set[str] = set()
|
| 451 |
+
count = 0
|
| 452 |
+
with zipfile.ZipFile(tmp, "w", zipfile.ZIP_STORED) as zf:
|
| 453 |
+
for jid in wanted:
|
| 454 |
+
try:
|
| 455 |
+
job = _done_job(jid)
|
| 456 |
+
except HTTPException:
|
| 457 |
+
continue
|
| 458 |
+
data, fname, _ = _encode_like_original(job)
|
| 459 |
+
folder = "/".join(job["rel_path"].split("/")[:-1])
|
| 460 |
+
arc = f"{folder}/{fname}" if folder else fname
|
| 461 |
+
base, ext = os.path.splitext(arc)
|
| 462 |
+
n = 2
|
| 463 |
+
while arc in used:
|
| 464 |
+
arc = f"{base} ({n}){ext}"
|
| 465 |
+
n += 1
|
| 466 |
+
used.add(arc)
|
| 467 |
+
zf.writestr(arc, data)
|
| 468 |
+
count += 1
|
| 469 |
+
if count == 0:
|
| 470 |
+
tmp.close()
|
| 471 |
+
raise HTTPException(404, "μλ£λ κ²°κ³Όκ° μμ΅λλ€.")
|
| 472 |
+
tmp.seek(0)
|
| 473 |
+
|
| 474 |
+
def _iter():
|
| 475 |
+
try:
|
| 476 |
+
while chunk := tmp.read(1024 * 1024):
|
| 477 |
+
yield chunk
|
| 478 |
+
finally:
|
| 479 |
+
tmp.close()
|
| 480 |
+
|
| 481 |
+
safe = re.sub(r'[\\/:*?"<>|]', "_", name).strip() or "faceswap_results"
|
| 482 |
+
zip_name = f"{safe}.zip"
|
| 483 |
+
return StreamingResponse(_iter(), media_type="application/zip",
|
| 484 |
+
headers={"Content-Disposition": _content_disposition("attachment", zip_name)})
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
# ββ μ§λ κ²°κ³Ό βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 488 |
+
@app.get("/api/history")
|
| 489 |
+
def history_list(q: str = "", limit: int = 1000):
|
| 490 |
+
items = history.list_entries(q, min(max(limit, 1), 3000))
|
| 491 |
+
return {"items": [{**{k: e.get(k) for k in ("id", "rel_path", "filename", "folder", "gender", "date", "time", "elapsedSec")}, "canRegen": bool(e.get("comfy_image"))} for e in items],
|
| 492 |
+
"total": len(items)}
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
@app.post("/api/history/hide")
|
| 496 |
+
def history_hide(payload: Dict[str, Any] = Body(...)):
|
| 497 |
+
ids = [str(i) for i in payload.get("ids", [])]
|
| 498 |
+
return {"hidden": history.hide(ids)}
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
@app.get("/api/history/status")
|
| 502 |
+
def history_status():
|
| 503 |
+
return history.status()
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
@app.on_event("shutdown")
|
| 507 |
+
def _on_shutdown() -> None:
|
| 508 |
+
history.flush(20)
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
# ββ μ€μ / μν βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 512 |
+
@app.get("/api/swap/defaults")
|
| 513 |
+
def defaults():
|
| 514 |
+
try:
|
| 515 |
+
return cc.workflow_defaults()
|
| 516 |
+
except cc.ComfyError as e:
|
| 517 |
+
raise HTTPException(500, str(e))
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
@app.get("/api/health")
|
| 521 |
+
def health():
|
| 522 |
+
return {**cc.status(), "maxConcurrent": MAX_CONCURRENT}
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
def _find_index() -> Optional[str]:
|
| 526 |
+
"""νλ©΄ νμΌ μμΉ: 루νΈμ index.html μ μ°μ , μμΌλ©΄ static/index.html. (λ μ€ μ΄λμ μ¬λ €λ λμ)"""
|
| 527 |
+
for cand in (os.path.join(BASE_DIR, "index.html"), os.path.join(BASE_DIR, "static", "index.html")):
|
| 528 |
+
if os.path.exists(cand):
|
| 529 |
+
return cand
|
| 530 |
+
return None
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
@app.get("/", include_in_schema=False)
|
| 534 |
+
@app.get("/index.html", include_in_schema=False)
|
| 535 |
+
def index_page():
|
| 536 |
+
path = _find_index()
|
| 537 |
+
if not path:
|
| 538 |
+
raise HTTPException(500, "index.html νμΌμ΄ μμ΅λλ€. server.py μ κ°μ ν΄λ(λλ static/)μ μ¬λ €μ£ΌμΈμ.")
|
| 539 |
+
return FileResponse(path, media_type="text/html", headers={"Cache-Control": "no-cache"})
|