Spaces:
Sleeping

sunyoung00 commited on
Commit
cbb64dc
Β·
verified Β·
1 Parent(s): e364614

Upload 2 files

Browse files
Files changed (2) hide show
  1. index (46).html +0 -0
  2. 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 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"})