sunyoung00 commited on
Commit
e4304e3
Β·
verified Β·
1 Parent(s): d08d93f

Upload 2 files

Browse files
Files changed (2) hide show
  1. index (36).html +0 -0
  2. server (33).py +775 -0
index (36).html ADDED
The diff for this file is too large to render. See raw diff
 
server (33).py ADDED
@@ -0,0 +1,775 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/whoami λ‘œκ·ΈμΈν•œ μ‚¬μš©μž (HF OAuth, 선택)
13
+ GET /api/dashboard 생성 기둝 λŒ€μ‹œλ³΄λ“œ 집계 (κΈ°κ°„: ?from=YYYY-MM-DD&to=YYYY-MM-DD)
14
+ GET /api/swap/faces μ‚½μž…ν•  μ–Όκ΅΄(λ‚¨μž/μ—¬μž) κΈ°λ³Έ 정보
15
+ POST /api/swap/faces/{gender} μ–Όκ΅΄ ꡐ체 μ—…λ‘œλ“œ
16
+ GET /api/swap/defaults μ›Œν¬ν”Œλ‘œμš° κΈ°λ³Έκ°’(κ³ κΈ‰ μ„€μ •)
17
+ GET /api/history μ§€λ‚œ κ²°κ³Ό λͺ©λ‘ (영ꡬ μ €μž₯λΆ„ 포함)
18
+ POST /api/history/hide λͺ©λ‘μ—μ„œ μ§€μš°κΈ° (μ €μž₯μ†Œ νŒŒμΌμ€ 남김)
19
+ GET /api/history/status 영ꡬ μ €μž₯ μƒνƒœ
20
+ GET /api/health μ›Œν¬ν”Œλ‘œμš°Β·API ν‚€ μƒνƒœ
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import hashlib
25
+ import io
26
+ import json
27
+ import mimetypes
28
+ import os
29
+ import re
30
+ import tempfile
31
+ import threading
32
+ import time
33
+ import traceback
34
+ import unicodedata
35
+ import uuid
36
+ import zipfile
37
+ from typing import Any, Dict, List, Optional
38
+ from urllib.parse import quote
39
+
40
+ from fastapi import Body, Depends, FastAPI, File, Form, HTTPException, Query, Request, UploadFile
41
+ from fastapi.responses import FileResponse, HTMLResponse, Response, StreamingResponse
42
+ from PIL import Image
43
+
44
+ import comfy_client as cc
45
+ import history
46
+
47
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
48
+ FACE_DIR = os.path.join(BASE_DIR, "assets", "faces")
49
+
50
+ MAX_CONCURRENT = int(os.environ.get("COMFY_MAX_CONCURRENT", "4"))
51
+ JOB_TTL_SEC = int(os.environ.get("JOB_TTL_SEC", str(6 * 3600)))
52
+ GENDERS = ("male", "female")
53
+
54
+ _OPEN_API = ("/api/health", "/api/whoami") # 둜그인 전에도 μ—΄λ € μžˆμ–΄μ•Ό ν•˜λŠ” 것(μƒνƒœ 확인, 둜그인 μ—¬λΆ€ 확인)
55
+
56
+
57
+ def _guard(request: Request) -> None:
58
+ """둜그인이 ν•„μš”ν•œ ν™˜κ²½μ—μ„œλŠ” /api/* 전체λ₯Ό λ‘œκ·ΈμΈν•œ μ‚¬λžŒλ§Œ μ“°κ²Œ ν•œλ‹€(ν™”λ©΄ '/' 은 index_page κ°€ 둜그인 μ•ˆλ‚΄λ₯Ό 보여 μ€€λ‹€)."""
59
+ if not _login_required():
60
+ return
61
+ path = request.url.path
62
+ if not path.startswith("/api/") or path in _OPEN_API:
63
+ return
64
+ if not get_current_user(request)["is_logged_in"]:
65
+ raise HTTPException(401, "둜그인이 ν•„μš”ν•΄μš”. 화면을 μƒˆλ‘œκ³ μΉ¨ν•œ λ’€ Hugging Face 둜 λ‘œκ·ΈμΈν•΄ μ£Όμ„Έμš”.")
66
+
67
+
68
+ app = FastAPI(title="Face swap batch", dependencies=[Depends(_guard)], docs_url=None, redoc_url=None, openapi_url=None) # 둜그인 μ „μ—λŠ” 경둜 λͺ©λ‘(λ¬Έμ„œ)도 λ…ΈμΆœν•˜μ§€ μ•ŠλŠ”λ‹€
69
+
70
+ history.init()
71
+
72
+ # ── 둜그인(HF OAuth) β€” μ‚¬μš© 톡계에 'λˆ„κ°€ μΌλŠ”μ§€'λ₯Ό 남기기 μœ„ν•¨ ────────────────────
73
+ # Space 의 README.md 에 `hf_oauth: true` κ°€ 있으면 HF κ°€ OAUTH_CLIENT_ID 등을 λ„£μ–΄ μ€€λ‹€. κ·Έλ•Œλ§Œ 둜그인 κΈ°λŠ₯을 뢙인닀.
74
+ try:
75
+ from huggingface_hub import attach_huggingface_oauth, parse_huggingface_oauth
76
+ except Exception: # noqa: BLE001
77
+ attach_huggingface_oauth = parse_huggingface_oauth = None
78
+ _OAUTH_ATTACHED = False
79
+ if attach_huggingface_oauth is not None and os.environ.get("OAUTH_CLIENT_ID"):
80
+ try:
81
+ attach_huggingface_oauth(app)
82
+ _OAUTH_ATTACHED = True
83
+ print("[OAUTH] HF OAuth 연결됨")
84
+ except Exception as _e: # noqa: BLE001
85
+ print(f"[OAUTH] μ—°κ²° μ‹€νŒ¨: {_e}")
86
+ # ν…ŒμŠ€νŠΈΒ·λ‘œμ»¬ 개발용(Space μ—μ„œλŠ” μ“°μ§€ μ•ŠλŠ”λ‹€): DEV_USER="아이디|이름" β†’ κ·Έ μ‚¬λžŒμœΌλ‘œ λ‘œκ·ΈμΈν•œ κ²ƒμ²˜λŸΌ λ™μž‘, DEV_OAUTH=1 β†’ 둜그인 ν•„μˆ˜ ν™”λ©΄ ν™•μΈμš©
87
+ _DEV_USER = os.environ.get("DEV_USER", "")
88
+ if os.environ.get("DEV_OAUTH") == "1":
89
+ _OAUTH_ATTACHED = True
90
+ # README 에 hf_oauth: true κ°€ μžˆμ–΄ 둜그인이 λΆ™μœΌλ©΄, λ‘œκ·ΈμΈν•œ μ‚¬λžŒλ§Œ μ“Έ 수 μžˆλ‹€(SPAO V2 와 같은 방식). README 에 μ—†μœΌλ©΄ μ˜ˆμ „μ²˜λŸΌ 둜그인 없이 λ™μž‘ν•œλ‹€.
91
+ # 둜그인이 λΆ™μ–΄ μžˆμ–΄λ„ 둜그인 없이 μ“°κ²Œ ν•˜λ €λ©΄ REQUIRE_LOGIN=false.
92
+ REQUIRE_LOGIN = os.environ.get("REQUIRE_LOGIN", "true").lower() in ("1", "true", "yes", "on")
93
+
94
+
95
+ def get_current_user(request: Request) -> Dict[str, Any]:
96
+ anon = {"username": "anonymous", "name": "", "email": "", "is_logged_in": False}
97
+ if _DEV_USER:
98
+ uid, _, nm = _DEV_USER.partition("|")
99
+ return {"username": uid, "name": nm or uid, "email": "", "is_logged_in": True}
100
+ if not _OAUTH_ATTACHED or parse_huggingface_oauth is None:
101
+ return anon
102
+ try:
103
+ info = parse_huggingface_oauth(request)
104
+ ui = getattr(info, "user_info", None) if info else None
105
+ if not ui:
106
+ return anon
107
+ return {"username": getattr(ui, "preferred_username", "") or "anonymous", "name": getattr(ui, "name", "") or "",
108
+ "email": getattr(ui, "email", "") or "", "is_logged_in": True}
109
+ except Exception as e: # noqa: BLE001
110
+ print(f"[OAUTH] μ‚¬μš©μž 확인 μ‹€νŒ¨: {e}")
111
+ return anon
112
+
113
+
114
+ def _login_required() -> bool:
115
+ return REQUIRE_LOGIN and _OAUTH_ATTACHED
116
+
117
+
118
+ def _require_login(user: Dict[str, Any]) -> None:
119
+ if _login_required() and not user["is_logged_in"]:
120
+ raise HTTPException(401, "둜그인이 ν•„μš”ν•΄μš”. ν™”λ©΄ μœ„μͺ½μ˜ '둜그인'을 눌러 Hugging Face 둜 λ‘œκ·ΈμΈν•œ λ’€ λ‹€μ‹œ μ‹œλ„ν•΄ μ£Όμ„Έμš”.")
121
+
122
+
123
+ _LOGIN_GATE_HTML = """<!DOCTYPE html><html lang="ko"><head><meta charset="utf-8"/>
124
+ <meta name="viewport" content="width=device-width, initial-scale=1"/><title>AI μ–Όκ΅΄ ꡐ체 Β· 둜그인</title>
125
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/static/pretendard.min.css"/>
126
+ <style>*{font-family:'Pretendard',-apple-system,sans-serif;box-sizing:border-box}body{margin:0;background:#1a1a1a;color:#f9fafb;min-height:100vh;display:flex;align-items:center;justify-content:center}
127
+ .card{width:min(420px,92vw);background:#1e1e1e;border:1px solid #2a2a2a;border-radius:20px;padding:36px 32px;text-align:center}
128
+ .logo{width:44px;height:44px;border-radius:12px;background:#3B82F6;display:inline-flex;align-items:center;justify-content:center;margin-bottom:18px}
129
+ h1{font-size:18px;margin:0 0 6px}p{font-size:13px;color:#9ca3af;line-height:1.6;margin:0 0 24px}
130
+ a.btn{display:block;background:#3B82F6;color:#fff;text-decoration:none;font-weight:600;font-size:14px;padding:13px;border-radius:12px}a.btn:hover{background:#2563EB}
131
+ .note{font-size:11.5px;color:#6b7280;margin-top:16px}</style></head><body><div class="card">
132
+ <div class="logo"><svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/><path d="M20 3v4"/><path d="M22 5h-4"/><path d="M4 17v2"/><path d="M5 18H3"/></svg></div>
133
+ <h1>AI μ–Όκ΅΄ ꡐ체</h1><p>μ΄λžœλ“œμ΄λ…Έν”Œ 쑰직 λ©€λ²„λ§Œ μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€.<br/>Hugging Face κ³„μ •μœΌλ‘œ λ‘œκ·ΈμΈν•΄ μ£Όμ„Έμš”.</p>
134
+ <a class="btn" id="login" href="/oauth/huggingface/login">πŸ€— Hugging Face둜 둜그인</a>
135
+ <div class="note" id="note">둜그인 ν›„ μžλ™μœΌλ‘œ λŒμ•„μ˜΅λ‹ˆλ‹€. 쑰직 멀버가 μ•„λ‹ˆλ©΄ 접근이 κ±°λΆ€λ©λ‹ˆλ‹€.</div></div>
136
+ <script>if(window.top!==window.self){var a=document.getElementById("login");a.target="_blank";a.rel="noopener";document.getElementById("note").textContent="μƒˆ νƒ­μ—μ„œ λ‘œκ·ΈμΈν•œ λ’€, 이 화면을 μƒˆλ‘œκ³ μΉ¨ν•΄ μ£Όμ„Έμš”. 쑰직 멀버가 μ•„λ‹ˆλ©΄ 접근이 κ±°λΆ€λ©λ‹ˆλ‹€.";}</script>
137
+ </body></html>"""
138
+
139
+ _SEM = threading.Semaphore(MAX_CONCURRENT)
140
+ _JOBS: Dict[str, Dict[str, Any]] = {}
141
+ _LOCK = threading.Lock()
142
+ _FACES: Dict[str, bytes] = {} # faceId β†’ 원본 λ°”μ΄νŠΈ (κΈ°λ³Έ μ–Όκ΅΄ + μ‚¬μš©μžκ°€ κ΅μ²΄ν•œ μ–Όκ΅΄)
143
+
144
+ STAGE_LABEL = {
145
+ "queued_local": "λŒ€κΈ° 쀑",
146
+ "uploading": "이미지 μ—…λ‘œλ“œ 쀑",
147
+ "submitting": "μ›Œν¬ν”Œλ‘œμš° 제좜 쀑",
148
+ "queued_waiting": "Comfy λŒ€κΈ°μ—΄",
149
+ "queued_limited": "Comfy λŒ€κΈ°μ—΄ (λ™μ‹œ μ‹€ν–‰ μ œν•œ)",
150
+ "pending": "Comfy λŒ€κΈ°μ—΄",
151
+ "preparing": "GPU μ€€λΉ„ 쀑",
152
+ "executing": "생성 쀑",
153
+ "running": "생성 쀑",
154
+ "downloading": "κ²°κ³Ό λ°›λŠ” 쀑",
155
+ "done": "μ™„λ£Œ",
156
+ "error": "μ‹€νŒ¨",
157
+ "cancelled": "μ·¨μ†Œλ¨",
158
+ }
159
+
160
+
161
+ # ── μ–Όκ΅΄ ──────────────────────────────────────────────────────────────────────
162
+ def _load_default_faces() -> None:
163
+ for g in GENDERS:
164
+ path = os.path.join(FACE_DIR, f"{g}.jpg")
165
+ if os.path.exists(path):
166
+ with open(path, "rb") as f:
167
+ _FACES[f"default-{g}"] = f.read()
168
+ else:
169
+ print(f"[FACE] κΈ°λ³Έ 얼꡴이 μ—†μŠ΅λ‹ˆλ‹€: {path}")
170
+
171
+
172
+ _load_default_faces()
173
+
174
+
175
+ def _jpeg_thumb(data: bytes, max_side: int, quality: int = 85) -> bytes:
176
+ img = Image.open(io.BytesIO(data))
177
+ img.load()
178
+ from PIL import ImageOps
179
+ img = ImageOps.exif_transpose(img).convert("RGB")
180
+ img.thumbnail((max_side, max_side), Image.LANCZOS)
181
+ out = io.BytesIO()
182
+ img.save(out, "JPEG", quality=quality)
183
+ return out.getvalue()
184
+
185
+
186
+ @app.get("/api/swap/faces")
187
+ def faces_info():
188
+ return {g: {"id": f"default-{g}", "available": f"default-{g}" in _FACES} for g in GENDERS}
189
+
190
+
191
+ FACE_MAX_BYTES = 25 * 1024 * 1024 # 직접 μ˜¬λ¦¬λŠ” μ–Όκ΅΄(페λ₯΄μ†Œλ‚˜ λͺ¨λΈ) ν•œ μž₯의 μ΅œλŒ€ 크기
192
+ FACE_MIN_SIDE = 200 # 이보닀 μž‘μœΌλ©΄ 머리λ₯Ό 잘 μ°Ύμ§€ λͺ»ν•œλ‹€
193
+ FACE_MAX_CUSTOM = 40 # μ„œλ²„ λ©”λͺ¨λ¦¬μ— λ‘˜ 직접 올린 μ–Όκ΅΄ 수(였래된 것뢀터 정리)
194
+
195
+
196
+ @app.post("/api/swap/faces/{gender}")
197
+ async def upload_face(gender: str, file: UploadFile = File(...)):
198
+ """직접 올린 페λ₯΄μ†Œλ‚˜ λͺ¨λΈ(μ–Όκ΅΄). 같은 사진은 같은 id κ°€ λ‚˜μ˜¨λ‹€(λ‚΄μš© ν•΄μ‹œ) β†’ 화면을 μƒˆλ‘œ 열어도 λ‹€μ‹œ 올렀 같은 id 둜 이어 μ“΄λ‹€."""
199
+ if gender not in GENDERS:
200
+ raise HTTPException(400, "gender λŠ” male λ˜λŠ” female 이어야 ν•©λ‹ˆλ‹€.")
201
+ data = await file.read()
202
+ if not data:
203
+ raise HTTPException(400, "빈 νŒŒμΌμž…λ‹ˆλ‹€.")
204
+ if len(data) > FACE_MAX_BYTES:
205
+ raise HTTPException(413, f"사진이 λ„ˆλ¬΄ μ»€μš”(μ΅œλŒ€ {FACE_MAX_BYTES // 1024 // 1024}MB).")
206
+ try:
207
+ im = Image.open(io.BytesIO(data))
208
+ im.verify()
209
+ w, h = Image.open(io.BytesIO(data)).size
210
+ except Exception: # noqa: BLE001
211
+ raise HTTPException(400, "이미지 파일이 μ•„λ‹™λ‹ˆλ‹€. JPGΒ·PNGΒ·WEBP 사진을 올렀 μ£Όμ„Έμš”.")
212
+ if min(w, h) < FACE_MIN_SIDE:
213
+ raise HTTPException(400, f"사진이 λ„ˆλ¬΄ μž‘μ•„μš”({w}Γ—{h}). 짧은 변이 {FACE_MIN_SIDE}px 이상인 μ–Όκ΅΄ 사진을 올렀 μ£Όμ„Έμš”.")
214
+ fid = f"up-{hashlib.sha256(data).hexdigest()[:16]}"
215
+ with _LOCK:
216
+ _FACES.pop(fid, None) # λ‹€μ‹œ 올리면 'κ°€μž₯ 졜근'으둜
217
+ _FACES[fid] = data
218
+ custom = [k for k in _FACES if k.startswith("up-")]
219
+ for old in custom[:-FACE_MAX_CUSTOM]:
220
+ _FACES.pop(old, None)
221
+ return {"id": fid, "width": w, "height": h}
222
+
223
+
224
+ def _prep_settings(opts: Dict[str, Any], gender: str, face_id: str) -> Dict[str, Any]:
225
+ """ν™”λ©΄μ—μ„œ 온 섀정에 μ„œλ²„κ°€ μ•„λŠ” 값을 보탠닀: 성별(ν”„λ‘¬ν”„νŠΈ κ΅¬μ„±μš©), 머리 μŠ€νƒ€μΌ μ„€λͺ…(μ—†μœΌλ©΄ κΈ°λ³Έ 얼꡴일 λ•Œλ§Œ κΈ°λ³Έ μ„€λͺ…)."""
226
+ opts = dict(opts)
227
+ opts["gender"] = gender
228
+ if "hair_desc" not in opts:
229
+ opts["hair_desc"] = cc.DEFAULT_HAIR.get(gender, "") if (face_id or f"default-{gender}").startswith("default-") else ""
230
+ elif not isinstance(opts["hair_desc"], str):
231
+ opts["hair_desc"] = ""
232
+ else:
233
+ opts["hair_desc"] = " ".join(opts["hair_desc"].split())[:400] # ν•œ 쀄·400μžκΉŒμ§€
234
+ return opts
235
+
236
+
237
+ @app.get("/api/swap/face-img/{face_id}")
238
+ def face_img(face_id: str):
239
+ data = _FACES.get(face_id)
240
+ if not data:
241
+ raise HTTPException(404, "μ–Όκ΅΄ 이미지λ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")
242
+ return Response(_jpeg_thumb(data, 520), media_type="image/jpeg", headers={"Cache-Control": "no-cache"})
243
+
244
+
245
+ # ── μž‘μ—… ──────────────────────────────────────────────────────────────────────
246
+ def _update(job_id: str, **kw: Any) -> None:
247
+ with _LOCK:
248
+ if job_id in _JOBS:
249
+ _JOBS[job_id].update(kw)
250
+
251
+
252
+ def _gc() -> None:
253
+ """λλ‚œ μž‘μ—…μ˜ 'μ§„ν–‰ μƒνƒœ' ν•­λͺ©λ§Œ μ •λ¦¬ν•œλ‹€. κ²°κ³Ό νŒŒμΌμ€ history κ°€ 계속 λ³΄κ΄€ν•œλ‹€."""
254
+ now = time.time()
255
+ with _LOCK:
256
+ for j in [j for j, v in _JOBS.items() if v.get("finished_at") and now - v["finished_at"] > JOB_TTL_SEC]:
257
+ _JOBS.pop(j, None)
258
+
259
+
260
+ def _clean_rel(rel: str, fallback: str) -> str:
261
+ """μ—…λ‘œλ“œλœ μƒλŒ€κ²½λ‘œ β†’ μ•ˆμ „ν•œ 'a/b/c.jpg' ν˜•νƒœ. 파일λͺ…은 κ·ΈλŒ€λ‘œ μœ μ§€."""
262
+ rel = (rel or fallback or "image.png").replace("\\", "/")
263
+ parts = [p for p in rel.split("/") if p not in ("", ".", "..")]
264
+ return "/".join(parts) or "image.png"
265
+
266
+
267
+ _ORPHANS: set = set() # κ²°κ³ΌλŠ” λ²„λ Έμ§€λ§Œ Cloud μ—μ„œ 아직 돌고 μžˆμ„ 수 μžˆλŠ” '우리' μž‘μ—… (μ‹€ν–‰ 쀑이라 μ€‘λ‹¨ν•˜μ§€ λͺ»ν•œ 것)
268
+
269
+
270
+ def _remote_cancel(prompt_ids: set) -> None:
271
+ """Comfy Cloud μͺ½ μ·¨μ†Œ (λ„€νŠΈμ›Œν¬ 호좜이라 λ’€μ—μ„œ 처리).
272
+
273
+ interrupt λŠ” κ³„μ •μ˜ μ‹€ν–‰ 쀑 μž‘μ—… μ „λΆ€λ₯Ό λ©ˆμΆ”λ―€λ‘œ, Cloud μ—μ„œ λ„λŠ” μž‘μ—…μ΄ μ „λΆ€ '우리 것'일 λ•Œλ§Œ μ“΄λ‹€.
274
+ μ˜ˆμ „μ— μ·¨μ†Œν–ˆμ§€λ§Œ μ€‘λ‹¨ν•˜μ§€ λͺ»ν•΄ 계속 λ„λŠ” 우리 μž‘μ—…(_ORPHANS)도 우리 κ²ƒμœΌλ‘œ λ³Έλ‹€.
275
+ """
276
+ own = set(prompt_ids) | set(_ORPHANS)
277
+ for pid in prompt_ids:
278
+ try:
279
+ res = cc.cancel_job(pid, allowed_running=own)
280
+ except Exception as e: # noqa: BLE001
281
+ print(f"[CANCEL] {pid} μ·¨μ†Œ μš”μ²­ μ‹€νŒ¨: {e}")
282
+ res = "soft"
283
+ if res == "soft":
284
+ _ORPHANS.add(pid)
285
+ else:
286
+ _ORPHANS.discard(pid)
287
+ if res == "interrupted":
288
+ _ORPHANS.clear() # interrupt λŠ” μ‹€ν–‰ μ€‘μ΄λ˜ 우리 μž‘μ—…μ„ λͺ¨λ‘ λ©ˆμ·„λ‹€
289
+ with _LOCK:
290
+ for j in _JOBS.values():
291
+ if j.get("promptId") == pid:
292
+ j["remoteCancel"] = res
293
+ print(f"[CANCEL] prompt {pid} β†’ {res}")
294
+
295
+
296
+ def _input_gone(msg: str) -> bool:
297
+ """Comfy Cloud 에 올렀 λ‘” μž…λ ₯ 파일이 μ—†μ–΄μ‘Œμ„ λ•Œμ˜ 였λ₯˜μΈμ§€ (μ‹€μ œ Cloud λŠ” μ œμΆœμ€ λ°›μ•„ μ£Όκ³  μ‹€ν–‰ λ‹¨κ³„μ—μ„œ ImageDownloadError 둜 μ‹€νŒ¨μ‹œν‚¨λ‹€)."""
298
+ m = (msg or "").lower()
299
+ return any(k in m for k in ("imagedownloaderror", "doesn't exist", "does not exist", "value_not_in_list", "not in list", "input file"))
300
+
301
+
302
+ def _run_job(job_id: str, image_bytes: Optional[bytes], face_bytes: bytes, settings: Dict[str, Any],
303
+ main_name: Optional[str] = None, source_bytes: Optional[bytes] = None, remember_input: bool = True) -> None:
304
+ """image_bytes: μƒˆλ‘œ 올린 원본. μž¬μƒμ„±(regen)일 λ•ŒλŠ” None 이고, λŒ€μ‹  이전에 Comfy Cloud 에 올렀 λ‘” μž…λ ₯ 파일 이름(main_name)을 μ“΄λ‹€."""
305
+ started = time.time()
306
+ reused = main_name is not None
307
+ with _LOCK:
308
+ ev: threading.Event = _JOBS[job_id]["cancel"]
309
+ cancelled = ev.is_set
310
+ with _SEM:
311
+ try:
312
+ if cancelled():
313
+ raise cc.ComfyCancelled()
314
+ _update(job_id, stage="uploading")
315
+ if main_name is None:
316
+ main_name = cc.ensure_uploaded(image_bytes, "main")
317
+ face_name = cc.ensure_uploaded(face_bytes, "face")
318
+ if cancelled():
319
+ raise cc.ComfyCancelled()
320
+
321
+ _update(job_id, stage="submitting")
322
+ wf = cc.build_workflow(main_name, face_name, settings)
323
+ prompt_id = cc.submit(wf)
324
+ _update(job_id, promptId=prompt_id, stage="queued_waiting")
325
+ print(f"[JOB] {job_id} β†’ prompt {prompt_id}")
326
+ if cancelled(): # μ œμΆœν•˜λŠ” 사이에 μ·¨μ†Œκ°€ λ“€μ–΄μ˜¨ 경우
327
+ _remote_cancel({prompt_id})
328
+ raise cc.ComfyCancelled()
329
+
330
+ STATUS_TO_STAGE = {"waiting_to_dispatch": "queued_waiting", "pending": "queued_waiting",
331
+ "in_progress": "executing", "running": "executing"}
332
+
333
+ def on_status(st: str) -> None:
334
+ _update(job_id, stage=STATUS_TO_STAGE.get(st) or (st if st in STAGE_LABEL else "executing"))
335
+
336
+ result = cc.wait_for_result(prompt_id, on_status=on_status, should_cancel=cancelled)
337
+ _update(job_id, stage="downloading")
338
+ Image.open(io.BytesIO(result)).verify() # 이미지인지 확인
339
+ elapsed = round(time.time() - started, 1)
340
+ with _LOCK:
341
+ j = dict(_JOBS.get(job_id) or {})
342
+ history.record(job_id, {
343
+ "rel_path": j.get("rel_path", ""), "filename": j.get("filename", ""), "gender": j.get("gender", ""),
344
+ "elapsedSec": elapsed, "comfy_image": main_name if remember_input else None, # μž¬μƒμ„±μ— μ“°λ €κ³  μž…λ ₯ 파일 이름을 κΈ°μ–΅(μ €ν™”μ§ˆ 미리보기둜 λ§Œλ“  건 κΈ°μ–΅ν•˜μ§€ μ•ŠλŠ”λ‹€)
345
+ "user_username": (j.get("user") or {}).get("username", ""), "user_name": (j.get("user") or {}).get("name", ""), # λŒ€μ‹œλ³΄λ“œμš©
346
+ "regen": bool(j.get("regen") or j.get("regenOf")),
347
+ "settings": {k: settings.get(k) for k in ("face_strength", "hair_strength", "hair_desc", "denoise", "prompt", "mask_main", "mask_ref") if settings.get(k) is not None},
348
+ }, result, image_bytes or source_bytes,
349
+ original_bytes=image_bytes if (image_bytes and remember_input) else None, original_name=j.get("filename", ""), orig_ref=j.get("origRef"))
350
+ _update(job_id, status="done", stage="done", elapsedSec=elapsed, finished_at=time.time())
351
+ print(f"[JOB] {job_id} done in {elapsed}s")
352
+ except cc.ComfyCancelled:
353
+ if ev.is_set(): # μ‚¬μš©μžκ°€ μ·¨μ†Œν•œ 경우: Comfy Cloud μͺ½ μ·¨μ†Œ κ²°κ³Όκ°€ λ‚˜μ˜¨ 뒀에 'μ·¨μ†Œλ¨'으둜 μ•Œλ¦°λ‹€
354
+ for _ in range(60):
355
+ with _LOCK:
356
+ j = _JOBS.get(job_id) or {}
357
+ if j.get("remoteCancel") or not j.get("promptId"):
358
+ break
359
+ time.sleep(0.25)
360
+ print(f"[JOB] {job_id} cancelled")
361
+ _update(job_id, status="cancelled", stage="cancelled", finished_at=time.time())
362
+ except cc.ComfyError as e:
363
+ print(f"[JOB] {job_id} error: {e}")
364
+ gone = reused and _input_gone(str(e))
365
+ _update(job_id, status="error", stage="error", finished_at=time.time(), errorCode="input_gone" if gone else None,
366
+ error="이전에 올렀 λ‘” 원본을 Comfy Cloud μ—μ„œ μ°Ύμ§€ λͺ»ν–ˆμ–΄μš”(보관 기간이 지났을 수 μžˆμ–΄μš”)." if gone else str(e))
367
+ except Exception as e: # noqa: BLE001
368
+ traceback.print_exc()
369
+ _update(job_id, status="error", stage="error", error=f"예기치 λͺ»ν•œ 였λ₯˜: {str(e)[:200]}", finished_at=time.time())
370
+
371
+
372
+ @app.post("/api/swap/jobs")
373
+ async def create_job(
374
+ request: Request,
375
+ image: UploadFile = File(...),
376
+ rel_path: str = Form(""),
377
+ gender: str = Form(...),
378
+ face_id: str = Form(""),
379
+ settings: str = Form("{}"),
380
+ preview: str = Form(""), # "1" 이면 원본이 μ•„λ‹ˆλΌ μ €μž₯된 미리보기둜 λ§Œλ“  μž‘μ—… β†’ 이 μž…λ ₯은 μž¬μƒμ„±μ— μ“°μ§€ μ•ŠλŠ”λ‹€
381
+ regen: str = Form(""), # "1" 이면 λ§ˆμŒμ— μ•ˆ λ“€μ–΄ λ‹€μ‹œ λ§Œλ“  μž‘μ—…(톡계에 μž¬μƒμ„±μœΌλ‘œ 기둝)
382
+ ):
383
+ user = get_current_user(request)
384
+ _require_login(user)
385
+ if gender not in GENDERS:
386
+ raise HTTPException(400, "gender λŠ” male λ˜λŠ” female 이어야 ν•©λ‹ˆλ‹€.")
387
+ st = cc.status()
388
+ if not st["ok"]:
389
+ raise HTTPException(500, st["error"])
390
+ data = await image.read()
391
+ if not data:
392
+ raise HTTPException(400, "빈 νŒŒμΌμž…λ‹ˆλ‹€.")
393
+ face = _FACES.get(face_id or f"default-{gender}")
394
+ if not face:
395
+ raise HTTPException(400, f"{'λ‚¨μž' if gender == 'male' else 'μ—¬μž'} μ–Όκ΅΄ 이미지가 μ—†μŠ΅λ‹ˆλ‹€. 얼꡴을 λ¨Όμ € μ˜¬λ €μ£Όμ„Έμš”.")
396
+ try:
397
+ opts = json.loads(settings or "{}")
398
+ if not isinstance(opts, dict):
399
+ opts = {}
400
+ except json.JSONDecodeError:
401
+ opts = {}
402
+ opts = _prep_settings(opts, gender, face_id)
403
+
404
+ _gc()
405
+ rel = _clean_rel(rel_path, image.filename or "")
406
+ job_id = uuid.uuid4().hex[:12]
407
+ with _LOCK:
408
+ _JOBS[job_id] = {
409
+ "status": "running", "stage": "queued_local", "created_at": time.time(),
410
+ "rel_path": rel, "filename": rel.split("/")[-1], "gender": gender,
411
+ "cancel": threading.Event(), "user": user, "regen": bool(regen),
412
+ }
413
+ threading.Thread(target=_run_job, args=(job_id, data, face, opts, None, None, not preview), daemon=True).start()
414
+ return {"jobId": job_id}
415
+
416
+
417
+ @app.post("/api/swap/regen")
418
+ def regen_job(request: Request, from_id: str = Form(...), face_id: str = Form(""), settings: str = Form("{}")):
419
+ """μ§€λ‚œ κ²°κ³Ό(from_id)와 같은 μ›λ³ΈμœΌλ‘œ μƒˆ κ²°κ³Όλ₯Ό ν•˜λ‚˜ 더 λ§Œλ“ λ‹€.
420
+ 원본을 λ‹€μ‹œ μ˜¬λ¦¬μ§€ μ•Šκ³ , κ·Έλ•Œ Comfy Cloud 에 올렀 λ‘” μž…λ ₯ νŒŒμΌμ„ κ·ΈλŒ€λ‘œ μ“΄λ‹€ β†’ 원본 ν™”μ§ˆ μœ μ§€, μƒˆλ‘œκ³ μΉ¨ 후에도 λ™μž‘."""
421
+ user = get_current_user(request)
422
+ _require_login(user)
423
+ st = cc.status()
424
+ if not st["ok"]:
425
+ raise HTTPException(500, st["error"])
426
+ e = history.entry(from_id)
427
+ if not e:
428
+ raise HTTPException(404, "μ§€λ‚œ κ²°κ³Όλ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")
429
+ comfy_image = e.get("comfy_image")
430
+ if not comfy_image:
431
+ raise HTTPException(409, "이 κ²°κ³ΌλŠ” 원본 정보가 μ €μž₯λ˜μ§€ μ•Šμ•˜μ–΄μš”(이전 λ²„μ „μœΌλ‘œ λ§Œλ“  κ²°κ³Ό).")
432
+ gender = e.get("gender")
433
+ if gender not in GENDERS:
434
+ raise HTTPException(400, "성별 정보가 μ—†λŠ” κ²°κ³Όμ˜ˆμš”.")
435
+ face = _FACES.get(face_id or f"default-{gender}")
436
+ if not face:
437
+ raise HTTPException(400, f"{'λ‚¨μž' if gender == 'male' else 'μ—¬μž'} μ–Όκ΅΄ 이미지가 μ—†μŠ΅λ‹ˆλ‹€.")
438
+ try:
439
+ opts = json.loads(settings or "{}")
440
+ if not isinstance(opts, dict):
441
+ opts = {}
442
+ except json.JSONDecodeError:
443
+ opts = {}
444
+ opts = _prep_settings(opts, gender, face_id)
445
+ src_path = history.path(from_id, "source") # λͺ©λ‘ λΉ„κ΅μš© 미리보기만 μ΄μ–΄λ°›λŠ”λ‹€
446
+ src = None
447
+ if src_path:
448
+ with open(src_path, "rb") as f:
449
+ src = f.read()
450
+ _gc()
451
+ job_id = uuid.uuid4().hex[:12]
452
+ rel = e.get("rel_path", "")
453
+ with _LOCK:
454
+ _JOBS[job_id] = {
455
+ "status": "running", "stage": "queued_local", "created_at": time.time(),
456
+ "rel_path": rel, "filename": e.get("filename") or rel.split("/")[-1], "gender": gender,
457
+ "cancel": threading.Event(), "regenOf": from_id, "user": user, "regen": True,
458
+ **({"origRef": {"orig_file": e["orig_file"], "orig_size": e.get("orig_size")}} if e.get("orig_file") else {}),
459
+ }
460
+ threading.Thread(target=_run_job, args=(job_id, None, face, opts, comfy_image, src), daemon=True).start()
461
+ return {"jobId": job_id}
462
+
463
+
464
+ @app.post("/api/swap/cancel")
465
+ def cancel_jobs(payload: Dict[str, Any] = Body(...)):
466
+ """μ§„ν–‰Β·λŒ€κΈ° 쀑인 μž‘μ—…μ„ μ·¨μ†Œν•œλ‹€. Comfy Cloud μͺ½ μ·¨μ†ŒλŠ” λ’€μ—μ„œ μ²˜λ¦¬ν•œλ‹€."""
467
+ ids = [str(i) for i in payload.get("ids", [])]
468
+ prompt_ids = set()
469
+ n = 0
470
+ with _LOCK:
471
+ for i in ids:
472
+ j = _JOBS.get(i)
473
+ if j and j.get("status") == "running":
474
+ j["cancel"].set()
475
+ n += 1
476
+ if j.get("promptId"):
477
+ prompt_ids.add(j["promptId"])
478
+ if prompt_ids:
479
+ threading.Thread(target=_remote_cancel, args=(prompt_ids,), daemon=True).start()
480
+ return {"cancelled": n}
481
+
482
+
483
+ @app.get("/api/swap/jobs/{job_id}")
484
+ def job_info(job_id: str):
485
+ with _LOCK:
486
+ job = _JOBS.get(job_id)
487
+ snap = dict(job) if job else None
488
+ if snap is None:
489
+ e = history.entry(job_id) # μž¬μ‹œμž‘ 후에도 λλ‚œ μž‘μ—…μ€ 기둝에 남아 μžˆλ‹€
490
+ if e:
491
+ return {"status": "done", "stage": "done", "stageLabel": STAGE_LABEL["done"], "error": None, "elapsedSec": e.get("elapsedSec", 0)}
492
+ raise HTTPException(404, "μž‘μ—…μ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€ (μ„œλ²„κ°€ μž¬μ‹œμž‘λ˜μ—ˆμ„ 수 μžˆμŠ΅λ‹ˆλ‹€).")
493
+ stage = snap.get("stage", "")
494
+ return {
495
+ "status": snap["status"],
496
+ "stage": stage,
497
+ "stageLabel": STAGE_LABEL.get(stage, stage),
498
+ "error": snap.get("error"),
499
+ "errorCode": snap.get("errorCode"),
500
+ "cancelMode": snap.get("remoteCancel"), # removed | interrupted | soft(Cloud μ—μ„œλŠ” 이미 μ‹€ν–‰ 쀑이라 λκΉŒμ§€ μ§„ν–‰)
501
+ "elapsedSec": round((snap.get("finished_at") or time.time()) - snap["created_at"], 1),
502
+ }
503
+
504
+
505
+ # ── κ²°κ³Ό 파일 (원본 파일λͺ…Β·ν™•μž₯자 μœ μ§€) ───────────────────────────────────────
506
+ def _done_job(job_id: str) -> Dict[str, Any]:
507
+ e = history.entry(job_id)
508
+ path = history.path(job_id, "result") if e else None
509
+ if not e or not path:
510
+ raise HTTPException(404, "μ €μž₯된 κ²°κ³Όκ°€ μ—†μŠ΅λ‹ˆλ‹€.")
511
+ return {**e, "path": path}
512
+
513
+
514
+ def _encode_like_original(job: Dict[str, Any]) -> tuple[bytes, str, str]:
515
+ """κ²°κ³Όλ₯Ό 원본과 같은 파일λͺ…Β·ν™•μž₯자둜 인코딩. (bytes, filename, media_type)
516
+
517
+ jpg/jpeg β†’ JPEG(q95) Β· png β†’ PNG Β· webp β†’ WEBP.
518
+ κ·Έ μ™Έ ν™•μž₯자(bmp λ“±)λŠ” 파일λͺ… 쀄기λ₯Ό μœ μ§€ν•˜κ³  .png 둜 μ €μž₯ν•œλ‹€.
519
+ """
520
+ name = job["filename"]
521
+ stem, ext = os.path.splitext(name)
522
+ low = ext.lower()
523
+ img = Image.open(job["path"])
524
+ img.load()
525
+ img = img.convert("RGB")
526
+ out = io.BytesIO()
527
+ if low in (".jpg", ".jpeg"):
528
+ img.save(out, "JPEG", quality=95, subsampling=0, optimize=True)
529
+ return out.getvalue(), name, "image/jpeg"
530
+ if low == ".webp":
531
+ img.save(out, "WEBP", quality=95)
532
+ return out.getvalue(), name, "image/webp"
533
+ img.save(out, "PNG", compress_level=6)
534
+ return out.getvalue(), (name if low == ".png" else f"{stem}.png"), "image/png"
535
+
536
+
537
+ def _content_disposition(kind: str, filename: str) -> str:
538
+ ascii_fallback = re.sub(r"[^A-Za-z0-9._-]", "_", unicodedata.normalize("NFKD", filename).encode("ascii", "ignore").decode()) or "result"
539
+ return f"{kind}; filename=\"{ascii_fallback}\"; filename*=UTF-8''{quote(filename)}"
540
+
541
+
542
+ @app.get("/api/swap/jobs/{job_id}/thumb")
543
+ def job_thumb(job_id: str):
544
+ p = history.path(job_id, "thumb")
545
+ if not p:
546
+ raise HTTPException(404, "썸넀일이 μ—†μŠ΅λ‹ˆλ‹€.")
547
+ return FileResponse(p, media_type="image/jpeg", headers={"Cache-Control": "max-age=3600"})
548
+
549
+
550
+ @app.get("/api/swap/jobs/{job_id}/source")
551
+ def job_source(job_id: str):
552
+ p = history.path(job_id, "source")
553
+ if not p:
554
+ raise HTTPException(404, "원본 미리보기가 μ—†μŠ΅λ‹ˆλ‹€.")
555
+ return FileResponse(p, media_type="image/jpeg", headers={"Cache-Control": "max-age=3600"})
556
+
557
+
558
+ @app.get("/api/swap/jobs/{job_id}/original")
559
+ def job_original(job_id: str):
560
+ """올린 원본을 파일 κ·ΈλŒ€λ‘œ λ‚΄λ €μ€€λ‹€(μ €μž₯된 결과만). 파일 이름은 'μ›λž˜μ΄λ¦„_원본.ν™•μž₯자'."""
561
+ e = history.entry(job_id)
562
+ p = history.path(job_id, "original") if e else None
563
+ if not e or not p:
564
+ raise HTTPException(404, "원본이 μ €μž₯λ˜μ–΄ μžˆμ§€ μ•Šμ•„μš”(원본 μ €μž₯ κΈ°λŠ₯을 λ„£κΈ° 전에 λ§Œλ“  κ²°κ³Όμ˜ˆμš”).")
565
+ stem = os.path.splitext(e.get("filename") or "photo")[0]
566
+ ext = os.path.splitext(p)[1]
567
+ mt = mimetypes.guess_type(p)[0] or "application/octet-stream"
568
+ return FileResponse(p, media_type=mt, headers={"Content-Disposition": _content_disposition("attachment", f"{stem}_원본{ext}")})
569
+
570
+
571
+ @app.get("/api/swap/jobs/{job_id}/view")
572
+ def job_view(job_id: str):
573
+ job = _done_job(job_id)
574
+ data, name, mt = _encode_like_original(job)
575
+ return Response(data, media_type=mt, headers={"Content-Disposition": _content_disposition("inline", name)})
576
+
577
+
578
+ @app.get("/api/swap/jobs/{job_id}/download")
579
+ def job_download(job_id: str, tag: str = Query("")):
580
+ """κ²°κ³Ό λ‹€μš΄λ‘œλ“œ. tag(예: 1μ•ˆ)λ₯Ό μ£Όλ©΄ 파일λͺ… 끝에 뢙인닀 β†’ 같은 μ‚¬μ§„μ˜ 1μ•ˆΒ·2μ•ˆμ΄ 같은 μ΄λ¦„μœΌλ‘œ κ²ΉμΉ˜μ§€ μ•ŠλŠ”λ‹€."""
581
+ job = _done_job(job_id)
582
+ data, name, mt = _encode_like_original(job)
583
+ t = re.sub(r"[^0-9A-Za-zκ°€-힣_-]", "", tag or "")[:20] # μ•ˆμ „ν•œ κΈ€μžλ§Œ(경둜·특수문자 제거)
584
+ if t:
585
+ stem, ext = os.path.splitext(name)
586
+ name = f"{stem}_{t}{ext}"
587
+ return Response(data, media_type=mt, headers={"Content-Disposition": _content_disposition("attachment", name)})
588
+
589
+
590
+ @app.post("/api/swap/zip")
591
+ def zip_download(ids: str = Form(...), name: str = Form("faceswap_results")):
592
+ """μ„ νƒν•œ μ™„λ£Œ μž‘μ—…μ„ ZIP 으둜. 폴더 ꡬ쑰와 파일λͺ…을 μ—…λ‘œλ“œν•œ κ·ΈλŒ€λ‘œ μœ μ§€ν•œλ‹€."""
593
+ wanted = [i for i in re.split(r"[,\s]+", ids) if i]
594
+ if not wanted:
595
+ raise HTTPException(400, "λ‹€μš΄λ‘œλ“œν•  μž‘μ—…μ΄ μ—†μŠ΅λ‹ˆλ‹€.")
596
+ tmp = tempfile.TemporaryFile()
597
+ used: set[str] = set()
598
+ count = 0
599
+ with zipfile.ZipFile(tmp, "w", zipfile.ZIP_STORED) as zf:
600
+ for jid in wanted:
601
+ try:
602
+ job = _done_job(jid)
603
+ except HTTPException:
604
+ continue
605
+ data, fname, _ = _encode_like_original(job)
606
+ folder = "/".join(job["rel_path"].split("/")[:-1])
607
+ arc = f"{folder}/{fname}" if folder else fname
608
+ base, ext = os.path.splitext(arc)
609
+ n = 2
610
+ while arc in used:
611
+ arc = f"{base} ({n}){ext}"
612
+ n += 1
613
+ used.add(arc)
614
+ zf.writestr(arc, data)
615
+ count += 1
616
+ if count == 0:
617
+ tmp.close()
618
+ raise HTTPException(404, "μ™„λ£Œλœ κ²°κ³Όκ°€ μ—†μŠ΅λ‹ˆλ‹€.")
619
+ tmp.seek(0)
620
+
621
+ def _iter():
622
+ try:
623
+ while chunk := tmp.read(1024 * 1024):
624
+ yield chunk
625
+ finally:
626
+ tmp.close()
627
+
628
+ safe = re.sub(r'[\\/:*?"<>|]', "_", name).strip() or "faceswap_results"
629
+ zip_name = f"{safe}.zip"
630
+ return StreamingResponse(_iter(), media_type="application/zip",
631
+ headers={"Content-Disposition": _content_disposition("attachment", zip_name)})
632
+
633
+
634
+ # ── μ§€λ‚œ κ²°κ³Ό ─────────────────────────────────────────────────────────────────
635
+ @app.get("/api/history")
636
+ def history_list(q: str = "", limit: int = 1000):
637
+ items = history.list_entries(q, min(max(limit, 1), 3000))
638
+ return {"items": [{**{k: e.get(k) for k in ("id", "rel_path", "filename", "folder", "gender", "date", "time", "elapsedSec")}, "canRegen": bool(e.get("comfy_image")), "hasOriginal": bool(e.get("orig_file")), "origSize": e.get("orig_size")} for e in items],
639
+ "total": len(items)}
640
+
641
+
642
+ @app.post("/api/history/hide")
643
+ def history_hide(payload: Dict[str, Any] = Body(...)):
644
+ ids = [str(i) for i in payload.get("ids", [])]
645
+ return {"hidden": history.hide(ids)}
646
+
647
+
648
+ CREDITS_PER_IMAGE = float(os.environ.get("CREDITS_PER_IMAGE", "8.6")) # λŒ€λž΅μΉ˜(μž₯λ‹Ή GPU μ•½ 22초 Γ— 0.39 ν¬λ ˆλ”§/초). λŒ€μ‹œλ³΄λ“œμ˜ 'λŒ€λž΅ ν¬λ ˆλ”§'μ—λ§Œ μ“΄λ‹€.
649
+
650
+
651
+ @app.get("/api/dashboard")
652
+ def dashboard(request: Request, date_from: str = Query("", alias="from"), date_to: str = Query("", alias="to"), recent: int = 60):
653
+ """생성 기둝 λŒ€μ‹œλ³΄λ“œ: μ§€λ‚œ κ²°κ³Ό 기둝(μ™„λ£Œλœ μƒμ„±λ§Œ)을 κΈ°κ°„λ³„λ‘œ μ§‘κ³„ν•œλ‹€. λͺ©λ‘μ—μ„œ 숨긴 것도 ν¬ν•¨ν•΄μ„œ μ„Όλ‹€."""
654
+ _require_login(get_current_user(request))
655
+ df, dt = (date_from or "")[:10], (date_to or "")[:10]
656
+ rows = [e for e in history.all_entries() if (not df or e.get("date", "") >= df) and (not dt or e.get("date", "") <= dt)]
657
+ days: Dict[str, Dict[str, Any]] = {}
658
+ users: Dict[str, Dict[str, Any]] = {}
659
+ folders: Dict[str, Dict[str, Any]] = {}
660
+ files: set = set()
661
+ hours = [0] * 24
662
+ gender = {"male": 0, "female": 0}
663
+ elapsed_all: List[float] = []
664
+ regen_total = 0
665
+ for e in rows:
666
+ day = e.get("date", "")
667
+ is_regen = bool(e.get("regen"))
668
+ rel = unicodedata.normalize("NFC", e.get("rel_path") or e.get("filename") or "")
669
+ stamp = e.get("created_at", "")
670
+ d = days.setdefault(day, {"day": day, "gen": 0, "regen": 0})
671
+ d["gen"] += 1
672
+ d["regen"] += 1 if is_regen else 0
673
+ regen_total += 1 if is_regen else 0
674
+ files.add(rel)
675
+ if e.get("gender") in gender:
676
+ gender[e["gender"]] += 1
677
+ try:
678
+ hours[int((e.get("time") or "00:00")[:2])] += 1
679
+ except ValueError:
680
+ pass
681
+ es = e.get("elapsedSec")
682
+ if isinstance(es, (int, float)):
683
+ elapsed_all.append(float(es))
684
+ uk = e.get("user_username", "") # "" = 이 κΈ°λŠ₯ 이전 기둝(미기둝), "anonymous" = 둜그인 없이 μ‚¬μš©
685
+ u = users.setdefault(uk, {"username": uk, "name": "", "gen": 0, "regen": 0, "files": set(), "days": set(), "elapsed": [], "last": ""})
686
+ u["name"] = e.get("user_name") or u["name"]
687
+ u["gen"] += 1
688
+ u["regen"] += 1 if is_regen else 0
689
+ u["files"].add(rel)
690
+ u["days"].add(day)
691
+ if isinstance(es, (int, float)):
692
+ u["elapsed"].append(float(es))
693
+ u["last"] = max(u["last"], stamp)
694
+ fk = rel.rsplit("/", 1)[0] if "/" in rel else history.NO_FOLDER
695
+ f = folders.setdefault(fk, {"folder": fk, "gen": 0, "files": set(), "last": ""})
696
+ f["gen"] += 1
697
+ f["files"].add(rel)
698
+ f["last"] = max(f["last"], stamp)
699
+
700
+ def avg(xs: List[float]) -> Optional[float]:
701
+ return round(sum(xs) / len(xs), 1) if xs else None
702
+
703
+ user_list = sorted(({"username": u["username"], "name": u["name"], "gen": u["gen"], "regen": u["regen"], "files": len(u["files"]),
704
+ "active_days": len(u["days"]), "avg_elapsed": avg(u["elapsed"]), "last": u["last"].replace("T", " ")[:16]} for u in users.values()),
705
+ key=lambda x: (-x["gen"], x["username"]))
706
+ folder_list = sorted(({"folder": f["folder"], "gen": f["gen"], "files": len(f["files"]), "last": f["last"].replace("T", " ")[:16]} for f in folders.values()),
707
+ key=lambda x: (-x["gen"], x["folder"]))
708
+ rows.sort(key=lambda e: e.get("created_at", ""), reverse=True)
709
+ recent_list = [{"id": e["id"], "when": f"{e.get('date', '')} {e.get('time', '')}", "rel_path": e.get("rel_path", ""), "filename": e.get("filename", ""),
710
+ "gender": e.get("gender", ""), "elapsed": e.get("elapsedSec"), "regen": bool(e.get("regen")),
711
+ "username": e.get("user_username", ""), "name": e.get("user_name", ""),
712
+ "hasOriginal": bool(e.get("orig_file")), "origSize": e.get("orig_size")} for e in rows[:max(1, min(recent, 200))]]
713
+ st = history.status()
714
+ all_days = sorted(d for d in days if d)
715
+ return {
716
+ "summary": {"gen": len(rows), "files": len(files), "regen": regen_total, "users": len([u for u in users if u and u != "anonymous"]), "days": len(all_days),
717
+ "avg_elapsed": avg(elapsed_all), "credits_est": round(len(rows) * CREDITS_PER_IMAGE),
718
+ "first_day": all_days[0] if all_days else "", "last_day": all_days[-1] if all_days else "",
719
+ "legacy_rows": users.get("", {}).get("gen", 0)},
720
+ "daily": [days[d] for d in sorted(days)], "gender": gender, "hours": hours,
721
+ "users": user_list, "folders": folder_list, "recent": recent_list,
722
+ "filter": {"from": df, "to": dt}, "durable": bool(st.get("durable")), "remote": st.get("remote", ""),
723
+ }
724
+
725
+
726
+ @app.get("/api/history/status")
727
+ def history_status():
728
+ return history.status()
729
+
730
+
731
+ @app.on_event("shutdown")
732
+ def _on_shutdown() -> None:
733
+ history.flush(20)
734
+
735
+
736
+ # ── μ„€μ • / μƒνƒœ ───────────────────────────────────────────────────────────────
737
+ @app.get("/api/swap/defaults")
738
+ def defaults():
739
+ try:
740
+ return cc.workflow_defaults()
741
+ except cc.ComfyError as e:
742
+ raise HTTPException(500, str(e))
743
+
744
+
745
+ @app.get("/api/health")
746
+ def health():
747
+ return {**cc.status(), "maxConcurrent": MAX_CONCURRENT, "oauth": _OAUTH_ATTACHED}
748
+
749
+
750
+ @app.get("/api/whoami")
751
+ def whoami(request: Request):
752
+ """ν™”λ©΄ μœ„μͺ½μ˜ 둜그인 ν‘œμ‹œμš©."""
753
+ u = get_current_user(request)
754
+ return {**u, "oauth_enabled": _OAUTH_ATTACHED, "login_required": _login_required(),
755
+ "login_url": "/oauth/huggingface/login" if _OAUTH_ATTACHED else None,
756
+ "logout_url": "/oauth/huggingface/logout" if _OAUTH_ATTACHED else None}
757
+
758
+
759
+ def _find_index() -> Optional[str]:
760
+ """ν™”λ©΄ 파일 μœ„μΉ˜: 루트의 index.html 을 μš°μ„ , μ—†μœΌλ©΄ static/index.html. (λ‘˜ 쀑 어디에 μ˜¬λ €λ„ λ™μž‘)"""
761
+ for cand in (os.path.join(BASE_DIR, "index.html"), os.path.join(BASE_DIR, "static", "index.html")):
762
+ if os.path.exists(cand):
763
+ return cand
764
+ return None
765
+
766
+
767
+ @app.get("/", include_in_schema=False)
768
+ @app.get("/index.html", include_in_schema=False)
769
+ def index_page(request: Request):
770
+ if _login_required() and not get_current_user(request)["is_logged_in"]:
771
+ return HTMLResponse(_LOGIN_GATE_HTML, status_code=401, headers={"Cache-Control": "no-cache"})
772
+ path = _find_index()
773
+ if not path:
774
+ raise HTTPException(500, "index.html 파일이 μ—†μŠ΅λ‹ˆλ‹€. server.py 와 같은 폴더(λ˜λŠ” static/)에 μ˜¬λ €μ£Όμ„Έμš”.")
775
+ return FileResponse(path, media_type="text/html", headers={"Cache-Control": "no-cache"})