sunyoung00 commited on
Commit
09388ba
Β·
verified Β·
1 Parent(s): a12ee28

Upload 3 files

Browse files
Files changed (3) hide show
  1. comfy_client (20).py +566 -0
  2. comfy_routes (20).py +372 -0
  3. index (45).html +659 -0
comfy_client (20).py ADDED
@@ -0,0 +1,566 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ comfy_client.py β€” Comfy Cloud REST ν΄λΌμ΄μ–ΈνŠΈ (SPAO 룩뢁 μ›Œν¬ν”Œλ‘œμš° μ „μš©)
3
+
4
+ 흐름: 이미지 μ—…λ‘œλ“œ(ν•΄μ‹œ μΊμ‹œ) β†’ workflow_api.json 패치 β†’ /api/prompt 제좜
5
+ β†’ /api/job/{id}/status 폴링 β†’ 좜λ ₯ 파일 λ‹€μš΄λ‘œλ“œ(/api/view 302 β†’ signed URL)
6
+
7
+ ν•„μš” ν™˜κ²½λ³€μˆ˜:
8
+ COMFY_CLOUD_API_KEY platform.comfy.org μ—μ„œ λ°œκΈ‰ν•œ ν‚€ (Space secret)
9
+ COMFY_BASE_URL κΈ°λ³Έ https://cloud.comfy.org
10
+ COMFY_WORKFLOW_PATH κΈ°λ³Έ workflow_api.json (Comfy Cloud μ—λ””ν„°μ—μ„œ Export (API) 둜 μ €μž₯ν•œ 파일)
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import base64
15
+ import copy
16
+ import hashlib
17
+ import io
18
+ import json
19
+ import os
20
+ import random
21
+ import threading
22
+ import time
23
+ from typing import Any, Dict, List, Optional, Tuple
24
+
25
+ import httpx
26
+ from PIL import Image
27
+
28
+ BASE_URL = os.environ.get("COMFY_BASE_URL", "https://cloud.comfy.org").rstrip("/")
29
+ API_KEY = os.environ.get("COMFY_CLOUD_API_KEY", "")
30
+ WORKFLOW_PATH = os.environ.get("COMFY_WORKFLOW_PATH", "workflow_api.json")
31
+
32
+ # ── μ›Œν¬ν”Œλ‘œμš° λ…Έλ“œ ID (SPAO.json κΈ°μ€€, API export μ‹œ κ·ΈλŒ€λ‘œ μœ μ§€λ¨) ──────────
33
+ IMAGE_NODES = {
34
+ "face": "646", # μ–Όκ΅΄
35
+ "outer": "901", # μ•„μš°ν„°
36
+ "top": "902", # μƒμ˜
37
+ "bottom": "908", # ν•˜μ˜
38
+ "shoes": "909", # μ‹ λ°œ
39
+ "inner": "957", # μ΄λ„ˆμ›¨μ–΄
40
+ "belt": "958", # 벨트
41
+ "background": "907", # λ°°κ²½
42
+ "pose": "916", # 레퍼런슀 포즈
43
+ }
44
+ # λ””ν…ŒμΌ μ°Έμ‘° (v5 μ›Œν¬ν”Œλ‘œμš°λΆ€ν„°) β€” 쑰직감/둜고/λ„₯라인/μ†Œλ§€/밑단/λΆ€μžμž¬ ν΄λ‘œμ¦ˆμ—…μ„ GPT-image 의 image_9~12 슬둯으둜 직접 전달.
45
+ # μ‚¬μš©ν•˜μ§€ μ•ŠλŠ” μŠ¬λ‘―μ€ API μ›Œν¬ν”Œλ‘œμš°μ—μ„œ μž…λ ₯ 자체λ₯Ό μ œκ±°ν•΄ 빈 이미지가 μ „μ†‘λ˜μ§€ μ•Šκ²Œ ν•œλ‹€.
46
+ GPT_IMAGE_NODE = "915"
47
+ DETAIL_NODES = {"detail1": "1046", "detail2": "1047", "detail3": "1048", "detail4": "1049"}
48
+ DETAIL_SLOT_INDEX = {"detail1": 9, "detail2": 10, "detail3": 11, "detail4": 12}
49
+ DETAIL_GARMENT_EN = {"outer": "OUTERWEAR (image 1)", "top": "TOP (image 2)", "bottom": "BOTTOMS (image 5)",
50
+ "shoes": "SHOES (image 6)", "inner": "INNERWEAR (image 8, left)", "belt": "BELT (image 8, right)"}
51
+ # ν‚€λŠ” index.html 의 DETAIL_KINDS_BY_GARMENT ν•­λͺ©κ³Ό 1:1. texture/material 은 전체 적용, λ‚˜λ¨Έμ§€λŠ” κ΅­μ†Œ 적용 κ·œμΉ™μ„ 뢙인닀.
52
+ _DETAIL_LOCAL_RULE = ("apply ONLY to that region; keep the item's silhouette, length, fit, color and every other part "
53
+ "exactly as in its main photo β€” this is a localized construction reference, not a new item")
54
+ DETAIL_KIND_EN = {
55
+ # 전체 적용
56
+ "texture": "FABRIC TEXTURE close-up β€” reproduce this exact weave/knit/pile and surface finish across the whole garment at realistic scale",
57
+ "material": "MATERIAL close-up (leather, suede, mesh, canvas…) β€” reproduce this exact material grain, sheen and surface finish across the whole item at realistic scale",
58
+ # μœ„μΉ˜ κ³ μ •
59
+ "logo": "LOGO/PRINT close-up β€” reproduce this exact graphic with the same shape, colors and proportions, at the same position on the item as in its main photo",
60
+ # 의λ₯˜ κ΅­μ†Œ
61
+ "neckline": f"NECKLINE close-up β€” reproduce this exact neckline shape, ribbing, binding and stitching; {_DETAIL_LOCAL_RULE}",
62
+ "collar": f"COLLAR/HOOD/LAPEL close-up β€” reproduce this exact collar or hood construction, shape, lining and stitching; {_DETAIL_LOCAL_RULE}",
63
+ "sleeve": f"SLEEVE/CUFF close-up β€” reproduce this exact cuff construction, ribbing, hem finish and stitching at the sleeve ends; {_DETAIL_LOCAL_RULE}",
64
+ "hem": f"HEM close-up β€” reproduce this exact bottom-edge finish (ribbing, banding, cuff, raw/rolled edge, stitching); {_DETAIL_LOCAL_RULE}",
65
+ "waist": f"WAISTBAND close-up β€” reproduce this exact waistband construction (band width, belt loops, drawstring, elastic, button/fly) at the waist; {_DETAIL_LOCAL_RULE}",
66
+ "pocket": f"POCKET close-up β€” reproduce this exact pocket shape, flap, topstitching and placement; {_DETAIL_LOCAL_RULE}",
67
+ "closure": f"CLOSURE close-up (zipper, buttons, snaps) β€” reproduce this exact hardware type, color, size and spacing along the closure; {_DETAIL_LOCAL_RULE}",
68
+ "trim": f"TRIM/LABEL close-up (tag, tab, patch, hardware) β€” reproduce this exact component with the same shape, material and placement as in the main photo; {_DETAIL_LOCAL_RULE}",
69
+ # μ‹ λ°œ
70
+ "sole": f"SOLE/OUTSOLE close-up β€” reproduce this exact sole profile, thickness, tread pattern and color on the shoe; {_DETAIL_LOCAL_RULE}",
71
+ "lacing": f"LACING close-up β€” reproduce this exact lace type, color, eyelets and tongue; {_DETAIL_LOCAL_RULE}",
72
+ "heel": f"HEEL/ANKLE close-up β€” reproduce this exact heel counter, heel tab and ankle collar shape; {_DETAIL_LOCAL_RULE}",
73
+ # 벨트
74
+ "buckle": f"BUCKLE close-up β€” reproduce this exact buckle shape, size, metal finish and prong; {_DETAIL_LOCAL_RULE}",
75
+ "edge": f"STITCHING/EDGE close-up β€” reproduce this exact edge finish, stitching line, hole shape and tip on the belt; {_DETAIL_LOCAL_RULE}",
76
+ }
77
+
78
+ # CustomCombo λ…Έλ“œ: (node_id, μ˜΅μ…˜ λͺ©λ‘) β€” μ˜΅μ…˜ μˆœμ„œ = INDEX 좜λ ₯κ°’
79
+ COMBO_NODES = {
80
+ "shot": ("917", ["μ „μ‹ μ»·", "μƒλ°˜μ‹ μ»·", "ν•˜λ°˜μ‹ μ»·", "레퍼런슀 ꡬ도 κ·ΈλŒ€λ‘œ"]),
81
+ "angle": ("962", ["μ •λ©΄", "반츑면", "μΈ‘λ©΄", "λ‘œμš°μ•΅κΈ€", "ν•˜μ΄μ•΅κΈ€", "ν›„λ©΄", "레퍼런슀 따름"]), # 레퍼런슀 따름: v10~
82
+ "gaze": ("992", ["카메라 μ‘μ‹œ", "μžμ—°μŠ€λŸ¬μš΄ μ‹œμ„ ", "레퍼런슀 따름"]),
83
+ "age": ("918", ["성인", "ν‚€μ¦ˆ"]),
84
+ "outer_length": ("930", ["ν—ˆλ¦¬", "골반", "ν—ˆλ²…μ§€"]),
85
+ "outer_fit": ("931", ["슬림", "ν‘œμ€€", "μ˜€λ²„"]),
86
+ "top_length": ("932", ["ν—ˆλ¦¬", "골반", "ν—ˆλ²…μ§€"]),
87
+ "top_fit": ("933", ["슬림", "ν‘œμ€€", "μ˜€λ²„"]),
88
+ "bottom_length": ("934", ["ν—ˆλ²…μ§€", "무릎", "쒅아리", "발λͺ©", "μ‹ λ°œ"]),
89
+ "bottom_fit": ("935", ["슬림", "ν‘œμ€€", "μ˜€λ²„"]),
90
+ }
91
+
92
+ PROMPT_NODE = "914" # StringConcatenate "ν”„λ‘¬ν”„νŠΈ μž‘μ„±" β†’ string_b
93
+ SEED_NODES = ["781", "989"] # KSampler μ‹œλ“œ / 손 보정 μƒ˜ν”ŒλŸ¬
94
+ OUTPUT_NODE = "760" # SaveImage "Image Save(Output)"
95
+ TEXT_LOG_NODES = {"garment_specs": "1050", "final_prompt": "1051", "pose_spec": "1055"} # PreviewAny β€” μ˜μƒ 뢄석 / μ΅œμ’… ν”„λ‘¬ν”„νŠΈ / 포즈 뢄석(v14~)
96
+ # 포즈 ν…μŠ€νŠΈ μ˜€λ²„λΌμ΄λ“œ (v14~): 레퍼런슀 포즈 사진 β†’ GPT 비전이 λ¬Έμž₯으둜 β†’ ν”„λ‘¬ν”„νŠΈ 맨 끝에 FINAL POSE OVERRIDE 둜 κ²°ν•©
97
+ POSE_ANALYSIS_NODE = "1052" # OpenAIChatNode "포즈 뢄석 (GPT λΉ„μ „)"
98
+ POSE_PREFIX_NODE = "1053" # StringConcatenate: 접두문 + 뢄석 λ¬Έμž₯
99
+ POSE_FINAL_NODE = "1054" # StringConcatenate: κΈ°μ‘΄ μ΅œμ’… ν”„λ‘¬ν”„νŠΈ + 포즈 μ˜€λ²„λΌμ΄λ“œ β†’ GPT-image
100
+ SHOT_PROMPT_NODE = "912" # μƒ· 선택 ν”„λ‘¬ν”„νŠΈ β€” ν¬μ¦ˆκ°€ μžˆμ„ 땐 κΈ°λ³Έ μžμ„Έ 문ꡬλ₯Ό μ™„ν™”
101
+ _SHOT_POSTURE_RELAX = [("model standing straight, ", ""), ("model standing straight", "")]
102
+
103
+ TERMINAL_OK = {"success"}
104
+ TERMINAL_FAIL = {"error", "non_retryable_error", "lost", "cancelled"}
105
+
106
+ _HTTP_TIMEOUT = httpx.Timeout(connect=10.0, read=120.0, write=120.0, pool=10.0)
107
+
108
+
109
+ class ComfyError(RuntimeError):
110
+ pass
111
+
112
+
113
+ def _headers(json_ct: bool = True) -> Dict[str, str]:
114
+ if not API_KEY:
115
+ raise ComfyError("COMFY_CLOUD_API_KEY ν™˜κ²½λ³€μˆ˜κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€ (Space Settings β†’ Secrets).")
116
+ h = {"X-API-Key": API_KEY}
117
+ if json_ct:
118
+ h["Content-Type"] = "application/json"
119
+ return h
120
+
121
+
122
+ # ── μ›Œν¬ν”Œλ‘œμš° ν…œν”Œλ¦Ώ ──────────────────────────────────────────────────────────
123
+ _WORKFLOW_TEMPLATE: Optional[Dict[str, Any]] = None
124
+ _WORKFLOW_ERROR: Optional[str] = None
125
+
126
+
127
+ def load_workflow_template() -> Dict[str, Any]:
128
+ global _WORKFLOW_TEMPLATE, _WORKFLOW_ERROR
129
+ if _WORKFLOW_TEMPLATE is not None:
130
+ return _WORKFLOW_TEMPLATE
131
+ if not os.path.exists(WORKFLOW_PATH):
132
+ _WORKFLOW_ERROR = f"{WORKFLOW_PATH} 파일이 μ—†μŠ΅λ‹ˆλ‹€. Comfy Cloud μ—λ””ν„°μ—μ„œ μ›Œν¬ν”Œλ‘œμš°λ₯Ό μ—΄κ³  Export (API)둜 μ €μž₯ν•΄ Space λ£¨νŠΈμ— λ„£μ–΄μ£Όμ„Έμš”."
133
+ raise ComfyError(_WORKFLOW_ERROR)
134
+ with open(WORKFLOW_PATH, "r", encoding="utf-8") as f:
135
+ wf = json.load(f)
136
+ if not isinstance(wf, dict) or "nodes" in wf:
137
+ _WORKFLOW_ERROR = f"{WORKFLOW_PATH} λŠ” API 포맷이 μ•„λ‹™λ‹ˆλ‹€ (nodes/links μΊ”λ²„μŠ€ μ €μž₯ ν˜•μ‹). Export (API) 둜 λ‹€μ‹œ μ €μž₯ν•΄μ£Όμ„Έμš”."
138
+ raise ComfyError(_WORKFLOW_ERROR)
139
+ missing = [nid for nid in list(IMAGE_NODES.values()) + [PROMPT_NODE, OUTPUT_NODE] + SEED_NODES if nid not in wf]
140
+ if missing:
141
+ _WORKFLOW_ERROR = f"workflow_api.json 에 κΈ°λŒ€ν•œ λ…Έλ“œ IDκ°€ μ—†μŠ΅λ‹ˆλ‹€: {missing}. SPAO.json κ³Ό λ‹€λ₯Έ μ›Œν¬ν”Œλ‘œμš°λ₯Ό export ν–ˆλŠ”μ§€ ν™•μΈν•΄μ£Όμ„Έμš”."
142
+ raise ComfyError(_WORKFLOW_ERROR)
143
+ _WORKFLOW_TEMPLATE = wf
144
+ _WORKFLOW_ERROR = None
145
+ has_detail = all(nid in wf for nid in DETAIL_NODES.values())
146
+ print(f"[COMFY] Loaded workflow template {WORKFLOW_PATH} ({len(wf)} nodes, detail-cut slots: {'yes' if has_detail else 'no (v3 μ΄ν•˜)'})")
147
+ return wf
148
+
149
+
150
+ def supports_pose_text() -> bool:
151
+ try:
152
+ wf = load_workflow_template()
153
+ except ComfyError:
154
+ return False
155
+ return POSE_ANALYSIS_NODE in wf and POSE_FINAL_NODE in wf
156
+
157
+
158
+ def supports_detail_cuts() -> bool:
159
+ try:
160
+ wf = load_workflow_template()
161
+ except ComfyError:
162
+ return False
163
+ return all(nid in wf for nid in DETAIL_NODES.values())
164
+
165
+
166
+ def workflow_status() -> Dict[str, Any]:
167
+ try:
168
+ wf = load_workflow_template()
169
+ gpt = wf.get(GPT_IMAGE_NODE, {}).get("inputs", {})
170
+ wired = {f"image_{k}": (gpt.get(f"model.images.image_{k}") or [None])[0] for k in range(1, 15) if f"model.images.image_{k}" in gpt}
171
+ return {"ok": True, "nodes": len(wf), "path": WORKFLOW_PATH, "api_key": bool(API_KEY),
172
+ "detailCuts": all(nid in wf for nid in DETAIL_NODES.values()),
173
+ "poseText": POSE_ANALYSIS_NODE in wf and POSE_FINAL_NODE in wf,
174
+ "gptSlotsInExport": wired}
175
+ except ComfyError as e:
176
+ return {"ok": False, "error": str(e), "path": WORKFLOW_PATH, "api_key": bool(API_KEY)}
177
+
178
+
179
+ # ── 이미지 μ—…λ‘œλ“œ (λ‚΄μš© ν•΄μ‹œ μΊμ‹œ) ─────────────────────────────────────────────
180
+ _UPLOAD_CACHE: Dict[str, str] = {} # sha256 β†’ Comfy μ €μž₯μ†Œ 파일λͺ…
181
+ _UPLOAD_LOCK = threading.Lock()
182
+
183
+
184
+ def normalize_image_bytes(data: bytes, max_side: int = 2048) -> Tuple[bytes, str]:
185
+ """μ•ŒνŒŒ μ œκ±°Β·κ³ΌλŒ€ 이미지 μΆ•μ†Œ ν›„ (bytes, ext) λ°˜ν™˜. 동일 μž…λ ₯ β†’ 동일 λ°”μ΄νŠΈ (μΊμ‹œ μ•ˆμ •μ„±)."""
186
+ img = Image.open(io.BytesIO(data))
187
+ img.load()
188
+ if img.mode not in ("RGB", "L"):
189
+ bg = Image.new("RGB", img.size, (255, 255, 255))
190
+ if "A" in img.getbands():
191
+ bg.paste(img.convert("RGBA"), mask=img.convert("RGBA").split()[-1])
192
+ else:
193
+ bg.paste(img.convert("RGB"))
194
+ img = bg
195
+ elif img.mode == "L":
196
+ img = img.convert("RGB")
197
+ w, h = img.size
198
+ if max(w, h) > max_side:
199
+ s = max_side / max(w, h)
200
+ img = img.resize((max(1, int(w * s)), max(1, int(h * s))), Image.LANCZOS)
201
+ out = io.BytesIO()
202
+ img.save(out, format="PNG", compress_level=6)
203
+ return out.getvalue(), "png"
204
+
205
+
206
+ def ensure_uploaded(data: bytes, label: str = "") -> str:
207
+ """Comfy μ €μž₯μ†Œμ— 이미지가 μžˆλ„λ‘ 보μž₯ν•˜κ³  파일λͺ…을 λŒλ €μ€€λ‹€. 같은 λ°”μ΄νŠΈλŠ” ν•œ 번만 μ—…λ‘œλ“œ."""
208
+ norm, ext = normalize_image_bytes(data)
209
+ digest = hashlib.sha256(norm).hexdigest()
210
+ with _UPLOAD_LOCK:
211
+ cached = _UPLOAD_CACHE.get(digest)
212
+ if cached:
213
+ return cached
214
+ filename = f"{digest}.{ext}"
215
+ with httpx.Client(timeout=_HTTP_TIMEOUT) as client:
216
+ r = client.post(
217
+ f"{BASE_URL}/api/upload/image",
218
+ headers=_headers(json_ct=False),
219
+ files={"image": (filename, norm, "image/png")},
220
+ data={"type": "input", "overwrite": "true"},
221
+ )
222
+ if r.status_code >= 400:
223
+ raise ComfyError(f"이미지 μ—…λ‘œλ“œ μ‹€νŒ¨({label or filename}): HTTP {r.status_code} {r.text[:200]}")
224
+ name = r.json().get("name") or filename
225
+ with _UPLOAD_LOCK:
226
+ _UPLOAD_CACHE[digest] = name
227
+ print(f"[COMFY] uploaded {label or ''} β†’ {name} ({len(norm):,} bytes)")
228
+ return name
229
+
230
+
231
+ # 빈 슬둯용 흰색 1024x1024 PNG β€” λ°”μ΄νŠΈλ₯Ό μƒμˆ˜λ‘œ λ‚΄μž₯ν•΄ μ–΄λŠ ν™˜κ²½μ—μ„œλ“  같은 ν•΄μ‹œ 이름이 λ˜λ„λ‘ ν•œλ‹€.
232
+ # Comfy Cloud μ €μž₯μ†ŒλŠ” λ‚΄μš© ν•΄μ‹œ 파일λͺ…μœΌλ‘œ νŒŒμΌμ„ μ°ΎμœΌλ―€λ‘œ, 일반 이름(spao_blank_slot.png)은 μ‹€ν–‰ μ‹œ λͺ» μ°ΎλŠ”λ‹€.
233
+ _BLANK_SLOT_PNG_B64 = "iVBORw0KGgoAAAANSUhEUgAABAAAAAQACAIAAADwf7zUAAARiElEQVR42u3XMQEAAAjDMMC/5+EDEgn92kkKAAD4YSQAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAGAAJAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAYAAkAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAABgACQAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAGAAAAMAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAMAAAAAABgAAALhlAZ8nCv2Z0MRzAAAAAElFTkSuQmCC"
234
+ BLANK_SLOT_PNG = base64.b64decode(_BLANK_SLOT_PNG_B64)
235
+ BLANK_SLOT_NAME = hashlib.sha256(BLANK_SLOT_PNG).hexdigest() + ".png" # = c98a86e4558781ad0abe9c23ea463ac000cf38d25f2db7860e73661a1224ff46.png
236
+ _PLACEHOLDER_CACHE: Dict[str, bytes] = {}
237
+ _BLANK_UPLOADED = False
238
+
239
+
240
+ def ensure_blank_slot_uploaded() -> str:
241
+ """빈 슬둯 이미지λ₯Ό ν•΄μ‹œ 파일λͺ…μœΌλ‘œ μ—…λ‘œλ“œ(ν”„λ‘œμ„ΈμŠ€λ‹Ή 1회). μ›Œν¬ν”Œλ‘œμš° 기본값이 이 이름을 가리킨닀."""
242
+ global _BLANK_UPLOADED
243
+ if _BLANK_UPLOADED:
244
+ return BLANK_SLOT_NAME
245
+ with httpx.Client(timeout=_HTTP_TIMEOUT) as client:
246
+ r = client.post(f"{BASE_URL}/api/upload/image", headers=_headers(json_ct=False),
247
+ files={"image": (BLANK_SLOT_NAME, BLANK_SLOT_PNG, "image/png")},
248
+ data={"type": "input", "overwrite": "true"})
249
+ if r.status_code >= 400:
250
+ raise ComfyError(f"빈 슬둯 이미지 μ—…λ‘œλ“œ μ‹€νŒ¨: HTTP {r.status_code} {r.text[:200]}")
251
+ returned = r.json().get("name")
252
+ if returned and returned != BLANK_SLOT_NAME:
253
+ print(f"[COMFY] warning: blank slot uploaded as {returned} (expected {BLANK_SLOT_NAME})")
254
+ _BLANK_UPLOADED = True
255
+ print(f"[COMFY] blank slot image ready β†’ {returned or BLANK_SLOT_NAME}")
256
+ return returned or BLANK_SLOT_NAME
257
+
258
+
259
+ def placeholder_image_bytes(kind: str = "blank") -> bytes:
260
+ """λΉ„μ–΄ μžˆλŠ” 슬둯(μ•„μš°ν„°/μ΄λ„ˆ/벨트/포즈 λ―Έμ—…λ‘œλ“œ)용 흰색 이미지."""
261
+ if kind in _PLACEHOLDER_CACHE:
262
+ return _PLACEHOLDER_CACHE[kind]
263
+ size = (1024, 1024) if kind == "blank" else (1024, 1536)
264
+ img = Image.new("RGB", size, (255, 255, 255))
265
+ out = io.BytesIO()
266
+ img.save(out, format="PNG")
267
+ _PLACEHOLDER_CACHE[kind] = out.getvalue()
268
+ return _PLACEHOLDER_CACHE[kind]
269
+
270
+
271
+ # ── μ›Œν¬ν”Œλ‘œμš° 패치 ────────────────────────────────────────────────────────────
272
+ def _set_combo(wf: Dict[str, Any], node_id: str, options: List[str], label: str) -> None:
273
+ """CustomCombo λ…Έλ“œμ˜ choiceλ₯Ό λ°”κΎΈκ³ , κ·Έ λ…Έλ“œμ˜ STRING/INDEX 좜λ ₯을 μ“°λŠ”
274
+ λͺ¨λ“  μ†ŒλΉ„μž μž…λ ₯을 μƒμˆ˜λ‘œ μΉ˜ν™˜ν•œλ‹€ (λ°±μ—”λ“œ CustomCombo λ™μž‘μ— μ˜μ‘΄ν•˜μ§€ μ•Šλ„λ‘)."""
275
+ if label not in options:
276
+ raise ComfyError(f"'{label}' 은(λŠ”) ν—ˆμš©λœ μ˜΅μ…˜μ΄ μ•„λ‹™λ‹ˆλ‹€: {options}")
277
+ idx = options.index(label)
278
+ node = wf.get(node_id)
279
+ if node is not None:
280
+ node.setdefault("inputs", {})["choice"] = label
281
+ for other in wf.values():
282
+ for k, v in list(other.get("inputs", {}).items()):
283
+ if isinstance(v, list) and len(v) == 2 and str(v[0]) == node_id:
284
+ other["inputs"][k] = label if v[1] == 0 else idx
285
+
286
+
287
+ def build_workflow(image_names: Dict[str, str], combos: Dict[str, str], prompt: str,
288
+ details: Optional[List[Dict[str, str]]] = None,
289
+ has_pose: bool = False, pose_spec_override: Optional[str] = None) -> Dict[str, Any]:
290
+ """details: [{"name": <comfy filename>, "garment": "top", "kind": DETAIL_KIND_EN ν‚€}] μ΅œλŒ€ 4개 (μ•žμ—μ„œλΆ€ν„° image_9..12).
291
+ has_pose: 레퍼런슀 포즈 μ—…λ‘œλ“œ μ—¬λΆ€. pose_spec_override: μ‚¬μš©μžκ°€ 직접 μ“΄ 포즈 λ¬Έμž₯(있으면 GPT λΉ„μ „ 뢄석 λŒ€μ‹  μ‚¬μš©)."""
292
+ wf = copy.deepcopy(load_workflow_template())
293
+ details = [x for x in (details or []) if x.get("name")][:4]
294
+ if supports_pose_text():
295
+ override = (pose_spec_override or "").strip()
296
+ if not has_pose and not override:
297
+ # 포즈 μ—†μŒ: μ˜€λ²„λΌμ΄λ“œ 체인 제거 (μ΅œμ’… ν”„λ‘¬ν”„νŠΈλŠ” κΈ°μ‘΄ κ·ΈλŒ€λ‘œ)
298
+ wf[POSE_FINAL_NODE]["inputs"]["string_b"] = ""
299
+ for nid in (POSE_ANALYSIS_NODE, POSE_PREFIX_NODE, TEXT_LOG_NODES["pose_spec"]):
300
+ wf.pop(nid, None)
301
+ else:
302
+ if override:
303
+ # μ‚¬μš©μž λ¬Έμž₯으둜 λŒ€μ²΄: λΉ„μ „ 뢄석 λ…Έλ“œλŠ” μ‹€ν–‰ν•˜μ§€ μ•ŠμŒ
304
+ wf[POSE_PREFIX_NODE]["inputs"]["string_b"] = override
305
+ for nid in (POSE_ANALYSIS_NODE, TEXT_LOG_NODES["pose_spec"]):
306
+ wf.pop(nid, None)
307
+ # μƒ· κΈ°λ³Έ μžμ„Έ 문ꡬ μ™„ν™” (레퍼런슀 ν¬μ¦ˆκ°€ μš°μ„ ν•˜λ„λ‘)
308
+ shot = wf.get(SHOT_PROMPT_NODE, {}).get("inputs", {})
309
+ if isinstance(shot.get("prompts"), str):
310
+ for a, b in _SHOT_POSTURE_RELAX:
311
+ shot["prompts"] = shot["prompts"].replace(a, b)
312
+ if supports_detail_cuts():
313
+ gpt = wf[GPT_IMAGE_NODE]["inputs"]
314
+ notes = []
315
+ for i, key in enumerate(["detail1", "detail2", "detail3", "detail4"]):
316
+ slot = f"model.images.image_{DETAIL_SLOT_INDEX[key]}"
317
+ if i < len(details):
318
+ wf[DETAIL_NODES[key]]["inputs"]["image"] = details[i]["name"]
319
+ gpt[slot] = [DETAIL_NODES[key], 0]
320
+ notes.append(f"image {DETAIL_SLOT_INDEX[key]} = {DETAIL_GARMENT_EN.get(details[i].get('garment'), 'a provided garment')}: "
321
+ f"{DETAIL_KIND_EN.get(details[i].get('kind'), DETAIL_KIND_EN['texture'])}")
322
+ else:
323
+ gpt.pop(slot, None) # μ•ˆ μ“°λŠ” μŠ¬λ‘―μ€ GPT μž…λ ₯μ—μ„œ 제거
324
+ wf.pop(DETAIL_NODES[key], None) # 그리고 λ…Έλ“œ 자체λ₯Ό ν”„λ‘¬ν”„νŠΈμ—μ„œ 제거 (μ—°κ²° μ•ˆ 된 LoadImage λŠ” Cloud κ°€ νŒŒμΌμ„ λͺ» μ°Ύμ•„ μ‹€νŒ¨)
325
+ if notes:
326
+ prompt = (prompt or "").rstrip() + "\n\nDETAIL REFERENCES: " + "; ".join(notes) + "."
327
+ for key, node_id in IMAGE_NODES.items():
328
+ name = image_names.get(key)
329
+ if name:
330
+ wf[node_id]["inputs"]["image"] = name
331
+ for key, (node_id, options) in COMBO_NODES.items():
332
+ label = combos.get(key)
333
+ if label:
334
+ _set_combo(wf, node_id, options, label)
335
+ wf[PROMPT_NODE]["inputs"]["string_b"] = prompt or ""
336
+ for nid in SEED_NODES:
337
+ if nid in wf and "seed" in wf[nid]["inputs"]:
338
+ wf[nid]["inputs"]["seed"] = random.randint(0, 2**53)
339
+ return wf
340
+
341
+
342
+ # ── 제좜 / μƒνƒœ / λ‹€μš΄λ‘œλ“œ ────────────────────────────────────────────────────���
343
+ def submit(wf: Dict[str, Any]) -> str:
344
+ payload = {"prompt": wf, "extra_data": {"api_key_comfy_org": API_KEY}}
345
+ with httpx.Client(timeout=_HTTP_TIMEOUT) as client:
346
+ r = client.post(f"{BASE_URL}/api/prompt", headers=_headers(), json=payload)
347
+ if r.status_code >= 400:
348
+ detail = r.text[:400]
349
+ try:
350
+ j = r.json()
351
+ errs = j.get("node_errors") or j.get("error")
352
+ if errs:
353
+ detail = json.dumps(errs, ensure_ascii=False)[:600]
354
+ except Exception:
355
+ pass
356
+ hint = {401: "API ν‚€κ°€ 잘λͺ»λ˜μ—ˆμŠ΅λ‹ˆλ‹€.", 402: "Comfy ν¬λ ˆλ”§μ΄ λΆ€μ‘±ν•©λ‹ˆλ‹€.", 429: "Comfy Cloud ꡬ독이 λΉ„ν™œμ„±μž…λ‹ˆλ‹€."}.get(r.status_code, "")
357
+ raise ComfyError(f"μ›Œν¬ν”Œλ‘œμš° 제좜 μ‹€νŒ¨ (HTTP {r.status_code}) {hint} {detail}")
358
+ j = r.json()
359
+ if j.get("error"):
360
+ raise ComfyError(f"μ›Œν¬ν”Œλ‘œμš° 검증 였λ₯˜: {json.dumps(j.get('node_errors') or j['error'], ensure_ascii=False)[:600]}")
361
+ return j["prompt_id"]
362
+
363
+
364
+ def job_status(prompt_id: str) -> str:
365
+ with httpx.Client(timeout=_HTTP_TIMEOUT) as client:
366
+ r = client.get(f"{BASE_URL}/api/job/{prompt_id}/status", headers=_headers())
367
+ if r.status_code >= 400:
368
+ raise ComfyError(f"μƒνƒœ 쑰회 μ‹€νŒ¨: HTTP {r.status_code} {r.text[:200]}")
369
+ return str(r.json().get("status", ""))
370
+
371
+
372
+ def _find_image_refs(obj: Any, acc: List[Dict[str, Any]]) -> None:
373
+ """응닡 JSON 어디에 μžˆλ“  {filename, subfolder, type} ν˜•νƒœμ˜ 이미지 μ°Έμ‘°λ₯Ό μˆ˜μ§‘."""
374
+ if isinstance(obj, dict):
375
+ if "filename" in obj and isinstance(obj["filename"], str):
376
+ acc.append(obj)
377
+ for v in obj.values():
378
+ _find_image_refs(v, acc)
379
+ elif isinstance(obj, list):
380
+ for v in obj:
381
+ _find_image_refs(v, acc)
382
+
383
+
384
+ def _refs_from_outputs(outputs: Any) -> List[Dict[str, Any]]:
385
+ """ComfyUI outputs 객체({node_id: {images: [...]}})μ—μ„œ SaveImage(760) 이미지 μš°μ„  μΆ”μΆœ."""
386
+ if not isinstance(outputs, dict):
387
+ return []
388
+ refs: List[Dict[str, Any]] = []
389
+ if isinstance(outputs.get(OUTPUT_NODE), dict):
390
+ _find_image_refs(outputs[OUTPUT_NODE], refs)
391
+ if not refs:
392
+ _find_image_refs(outputs, refs)
393
+ return [x for x in refs if x.get("type", "output") == "output"]
394
+
395
+
396
+ _LAST_OUTPUTS: Dict[str, Any] = {} # prompt_id β†’ 원본 outputs 객체 (ν…μŠ€νŠΈ 둜그 μΆ”μΆœμš©)
397
+
398
+
399
+ def _extract_texts(outputs: Any) -> Dict[str, str]:
400
+ """PreviewAny λ…Έλ“œ 좜λ ₯({node: {"text": [...]}})μ—μ„œ 둜그용 ν…μŠ€νŠΈλ₯Ό λ½‘λŠ”λ‹€."""
401
+ texts: Dict[str, str] = {}
402
+ if not isinstance(outputs, dict):
403
+ return texts
404
+ for key, nid in TEXT_LOG_NODES.items():
405
+ node_out = outputs.get(nid)
406
+ if isinstance(node_out, dict):
407
+ val = node_out.get("text") or node_out.get("string") or node_out.get("value")
408
+ if isinstance(val, list):
409
+ val = "\n".join(str(x) for x in val)
410
+ if val:
411
+ texts[key] = str(val)
412
+ return texts
413
+
414
+
415
+ def job_texts(prompt_id: str) -> Dict[str, str]:
416
+ return _extract_texts(_LAST_OUTPUTS.get(prompt_id))
417
+
418
+
419
+ def _find_error_dicts(obj: Any, acc: List[Dict[str, Any]], depth: int = 0) -> None:
420
+ if depth > 8:
421
+ return
422
+ if isinstance(obj, dict):
423
+ if any(k in obj for k in ("exception_message", "exception_type", "execution_error", "error_message")):
424
+ acc.append(obj)
425
+ for v in obj.values():
426
+ _find_error_dicts(v, acc, depth + 1)
427
+ elif isinstance(obj, list):
428
+ for v in obj:
429
+ _find_error_dicts(v, acc, depth + 1)
430
+
431
+
432
+ def job_error_detail(prompt_id: str) -> str:
433
+ """μ‹€νŒ¨ν•œ μž‘μ—…μ˜ λ…Έλ“œ/μ˜ˆμ™Έ λ©”μ‹œμ§€λ₯Ό /api/jobs/{id} μ—μ„œ μ°Ύμ•„ μ‚¬λžŒμ΄ 읽을 수 μžˆλŠ” ν•œ μ€„λ‘œ."""
434
+ try:
435
+ with httpx.Client(timeout=_HTTP_TIMEOUT) as client:
436
+ r = client.get(f"{BASE_URL}/api/jobs/{prompt_id}", headers=_headers())
437
+ if r.status_code >= 400:
438
+ return f"(상세 쑰회 μ‹€νŒ¨: HTTP {r.status_code})"
439
+ data = r.json()
440
+ except Exception as e: # noqa: BLE001
441
+ return f"(상세 쑰회 μ‹€νŒ¨: {e})"
442
+ found: List[Dict[str, Any]] = []
443
+ _find_error_dicts(data, found)
444
+ parts: List[str] = []
445
+ for d in found:
446
+ ex = d.get("execution_error") if isinstance(d.get("execution_error"), dict) else d
447
+ node = ex.get("node_type") or ex.get("class_type") or ""
448
+ nid = ex.get("node_id") or ""
449
+ msg = ex.get("exception_message") or ex.get("error_message") or ex.get("message") or ""
450
+ etype = ex.get("exception_type") or ""
451
+ line = " ".join(x for x in [f"{node}#{nid}" if (node or nid) else "", etype, str(msg)[:300]] if x)
452
+ if line and line not in parts:
453
+ parts.append(line)
454
+ if not parts:
455
+ # μ΅œν›„ μˆ˜λ‹¨: λ¬Έμžμ—΄ ν•„λ“œ 쀑 error λΉ„μŠ·ν•œ 것
456
+ for k in ("error", "status_message", "message"):
457
+ v = data.get(k) if isinstance(data, dict) else None
458
+ if isinstance(v, str) and v:
459
+ parts.append(v[:300])
460
+ print(f"[COMFY] job {prompt_id} failed; detail keys={list(data.keys())[:15] if isinstance(data, dict) else type(data)}")
461
+ return " | ".join(parts) if parts else "(Comfyκ°€ 상세 λ©”μ‹œμ§€λ₯Ό μ œκ³΅ν•˜μ§€ μ•ŠμŒ β€” Comfy Cloud ν™”λ©΄μ˜ μ‹€ν–‰ κΈ°λ‘μ—μ„œ 확인)"
462
+
463
+
464
+ def job_outputs(prompt_id: str, attempts: int = 5, delay: float = 2.0) -> List[Dict[str, Any]]:
465
+ """μ™„λ£Œλœ μž‘μ—…μ˜ 좜λ ₯ 파일 λͺ©λ‘.
466
+ /api/jobs/{id} 의 outputs β†’ legacy history 순으둜 확인. 'workflow'/'prompt' ν•„λ“œ μ•ˆμ˜
467
+ λ…Έλ“œ μ •μ˜(같은 λ…Έλ“œ IDλ₯Ό 가짐)λŠ” μ ˆλŒ€ νƒμƒ‰ν•˜μ§€ μ•ŠλŠ”λ‹€. μƒνƒœκ°€ success 둜 바뀐 직후
468
+ outputs κ°€ 아직 λΉ„μ–΄ μžˆμ„ 수 μžˆμ–΄ λͺ‡ 번 μž¬μ‹œλ„ν•œλ‹€."""
469
+ last_debug = ""
470
+ with httpx.Client(timeout=_HTTP_TIMEOUT) as client:
471
+ for attempt in range(attempts):
472
+ for url in (f"{BASE_URL}/api/jobs/{prompt_id}",
473
+ f"{BASE_URL}/api/history_v2/{prompt_id}",
474
+ f"{BASE_URL}/api/history/{prompt_id}"):
475
+ try:
476
+ r = client.get(url, headers=_headers())
477
+ except Exception as e: # noqa: BLE001
478
+ last_debug = f"{url}: {e}"
479
+ continue
480
+ if r.status_code >= 400:
481
+ last_debug = f"{url}: HTTP {r.status_code} {r.text[:120]}"
482
+ continue
483
+ try:
484
+ data = r.json()
485
+ except Exception:
486
+ continue
487
+ candidates = []
488
+ if isinstance(data, dict):
489
+ candidates.append(data.get("outputs")) # /api/jobs
490
+ if isinstance(data.get(prompt_id), dict): # /api/history
491
+ candidates.append(data[prompt_id].get("outputs"))
492
+ for v in data.values(): # 기타 λž˜ν•‘
493
+ if isinstance(v, dict) and isinstance(v.get("outputs"), dict):
494
+ candidates.append(v["outputs"])
495
+ for c in candidates:
496
+ refs = _refs_from_outputs(c)
497
+ if refs:
498
+ _LAST_OUTPUTS[prompt_id] = c
499
+ return refs
500
+ if isinstance(data, dict):
501
+ last_debug = f"{url}: keys={list(data.keys())[:12]} outputs_count={data.get('outputs_count')}"
502
+ time.sleep(delay)
503
+ print(f"[COMFY] no outputs for {prompt_id}: {last_debug}")
504
+ return []
505
+
506
+
507
+ def download_output(ref: Dict[str, Any]) -> bytes:
508
+ params = {"filename": ref["filename"], "subfolder": ref.get("subfolder", ""), "type": ref.get("type", "output")}
509
+ with httpx.Client(timeout=_HTTP_TIMEOUT, follow_redirects=False) as client:
510
+ r = client.get(f"{BASE_URL}/api/view", headers=_headers(json_ct=False), params=params)
511
+ if r.status_code in (301, 302, 303, 307, 308):
512
+ signed = r.headers.get("location")
513
+ r2 = client.get(signed, follow_redirects=True) # signed URL: 헀더 없이
514
+ r2.raise_for_status()
515
+ return r2.content
516
+ if r.status_code == 200:
517
+ return r.content
518
+ raise ComfyError(f"좜λ ₯ λ‹€μš΄λ‘œλ“œ μ‹€νŒ¨: HTTP {r.status_code}")
519
+
520
+
521
+ def cancel(prompt_id: str) -> str:
522
+ """μ‹€ν–‰ 쀑/λŒ€κΈ° 쀑 μž‘μ—… μ·¨μ†Œ μš”μ²­. λ°°ν¬λ³„λ‘œ μ—”λ“œν¬μΈνŠΈκ°€ 달라 μˆœμ„œλŒ€λ‘œ μ‹œλ„ν•˜κ³ , 수락된 URL을 λ°˜ν™˜."""
523
+ attempts = [
524
+ ("POST", f"{BASE_URL}/api/job/{prompt_id}/cancel", None),
525
+ ("POST", f"{BASE_URL}/api/jobs/{prompt_id}/cancel", None),
526
+ ("POST", f"{BASE_URL}/api/interrupt", {"prompt_id": prompt_id}),
527
+ ("POST", f"{BASE_URL}/api/queue", {"delete": [prompt_id]}),
528
+ ]
529
+ last_err = ""
530
+ with httpx.Client(timeout=_HTTP_TIMEOUT) as client:
531
+ for method, url, body in attempts:
532
+ try:
533
+ r = client.request(method, url, headers=_headers(), json=body)
534
+ if r.status_code < 300:
535
+ return url
536
+ last_err = f"{url} β†’ HTTP {r.status_code}"
537
+ except Exception as e: # noqa: BLE001
538
+ last_err = f"{url} β†’ {e}"
539
+ raise ComfyError(f"μ·¨μ†Œ μš”μ²­μ΄ μˆ˜λ½λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€ ({last_err})")
540
+
541
+
542
+ class CancelledByUser(ComfyError):
543
+ pass
544
+
545
+
546
+ def wait_for_result(prompt_id: str, timeout_sec: int = 1200, interval: float = 3.0,
547
+ on_status=None, should_stop=None) -> bytes:
548
+ """터미널 μƒνƒœκΉŒμ§€ 폴링 ν›„ 첫 좜λ ₯ 이미지 bytes λ°˜ν™˜. should_stop() 이 True λ©΄ μ¦‰μ‹œ 쀑단."""
549
+ start = time.time()
550
+ last = ""
551
+ while time.time() - start < timeout_sec:
552
+ if should_stop and should_stop():
553
+ raise CancelledByUser("μ‚¬μš©μžκ°€ μž‘μ—…μ„ μ·¨μ†Œν–ˆμŠ΅λ‹ˆλ‹€.")
554
+ st = job_status(prompt_id)
555
+ if st != last and on_status:
556
+ on_status(st)
557
+ last = st
558
+ if st in TERMINAL_OK:
559
+ refs = job_outputs(prompt_id)
560
+ if not refs:
561
+ raise ComfyError("μž‘μ—…μ€ μ„±κ³΅ν–ˆμ§€λ§Œ 좜λ ₯ 이미지λ₯Ό μ°Ύμ§€ λͺ»ν–ˆμŠ΅λ‹ˆλ‹€ (SaveImage λ…Έλ“œ 760 확인).")
562
+ return download_output(refs[0])
563
+ if st in TERMINAL_FAIL:
564
+ raise ComfyError(f"Comfy Cloud μž‘μ—… μ‹€νŒ¨({st}): {job_error_detail(prompt_id)}")
565
+ time.sleep(interval)
566
+ raise ComfyError(f"{timeout_sec}초 내에 μž‘μ—…μ΄ λλ‚˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
comfy_routes (20).py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ comfy_routes.py β€” HF Space(FastAPI) ↔ Comfy Cloud λΈŒλ¦¬μ§€ λΌμš°ν„°
3
+
4
+ POST /api/comfy/generate β†’ μ¦‰μ‹œ {jobId} λ°˜ν™˜, λ°±κ·ΈλΌμš΄λ“œμ—μ„œ μ—…λ‘œλ“œβ†’μ œμΆœβ†’ν΄λ§β†’λ‹€μš΄λ‘œλ“œ
5
+ GET /api/comfy/jobs/{jobId} β†’ {status, stage, imageUrl?, error?, elapsedSec}
6
+ GET /api/comfy/jobs β†’ ν˜„μž¬ μ‚¬μš©μž(둜그인 계정 λ˜λŠ” X-Client-Id)의 μž‘μ—… λͺ©λ‘ (μƒˆλ‘œκ³ μΉ¨ 볡ꡬ용)
7
+ GET /api/comfy/health β†’ μ›Œν¬ν”Œλ‘œμš° 파일/API ν‚€ μƒνƒœ
8
+
9
+ server.py μ—μ„œ:
10
+ from comfy_routes import build_comfy_router
11
+ app.include_router(build_comfy_router(get_current_user, require_login, _FACE_PRESET_CACHE, _push_to_hub_background))
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import base64
16
+ import datetime
17
+ import os
18
+ import re
19
+ import threading
20
+ import time
21
+ import traceback
22
+ import uuid
23
+ from typing import Any, Callable, Dict, Optional
24
+
25
+ from fastapi import APIRouter, Body, HTTPException, Request
26
+
27
+ import comfy_client as cc
28
+
29
+ _JOBS: Dict[str, Dict[str, Any]] = {}
30
+ _JOBS_LOCK = threading.Lock()
31
+ _JOB_TTL_SEC = int(os.environ.get("COMFY_JOB_TTL_SEC", str(6 * 60 * 60))) # μ™„λ£Œ/μ‹€νŒ¨ μž‘μ—… 보관 μ‹œκ°„ (κΈ°λ³Έ 6μ‹œκ°„)
32
+ _MAX_CONCURRENT = int(os.environ.get("COMFY_MAX_CONCURRENT", "2"))
33
+ _SEM = threading.Semaphore(_MAX_CONCURRENT)
34
+
35
+ STAGE_LABEL = {
36
+ "queued_local": "λŒ€κΈ° 쀑",
37
+ "uploading": "이미지 μ—…λ‘œλ“œ 쀑",
38
+ "submitting": "μ›Œν¬ν”Œλ‘œμš° 제좜 쀑",
39
+ "submitted": "제좜됨",
40
+ "queued_waiting": "Comfy λŒ€κΈ°μ—΄",
41
+ "queued_limited": "Comfy λŒ€κΈ°μ—΄ (λ™μ‹œ μ‹€ν–‰ μ œν•œ)",
42
+ "preparing": "GPU μ€€λΉ„ 쀑",
43
+ "executing": "생성 쀑",
44
+ "downloading": "κ²°κ³Ό λ‹€μš΄λ‘œλ“œ 쀑",
45
+ "done": "μ™„λ£Œ",
46
+ "error": "였λ₯˜",
47
+ "cancelling": "μ·¨μ†Œ 쀑",
48
+ "cancelled": "μ·¨μ†Œλ¨",
49
+ }
50
+
51
+
52
+ def _parse_data_url(data_url: Optional[str]) -> Optional[bytes]:
53
+ if not data_url or not isinstance(data_url, str):
54
+ return None
55
+ if data_url.startswith("data:") and ";base64," in data_url:
56
+ return base64.b64decode(data_url.split(";base64,", 1)[1])
57
+ return None
58
+
59
+
60
+ def _safe_name(name: Optional[str], fallback: str) -> str:
61
+ """원본 파일λͺ…은 μ΅œλŒ€ν•œ μœ μ§€ν•˜λ˜ HF κ²½λ‘œμ— μ•ˆμ „ν•˜κ²Œ (server._sanitize_upload_filename κ³Ό 동일 κ·œμΉ™)."""
62
+ raw = (name or "").strip() if isinstance(name, str) else ""
63
+ base = os.path.basename(raw.replace("\\", "/")) if raw else ""
64
+ if not base or base in (".", ".."):
65
+ return fallback
66
+ cleaned = re.sub(r"[^\w.\-κ°€-힣]+", "_", base, flags=re.UNICODE).strip("._") or fallback
67
+ cleaned = cleaned.replace("..", "_")
68
+ if len(cleaned) > 120:
69
+ stem, ext = os.path.splitext(cleaned)
70
+ cleaned = stem[:100] + ext[:20]
71
+ return cleaned
72
+
73
+
74
+ def _update(job_id: str, **kw) -> None:
75
+ with _JOBS_LOCK:
76
+ if job_id in _JOBS:
77
+ _JOBS[job_id].update(kw)
78
+
79
+
80
+ def _gc_jobs() -> None:
81
+ now = time.time()
82
+ with _JOBS_LOCK:
83
+ for jid in [j for j, v in _JOBS.items() if v.get("finished_at") and now - v["finished_at"] > _JOB_TTL_SEC]:
84
+ _JOBS.pop(jid, None)
85
+
86
+
87
+ def build_comfy_router(
88
+ get_current_user: Callable[[Request], dict],
89
+ require_login: Callable[[dict], None],
90
+ face_preset_cache: Dict[str, dict],
91
+ push_to_hub_background: Optional[Callable] = None,
92
+ ) -> APIRouter:
93
+ router = APIRouter(prefix="/api/comfy")
94
+
95
+ def _run_pipeline(job_id: str, payload: dict, user: dict) -> None:
96
+ started = time.time()
97
+ with _SEM:
98
+ try:
99
+ uploads = payload.get("images") or {}
100
+ combos = {k: v for k, v in (payload.get("options") or {}).items() if v}
101
+ if not uploads.get("pose") and combos.get("shot") == "레퍼런슀 ꡬ도 κ·ΈλŒ€λ‘œ":
102
+ raise cc.ComfyError("'레퍼런슀 ꡬ도 κ·ΈλŒ€λ‘œ'λ₯Ό μ„ νƒν•˜λ©΄ 레퍼런슀 포즈 이미지가 ν•„μš”ν•©λ‹ˆλ‹€.")
103
+ if not any(_parse_data_url(uploads.get(k)) for k in ("outer", "top", "bottom")):
104
+ raise cc.ComfyError("μ•„μš°ν„°Β·μƒμ˜Β·ν•˜μ˜ 쀑 μ΅œμ†Œ ν•œ 개의 μ˜μƒ 이미지가 ν•„μš”ν•©λ‹ˆλ‹€.")
105
+
106
+ _update(job_id, stage="uploading")
107
+ images: Dict[str, str] = {}
108
+
109
+ # ── μ–Όκ΅΄: 프리셋 id λ˜λŠ” μ—…λ‘œλ“œ data URL ──
110
+ face = payload.get("face")
111
+ face_bytes: Optional[bytes] = None
112
+ if isinstance(face, str) and face.startswith("preset_") and face in face_preset_cache:
113
+ face_bytes = base64.b64decode(face_preset_cache[face]["data"])
114
+ else:
115
+ face_bytes = _parse_data_url(face)
116
+ if not face_bytes:
117
+ raise cc.ComfyError("μ–Όκ΅΄ 프리셋을 μ„ νƒν•˜κ±°λ‚˜ μ–Όκ΅΄ 이미지λ₯Ό μ—…λ‘œλ“œν•΄μ£Όμ„Έμš”.")
118
+ images["face"] = cc.ensure_uploaded(face_bytes, "face")
119
+
120
+ # ── μ˜μƒ/λ°°κ²½/포즈 슬둯 ──
121
+ for key in ["outer", "top", "bottom", "shoes", "inner", "belt", "pose"]:
122
+ b = _parse_data_url(uploads.get(key))
123
+ images[key] = cc.ensure_uploaded(b, key) if b else cc.ensure_uploaded(cc.placeholder_image_bytes("blank"), f"{key}-empty")
124
+ # λ””ν…ŒμΌ μ°Έμ‘°(쑰직감/둜고): μ΅œλŒ€ 4μž₯, v5 μ›Œν¬ν”Œλ‘œμš°μΌ λ•Œλ§Œ (μ•„λ‹ˆλ©΄ 쑰용히 λ¬΄μ‹œ)
125
+ details_in = payload.get("details") if isinstance(payload.get("details"), list) else []
126
+ details: list = []
127
+ if cc.supports_detail_cuts():
128
+ for item in details_in[:4]:
129
+ if not isinstance(item, dict):
130
+ continue
131
+ b = _parse_data_url(item.get("image"))
132
+ if not b or not uploads.get(item.get("garment")):
133
+ continue # μ£Όμ»· μ—†λŠ” μ˜μƒμ˜ λ””ν…ŒμΌμ€ λ¬΄μ‹œ
134
+ details.append({"name": cc.ensure_uploaded(b, f"detail:{item.get('garment')}:{item.get('kind')}"),
135
+ "garment": item.get("garment"), "kind": item.get("kind") or "texture",
136
+ "image": item.get("image"), "filename": item.get("filename")})
137
+ detail_count = len(details)
138
+ bg = _parse_data_url(uploads.get("background"))
139
+ if not bg and os.path.exists("background.png"):
140
+ with open("background.png", "rb") as f:
141
+ bg = f.read()
142
+ images["background"] = cc.ensure_uploaded(bg, "background") if bg else cc.ensure_uploaded(cc.placeholder_image_bytes("studio"), "background-empty")
143
+ images["_blank"] = cc.ensure_blank_slot_uploaded()
144
+
145
+ prompt = (payload.get("prompt") or "").strip()
146
+
147
+ _update(job_id, stage="submitting")
148
+ pose_spec_override = (payload.get("poseSpec") or "").strip()[:1200] if isinstance(payload.get("poseSpec"), str) else ""
149
+ wf = cc.build_workflow(images, combos, prompt, details,
150
+ has_pose=bool(uploads.get("pose")), pose_spec_override=pose_spec_override)
151
+ prompt_id = cc.submit(wf)
152
+ _update(job_id, stage="submitted", promptId=prompt_id)
153
+ print(f"[COMFY] job {job_id} β†’ prompt_id {prompt_id} (user={user.get('username')})")
154
+
155
+ def on_status(st: str) -> None:
156
+ patch = {"stage": st if st in STAGE_LABEL else "executing", "comfyStatus": st}
157
+ with _JOBS_LOCK:
158
+ started = _JOBS.get(job_id, {}).get("exec_started_at")
159
+ # μ‹€μ œ μ›Œν¬ν”Œλ‘œμš° 싀행이 μ‹œμž‘λœ μ‹œμ (λŒ€κΈ°μ—΄Β·GPU μ€€λΉ„ μ œμ™Έ)λΆ€ν„° μ†Œμš”μ‹œκ°„μ„ μž°λ‹€
160
+ if st not in ("submitted", "queued_waiting", "queued_limited", "preparing") and not started:
161
+ patch["exec_started_at"] = time.time()
162
+ _update(job_id, **patch)
163
+
164
+ def cancelled() -> bool:
165
+ with _JOBS_LOCK:
166
+ return bool(_JOBS.get(job_id, {}).get("cancelRequested"))
167
+
168
+ img_bytes = cc.wait_for_result(prompt_id, on_status=on_status, should_stop=cancelled)
169
+ texts = cc.job_texts(prompt_id) # v6~: μ˜μƒ 뢄석 κ²°κ³Ό / μ΅œμ’… ν”„λ‘¬ν”„νŠΈ
170
+ if texts.get("garment_specs"):
171
+ print(f"[COMFY] job {job_id} garment specs: {texts['garment_specs'][:300]}")
172
+ _update(job_id, stage="downloading", garmentSpecs=texts.get("garment_specs"), finalPrompt=texts.get("final_prompt"),
173
+ poseSpec=texts.get("pose_spec") or (pose_spec_override or None))
174
+ b64 = base64.b64encode(img_bytes).decode("utf-8")
175
+ data_url = f"data:image/png;base64,{b64}"
176
+ with _JOBS_LOCK:
177
+ exec_started = _JOBS.get(job_id, {}).get("exec_started_at") or started
178
+ elapsed = round(time.time() - exec_started, 1) # 순수 생성 μ‹œκ°„
179
+ waited = round(exec_started - started, 1) # μ—…λ‘œλ“œ+λŒ€κΈ°μ—΄ μ‹œκ°„
180
+ _update(job_id, waitedSec=waited)
181
+ _update(job_id, status="done", stage="done", imageUrl=data_url, elapsedSec=elapsed, finished_at=time.time())
182
+ print(f"[COMFY] job {job_id} done in {elapsed}s ({len(img_bytes):,} bytes)")
183
+
184
+ # ── HF Dataset 기둝 (κΈ°μ‘΄ 둜직 μž¬μ‚¬μš©, μ‹€νŒ¨ν•΄λ„ λ¬΄μ‹œ) ──
185
+ if push_to_hub_background:
186
+ try:
187
+ now = datetime.datetime.now()
188
+ ts = now.strftime("%Y%m%d_%H%M%S_%f")[:-3]
189
+ names = payload.get("imageFilenames") if isinstance(payload.get("imageFilenames"), dict) else {}
190
+ garment_keys = ["outer", "top", "bottom", "shoes", "inner", "belt"]
191
+ present = [k for k in garment_keys if uploads.get(k)]
192
+ product_b64 = [uploads[k] for k in present] + [x["image"] for x in details]
193
+ product_names = [_safe_name(names.get(k), f"{k}.png") for k in present] + \
194
+ [_safe_name(x.get("filename"), f"{x['garment']}_{x['kind']}.png") for x in details]
195
+ ref_keys = [k for k in ("background", "pose") if uploads.get(k)]
196
+ ref_b64 = [uploads[k] for k in ref_keys]
197
+ ref_names = [_safe_name(names.get(k), f"{k}.png") for k in ref_keys]
198
+ is_preset = isinstance(face, str) and face.startswith("preset_")
199
+ face_filename = f"{face}.png" if is_preset else _safe_name(payload.get("faceFilename"), "face_upload.png")
200
+ push_to_hub_background(
201
+ record={
202
+ "timestamp": now.strftime("%Y-%m-%d %H:%M:%S"), "ts": ts,
203
+ "app": "clovis-comfy-lookbook", "engine": "comfy-cloud",
204
+ "shot_label": combos.get("shot", ""), "camera_angle": combos.get("angle", ""),
205
+ "gaze": combos.get("gaze", ""), "age_group": combos.get("age", ""),
206
+ "user_username": user.get("username"), "user_name": user.get("name"),
207
+ "user_email": user.get("email"), "user_logged_in": user.get("is_logged_in"),
208
+ "custom_prompt": prompt or "(none)", "comfy_prompt_id": prompt_id, "mode": "COMFY",
209
+ "model_face": face if is_preset else "user_upload", "model_face_filename": face_filename,
210
+ "has_reference": bool(uploads.get("pose")), "has_background": bool(uploads.get("background")),
211
+ "elapsed_sec": elapsed, "elapsed_ms": int(elapsed * 1000), "waited_sec": waited,
212
+ "product_image_filenames": product_names,
213
+ "slot_filenames": {k: _safe_name(names.get(k), f"{k}.png") for k in present + ref_keys},
214
+ "options": combos, "detail_refs": [{"garment": x["garment"], "kind": x["kind"]} for x in details],
215
+ "garment_specs": texts.get("garment_specs"), "final_prompt": texts.get("final_prompt"),
216
+ "pose_spec": texts.get("pose_spec") or (pose_spec_override or None),
217
+ "pose_spec_source": "user" if pose_spec_override else ("vision" if texts.get("pose_spec") else None),
218
+ },
219
+ image_bytes=img_bytes, ts=ts,
220
+ product_images_b64=product_b64, product_filenames=product_names,
221
+ face_b64=base64.b64encode(face_bytes).decode("utf-8"), face_filename=face_filename,
222
+ sub_product_images_b64=ref_b64, sub_product_filenames=ref_names,
223
+ )
224
+ except Exception as hub_err:
225
+ print(f"[HUB] comfy push failed: {hub_err}")
226
+ except cc.CancelledByUser:
227
+ print(f"[COMFY] job {job_id} cancelled by user")
228
+ _update(job_id, status="cancelled", stage="cancelled", finished_at=time.time())
229
+ except cc.ComfyError as e:
230
+ with _JOBS_LOCK:
231
+ was_cancel = bool(_JOBS.get(job_id, {}).get("cancelRequested"))
232
+ if was_cancel: # μ·¨μ†Œ μš”μ²­ ν›„ Comfy μͺ½μ—μ„œ cancelled 둜 λλ‚œ κ²½μš°λ„ μ·¨μ†Œλ‘œ 처리
233
+ print(f"[COMFY] job {job_id} cancelled (comfy: {e})")
234
+ _update(job_id, status="cancelled", stage="cancelled", finished_at=time.time())
235
+ else:
236
+ print(f"[COMFY] job {job_id} error: {e}")
237
+ _update(job_id, status="error", stage="error", error=str(e), finished_at=time.time())
238
+ except Exception as e: # noqa: BLE001
239
+ traceback.print_exc()
240
+ _update(job_id, status="error", stage="error", error=f"예기치 λͺ»ν•œ 였λ₯˜: {str(e)[:200]}", finished_at=time.time())
241
+
242
+ def _prewarm() -> None:
243
+ """μ„œλ²„ μ‹œμž‘ μ‹œ μ–Όκ΅΄ 프리셋·기본 배경·빈 슬둯 이미지λ₯Ό 미리 올렀 첫 μš”μ²­μ„ λΉ λ₯΄κ²Œ."""
244
+ try:
245
+ for pid, v in list(face_preset_cache.items()):
246
+ cc.ensure_uploaded(base64.b64decode(v["data"]), f"preset:{pid}")
247
+ if os.path.exists("background.png"):
248
+ with open("background.png", "rb") as f:
249
+ cc.ensure_uploaded(f.read(), "background")
250
+ cc.ensure_uploaded(cc.placeholder_image_bytes("blank"), "empty-slot")
251
+ cc.ensure_blank_slot_uploaded()
252
+ print("[COMFY] prewarm done")
253
+ except Exception as e: # noqa: BLE001
254
+ print(f"[COMFY] prewarm skipped: {e}")
255
+
256
+ if cc.API_KEY and os.environ.get("COMFY_PREWARM", "true").lower() in ("1", "true", "yes", "on"):
257
+ threading.Thread(target=_prewarm, daemon=True).start()
258
+
259
+ @router.get("/health")
260
+ def comfy_health(request: Request):
261
+ st = cc.workflow_status()
262
+ user = get_current_user(request)
263
+ st["oauthAttached"] = bool(user.get("is_logged_in")) or _oauth_attached()
264
+ st["loginRequired"] = _login_required()
265
+ return st
266
+
267
+ def _oauth_attached() -> bool:
268
+ try:
269
+ import server # noqa: WPS433 β€” λŸ°νƒ€μž„ μƒνƒœ 쑰회
270
+ return bool(getattr(server, "_OAUTH_ATTACHED", False))
271
+ except Exception:
272
+ return False
273
+
274
+ def _login_required() -> bool:
275
+ try:
276
+ import server
277
+ return bool(getattr(server, "REQUIRE_LOGIN", True) and getattr(server, "_OAUTH_ATTACHED", False))
278
+ except Exception:
279
+ return False
280
+
281
+ def _owner_of(request: Request, user: dict) -> str:
282
+ """둜그인 μ‚¬μš©μžλŠ” 계정λͺ…, λΉ„λ‘œκ·ΈμΈμ€ λΈŒλΌμš°μ €κ°€ λ³΄λ‚΄λŠ” X-Client-Id 둜 μž‘μ—… μ†Œμœ μžλ₯Ό 식별."""
283
+ if user.get("is_logged_in") and user.get("username"):
284
+ return f"user:{user['username']}"
285
+ cid = (request.headers.get("x-client-id") or "").strip()[:64]
286
+ return f"client:{cid}" if cid else "anonymous"
287
+
288
+ def _job_view(job_id: str, snap: Dict[str, Any], with_image: bool = True) -> Dict[str, Any]:
289
+ stage = snap.get("stage", "")
290
+ return {
291
+ "id": job_id,
292
+ "status": snap.get("status"),
293
+ "stage": stage,
294
+ "stageLabel": STAGE_LABEL.get(stage, stage),
295
+ "createdAt": int(snap["created_at"] * 1000),
296
+ # elapsedSec: μ›Œν¬ν”Œλ‘œμš° μ‹€ν–‰ μ‹œμž‘ 이후 κ²½κ³Ό(λŒ€κΈ° 쀑이면 null). μ™„λ£Œ μ‹œμ—” 순수 생성 μ‹œκ°„.
297
+ "elapsedSec": snap.get("elapsedSec") if snap.get("status") == "done"
298
+ else (round(time.time() - snap["exec_started_at"], 1) if snap.get("exec_started_at") else None),
299
+ "execStartedAt": int(snap["exec_started_at"] * 1000) if snap.get("exec_started_at") else None,
300
+ "waitedSec": snap.get("waitedSec"),
301
+ "meta": snap.get("meta") or {},
302
+ "imageUrl": snap.get("imageUrl") if with_image else None,
303
+ "garmentSpecs": snap.get("garmentSpecs"),
304
+ "finalPrompt": snap.get("finalPrompt"),
305
+ "poseSpec": snap.get("poseSpec"),
306
+ "error": snap.get("error"),
307
+ "promptId": snap.get("promptId"),
308
+ }
309
+
310
+ @router.get("/jobs")
311
+ def comfy_list_jobs(request: Request):
312
+ """이 μ‚¬μš©μžμ˜ μž‘μ—…(μ§„ν–‰ 쀑 + 보관 κΈ°κ°„ λ‚΄ μ™„λ£Œ/μ‹€νŒ¨)을 였래된 순으둜 λ°˜ν™˜."""
313
+ user = get_current_user(request)
314
+ require_login(user)
315
+ owner = _owner_of(request, user)
316
+ _gc_jobs()
317
+ with _JOBS_LOCK:
318
+ items = [(jid, dict(v)) for jid, v in _JOBS.items() if v.get("owner") == owner]
319
+ items.sort(key=lambda kv: kv[1]["created_at"])
320
+ return {"jobs": [_job_view(jid, v) for jid, v in items]}
321
+
322
+ @router.post("/generate")
323
+ async def comfy_generate(request: Request, payload: Dict = Body(...)):
324
+ user = get_current_user(request)
325
+ require_login(user)
326
+ st = cc.workflow_status()
327
+ if not st["ok"]:
328
+ raise HTTPException(status_code=500, detail=st["error"])
329
+ if not st["api_key"]:
330
+ raise HTTPException(status_code=500, detail="COMFY_CLOUD_API_KEY κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
331
+ _gc_jobs()
332
+ job_id = uuid.uuid4().hex[:12]
333
+ meta = payload.get("meta") if isinstance(payload.get("meta"), dict) else {}
334
+ with _JOBS_LOCK:
335
+ _JOBS[job_id] = {"status": "running", "stage": "queued_local", "created_at": time.time(),
336
+ "user": user.get("username"), "owner": _owner_of(request, user), "meta": meta}
337
+ threading.Thread(target=_run_pipeline, args=(job_id, payload, user), daemon=True).start()
338
+ return {"jobId": job_id}
339
+
340
+ @router.post("/jobs/{job_id}/cancel")
341
+ def comfy_cancel(request: Request, job_id: str):
342
+ user = get_current_user(request)
343
+ require_login(user)
344
+ with _JOBS_LOCK:
345
+ job = _JOBS.get(job_id)
346
+ if job is None:
347
+ raise HTTPException(status_code=404, detail="μž‘μ—…μ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")
348
+ if job.get("owner") != _owner_of(request, user):
349
+ raise HTTPException(status_code=403, detail="본인 μž‘μ—…λ§Œ μ·¨μ†Œν•  수 μžˆμŠ΅λ‹ˆλ‹€.")
350
+ if job.get("status") != "running":
351
+ return {"ok": True, "status": job.get("status")}
352
+ job["cancelRequested"] = True
353
+ pid = job.get("promptId")
354
+ _update(job_id, stage="cancelling")
355
+ if pid: # Comfy Cloud μͺ½ 싀행도 μ‹€μ œλ‘œ 쀑단 (ν¬λ ˆλ”§ μ ˆμ•½). μ‹€νŒ¨ν•΄λ„ 폴링 루프가 κ³§ 멈좀.
356
+ try:
357
+ used = cc.cancel(pid)
358
+ print(f"[COMFY] job {job_id} cancel accepted via {used}")
359
+ except Exception as e: # noqa: BLE001
360
+ print(f"[COMFY] job {job_id} comfy-side cancel failed (will stop polling anyway): {e}")
361
+ return {"ok": True}
362
+
363
+ @router.get("/jobs/{job_id}")
364
+ def comfy_job(job_id: str):
365
+ with _JOBS_LOCK:
366
+ job = _JOBS.get(job_id)
367
+ if job is None:
368
+ raise HTTPException(status_code=404, detail="μž‘μ—…μ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€ (μ„œλ²„κ°€ μž¬μ‹œμž‘λ˜μ—ˆμ„ 수 μžˆμŠ΅λ‹ˆλ‹€).")
369
+ snap = dict(job)
370
+ return _job_view(job_id, snap)
371
+
372
+ return router
index (45).html ADDED
@@ -0,0 +1,659 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="ko" class="dark">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>CLOVIS AI 룩뢁 생성기</title>
7
+ <script src="https://cdn.tailwindcss.com"></script>
8
+ <script>
9
+ tailwind.config = { darkMode: 'class', theme: { extend: { colors: { brand: { blue: '#3B82F6', hover: '#2563EB' } } } } }
10
+ </script>
11
+ <link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin />
12
+ <link rel="stylesheet" crossorigin href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/static/pretendard.min.css" />
13
+ <style>
14
+ * { font-family: 'Pretendard', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
15
+ body { -webkit-font-smoothing: antialiased; background: #1a1a1a; color: #f9fafb; margin: 0; overflow: hidden; }
16
+ ::-webkit-scrollbar { width: 6px; height: 6px; }
17
+ ::-webkit-scrollbar-track { background: #1a1a1a; }
18
+ ::-webkit-scrollbar-thumb { background: #374151; border-radius: 3px; }
19
+ ::-webkit-scrollbar-thumb:hover { background: #4b5563; }
20
+ @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
21
+ @keyframes shimmer { 0% { background-position: -600px 0; } 100% { background-position: 600px 0; } }
22
+ @keyframes pulseRing { 0% { transform: scale(0.85); opacity: .9; } 100% { transform: scale(1.6); opacity: 0; } }
23
+ .animate-fadeIn { animation: fadeIn .25s ease-out; }
24
+ .shimmer { background: linear-gradient(90deg, #232323 0%, #2c2c2c 40%, #232323 80%); background-size: 600px 100%; animation: shimmer 1.6s linear infinite; }
25
+ .pulse-ring::before { content: ''; position: absolute; inset: -6px; border-radius: 9999px; border: 2px solid #3B82F6; animation: pulseRing 1.4s ease-out infinite; }
26
+ .ai-label-overlay { position: absolute; top: 12pt; right: 12pt; font-weight: 300; font-size: 10pt; color: #3c3c3c; pointer-events: none; z-index: 2; letter-spacing: -0.02em; }
27
+ .drop-active { border-color: #3B82F6 !important; background: rgba(59,130,246,.08) !important; }
28
+ textarea { resize: vertical; }
29
+ </style>
30
+ <script type="importmap">
31
+ { "imports": {
32
+ "react": "https://esm.sh/react@19.1.0",
33
+ "react/": "https://esm.sh/react@19.1.0/",
34
+ "react-dom/": "https://esm.sh/react-dom@19.1.0/",
35
+ "lucide-react": "https://esm.sh/lucide-react@0.462.0?external=react"
36
+ } }
37
+ </script>
38
+ </head>
39
+ <body>
40
+ <div id="root"></div>
41
+ <script type="module">
42
+ import React, { useState, useEffect, useRef, useCallback } from 'react';
43
+ import ReactDOM from 'react-dom/client';
44
+ import { Download, X, Upload, Sparkles, RefreshCw, AlertTriangle, Clock, Check, ImagePlus, User, Maximize2, ChevronDown } from 'lucide-react';
45
+
46
+ const h = React.createElement;
47
+
48
+ // ═══════════════════════════════════════════════════════════
49
+ // Constants β€” μ›Œν¬ν”Œλ‘œμš°(SPAO.json) CustomCombo μ˜΅μ…˜κ³Ό 1:1
50
+ // ═══════════════════════════════════════════════════════════
51
+ const SHOT_OPTIONS = ['μ „μ‹ μ»·', 'μƒλ°˜μ‹ μ»·', 'ν•˜λ°˜μ‹ μ»·']; // ν”„λ ˆμž„μ€ 항상 μƒ· κ·œμΉ™μ΄ 정함 (λ ˆνΌλŸ°μŠ€λŠ” 포즈 참고용)
52
+ const ANGLE_OPTIONS = ['μ •λ©΄', '반츑면', 'μΈ‘λ©΄', 'λ‘œμš°μ•΅κΈ€', 'ν•˜μ΄μ•΅κΈ€', 'ν›„λ©΄', '레퍼런슀 따름'];
53
+ const GAZE_OPTIONS = ['카메라 μ‘μ‹œ', 'μžμ—°μŠ€λŸ¬μš΄ μ‹œμ„ ', '레퍼런슀 따름'];
54
+ const AGE_OPTIONS = ['성인', 'ν‚€μ¦ˆ'];
55
+ const DETAIL_GROUPS = [
56
+ { key: 'outer', label: 'μ•„μš°ν„°', length: 'outer_length', fit: 'outer_fit' },
57
+ { key: 'top', label: 'μƒμ˜', length: 'top_length', fit: 'top_fit' },
58
+ { key: 'bottom', label: 'ν•˜μ˜', length: 'bottom_length', fit: 'bottom_fit' },
59
+ ];
60
+ const DETAIL_OPTIONS = {
61
+ outer_length: { label: 'μ•„μš°ν„° 길이', options: ['ν—ˆλ¦¬', '골반', 'ν—ˆλ²…μ§€'], def: '골반' },
62
+ outer_fit: { label: 'μ•„μš°ν„° 핏', options: ['슬림', 'ν‘œμ€€', 'μ˜€λ²„'], def: 'ν‘œμ€€' },
63
+ top_length: { label: 'μƒμ˜ 길이', options: ['ν—ˆλ¦¬', '골반', 'ν—ˆλ²…μ§€'], def: '골반' },
64
+ top_fit: { label: 'μƒμ˜ 핏', options: ['슬림', 'ν‘œμ€€', 'μ˜€λ²„'], def: 'μ˜€λ²„' },
65
+ bottom_length: { label: 'ν•˜μ˜ 길이', options: ['ν—ˆλ²…μ§€', '무릎', '쒅아리', '발λͺ©', 'μ‹ λ°œ'], def: 'μ‹ λ°œ' },
66
+ bottom_fit: { label: 'ν•˜μ˜ 핏', options: ['슬림', 'ν‘œμ€€', 'μ˜€λ²„'], def: 'μ˜€λ²„' },
67
+ };
68
+
69
+ const ADULT_FACE_PRESETS = [
70
+ { id: 'preset_17', label: 'μ—¬μ„± 1', url: '/face_preset_17.png' },
71
+ { id: 'preset_18', label: 'μ—¬μ„± 2', url: '/face_preset_18.png' },
72
+ { id: 'preset_19', label: 'μ—¬μ„± 3', url: '/face_preset_19.png' },
73
+ ];
74
+ // CLOVIS λŠ” ν‚€μ¦ˆ 라인이 μ—†μ–΄ ν‚€μ¦ˆ 프리셋·연령 토글을 λ…ΈμΆœν•˜μ§€ μ•ŠμŒ (μ›Œν¬ν”Œλ‘œμš° age μ½€λ³΄μ—λŠ” '성인' κ³ μ • 전달)
75
+
76
+ const IMAGE_SLOTS = [
77
+ { key: 'outer', label: 'μ•„μš°ν„°', required: false },
78
+ { key: 'top', label: 'μƒμ˜', required: false },
79
+ { key: 'bottom', label: 'ν•˜μ˜', required: false, hint: 'μ›ν”ΌμŠ€λ„ μ—¬κΈ°' },
80
+ { key: 'shoes', label: 'μ‹ λ°œ', required: false },
81
+ { key: 'inner', label: 'μ΄λ„ˆμ›¨μ–΄', required: false },
82
+ { key: 'belt', label: '벨트', required: false },
83
+ { key: 'background', label: 'λ°°κ²½', required: false, hint: 'λΉ„μš°λ©΄ κΈ°λ³Έ μŠ€νŠœλ””μ˜€' },
84
+ { key: 'pose', label: '레퍼런슀 포즈', required: false, hint: '포즈 참고용 Β· κ΅¬λ„λŠ” μƒ· 선택 κΈ°μ€€' },
85
+ ];
86
+
87
+ // λ””ν…ŒμΌ μ°Έμ‘°: ν΄λ‘œμ¦ˆμ—…μ„ 생성 λͺ¨λΈμ— 직접 참쑰둜 전달 (전체 μ΅œλŒ€ 4μž₯)
88
+ // μ˜·λ§ˆλ‹€ 슬둯 2개(a/b), μŠ¬λ‘―λ³„λ‘œ μ’…λ₯˜λ₯Ό 고름 β€” μ’…λ₯˜λŠ” comfy_client.DETAIL_KIND_EN 킀와 1:1
89
+ const DETAIL_MAX = 4;
90
+ const DETAIL_SLOTS = ['a', 'b'];
91
+ // 옷 μ’…λ₯˜λ³„ λ””ν…ŒμΌ ν•­λͺ© β€” key λŠ” comfy_client.DETAIL_KIND_EN κ³Ό 1:1. short: μΉ© ν‘œμ‹œ, label: 툴팁
92
+ const K = {
93
+ texture: { key: 'texture', short: '쑰직감', label: '원단 쑰직감 (옷 전체에 반영)' },
94
+ logo: { key: 'logo', short: '둜고', label: 'λ‘œκ³ Β·ν”„λ¦°νŠΈ (메인 사진과 같은 μœ„μΉ˜)' },
95
+ neckline: { key: 'neckline', short: 'λ„₯라인', label: 'λ„₯라인·카라' },
96
+ collar: { key: 'collar', short: 'μΉ΄λΌΒ·ν›„λ“œ', label: 'μΉ΄λΌΒ·ν›„λ“œΒ·λΌνŽ ' },
97
+ sleeve: { key: 'sleeve', short: 'μ†Œλ§€', label: 'μ†Œλ§€Β·μ»€ν”„μŠ€' },
98
+ hem: { key: 'hem', short: '밑단', label: '밑단·헴 마감' },
99
+ waist: { key: 'waist', short: 'ν—ˆλ¦¬', label: 'ν—ˆλ¦¬ (μ›¨μ΄μŠ€νŠΈλ°΄λ“œΒ·λ²¨νŠΈλ£¨ν”„Β·λ“œλ‘œμŠ€νŠΈλ§)' },
100
+ pocket: { key: 'pocket', short: '포켓', label: '포켓 (ν˜•νƒœΒ·μŠ€ν‹°μΉ˜Β·ν”Œλž©)' },
101
+ closure: { key: 'closure', short: 'μ§€νΌΒ·λ²„νŠΌ', label: 'μ§€νΌΒ·λ²„νŠΌΒ·μŠ€λƒ…' },
102
+ trim: { key: 'trim', short: 'λΆ€μžμž¬', label: 'λΆ€μžμž¬ (λΌλ²¨Β·νƒ­Β·μ™€νŽœ λ“±)' },
103
+ material: { key: 'material', short: 'μ†Œμž¬', label: 'μ†Œμž¬Β·μ§ˆκ° (κ°€μ£½Β·μŠ€μ›¨μ΄λ“œΒ·λ©”μ‹œ λ“±, 전체에 반영)' },
104
+ sole: { key: 'sole', short: 'λ°‘μ°½', label: '밑창·아웃솔' },
105
+ lacing: { key: 'lacing', short: '끈', label: 'λˆΒ·μ•„μΌλ ›Β·μ„€ν¬' },
106
+ heel: { key: 'heel', short: 'λ’€μΆ•', label: 'λ’€μΆ•Β·νžνƒ­Β·λ°œλͺ©' },
107
+ buckle: { key: 'buckle', short: '버클', label: '버클' },
108
+ edge: { key: 'edge', short: 'μŠ€ν‹°μΉ˜', label: 'μŠ€ν‹°μΉ˜Β·μ—£μ§€Β·λ²¨νŠΈν™€' },
109
+ };
110
+ const DETAIL_KINDS_BY_GARMENT = {
111
+ outer: [K.texture, K.logo, K.collar, K.sleeve, K.hem, K.pocket, K.closure, K.trim],
112
+ top: [K.texture, K.logo, K.neckline, K.sleeve, K.hem, K.pocket, K.trim],
113
+ bottom: [K.texture, K.logo, K.waist, K.hem, K.pocket, K.closure, K.trim],
114
+ shoes: [K.material, K.logo, K.sole, K.lacing, K.heel, K.trim],
115
+ inner: [K.texture, K.logo, K.neckline, K.sleeve, K.hem],
116
+ belt: [K.material, K.buckle, K.logo, K.edge],
117
+ };
118
+ // 슬둯 κΈ°λ³Έκ°’: μ™Όμͺ½ = μ†Œμž¬/쑰직감, 였λ₯Έμͺ½ = 둜고 (λ²¨νŠΈλŠ” 버클)
119
+ const defaultKind = (g, slot) => {
120
+ const list = DETAIL_KINDS_BY_GARMENT[g] || [];
121
+ if (slot === 'a') return list[0]?.key;
122
+ return g === 'belt' ? 'buckle' : (list.find(k => k.key === 'logo') || list[1] || list[0])?.key;
123
+ };
124
+ const DETAIL_GARMENTS = [
125
+ { key: 'outer', label: 'μ•„μš°ν„°' }, { key: 'top', label: 'μƒμ˜' }, { key: 'bottom', label: 'ν•˜μ˜' },
126
+ { key: 'shoes', label: 'μ‹ λ°œ' }, { key: 'inner', label: 'μ΄λ„ˆμ›¨μ–΄' }, { key: 'belt', label: '벨트' },
127
+ ];
128
+
129
+ // AI ν‘œκΈ° β€” μ €μž₯ μ‹œ μΊ”λ²„μŠ€μ— μ‚½μž… (κΈ°μ‘΄ μ•±κ³Ό 동일 규격)
130
+ const AI_LABEL_TEXT = 'AI 생성 이미지';
131
+ const AI_LABEL_FONT_PT = 28;
132
+ const AI_LABEL_MARGIN_PT = 12 * (28 / 10);
133
+
134
+ // ═══════════════════════════════════════════════════════════
135
+ // Helpers
136
+ // ═══════════════════════════════════════════════════════════
137
+ const fileToDataUrl = (file, maxSide = 1536) => new Promise((resolve, reject) => {
138
+ const reader = new FileReader();
139
+ reader.onerror = reject;
140
+ reader.onload = () => {
141
+ const img = new Image();
142
+ img.onerror = reject;
143
+ img.onload = () => {
144
+ const scale = Math.min(1, maxSide / Math.max(img.width, img.height));
145
+ const w = Math.round(img.width * scale), hgt = Math.round(img.height * scale);
146
+ const canvas = document.createElement('canvas');
147
+ canvas.width = w; canvas.height = hgt;
148
+ const ctx = canvas.getContext('2d');
149
+ const keepPng = /png|webp/i.test(file.type);
150
+ if (!keepPng) { ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, w, hgt); }
151
+ ctx.drawImage(img, 0, 0, w, hgt);
152
+ resolve(keepPng ? canvas.toDataURL('image/png') : canvas.toDataURL('image/jpeg', 0.92));
153
+ };
154
+ img.src = reader.result;
155
+ };
156
+ reader.readAsDataURL(file);
157
+ });
158
+
159
+ const drawAiDisclosureOnCanvas = (ctx, width, height) => {
160
+ ctx.save();
161
+ ctx.textAlign = 'right'; ctx.textBaseline = 'top'; ctx.fillStyle = '#3c3c3c';
162
+ ctx.font = `300 ${AI_LABEL_FONT_PT}pt 'Pretendard', 'Apple SD Gothic Neo', 'Malgun Gothic', sans-serif`;
163
+ const ptToPx = 96 / 72;
164
+ const m = Math.max(AI_LABEL_MARGIN_PT * ptToPx, Math.min(width, height) * 0.028, 18);
165
+ ctx.fillText(AI_LABEL_TEXT, width - m, m);
166
+ ctx.restore();
167
+ };
168
+
169
+ async function downloadWithLabel(imageUrl, filename, withLabel = true) {
170
+ const img = new Image();
171
+ await new Promise((res, rej) => { img.onload = res; img.onerror = rej; img.src = imageUrl; });
172
+ const canvas = document.createElement('canvas');
173
+ canvas.width = img.naturalWidth; canvas.height = img.naturalHeight;
174
+ const ctx = canvas.getContext('2d');
175
+ ctx.drawImage(img, 0, 0);
176
+ if (withLabel) drawAiDisclosureOnCanvas(ctx, canvas.width, canvas.height);
177
+ const a = document.createElement('a');
178
+ a.href = canvas.toDataURL('image/png'); a.download = filename; a.click();
179
+ }
180
+
181
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
182
+
183
+ // λΉ„λ‘œκ·ΈμΈ μ‚¬μš©μžλ„ μž‘μ—…μ„ λ‹€μ‹œ 뢈러올 수 μžˆλ„λ‘ λΈŒλΌμš°μ €λ³„ IDλ₯Ό 보관 (둜그인 μ‹œμ—” μ„œλ²„κ°€ 계정λͺ…μœΌλ‘œ 묢음)
184
+ const CLIENT_ID = (() => {
185
+ try {
186
+ let id = localStorage.getItem('clovis_client_id');
187
+ if (!id) { id = crypto.randomUUID(); localStorage.setItem('clovis_client_id', id); }
188
+ return id;
189
+ } catch { return 'c-' + Math.random().toString(36).slice(2); }
190
+ })();
191
+ const apiHeaders = (json = false) => ({ 'X-Client-Id': CLIENT_ID, ...(json ? { 'Content-Type': 'application/json' } : {}) });
192
+
193
+ // 제좜 β†’ jobId β†’ 폴링. κΈ΄ HTTP 연결을 작고 μžˆμ§€ μ•ŠμœΌλ―€λ‘œ Space ν”„λ‘μ‹œ νƒ€μž„μ•„μ›ƒκ³Ό 무관.
194
+ async function submitToComfy(payload) {
195
+ const res = await fetch('/api/comfy/generate', { method: 'POST', headers: apiHeaders(true), body: JSON.stringify(payload) });
196
+ if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.detail || `HTTP ${res.status}`); }
197
+ return (await res.json()).jobId;
198
+ }
199
+ async function pollComfyJob(jobId, onProgress) {
200
+ let misses = 0;
201
+ while (true) {
202
+ await sleep(3000);
203
+ let r;
204
+ try { r = await fetch(`/api/comfy/jobs/${jobId}`, { headers: apiHeaders() }); } catch { if (++misses > 10) throw new Error('μ„œλ²„ 응닡이 μ—†μŠ΅λ‹ˆλ‹€.'); continue; }
205
+ if (r.status === 404) throw new Error('μž‘μ—… 정보λ₯Ό μžƒμ–΄λ²„λ ΈμŠ΅λ‹ˆλ‹€ (μ„œλ²„ μž¬μ‹œμž‘). λ‹€μ‹œ μ‹œλ„ν•΄μ£Όμ„Έμš”.');
206
+ if (!r.ok) { if (++misses > 10) throw new Error(`HTTP ${r.status}`); continue; }
207
+ misses = 0;
208
+ const j = await r.json();
209
+ onProgress?.(j);
210
+ if (j.status === 'done') return j;
211
+ if (j.status === 'cancelled') return null; // μ‚¬μš©μž μ·¨μ†Œ β€” 쑰용히 μ’…λ£Œ
212
+ if (j.status === 'error') throw new Error(j.error || '생성 μ‹€νŒ¨');
213
+ }
214
+ }
215
+
216
+ const fmtSec = (s) => { s = Math.round(s || 0); return s >= 60 ? `${Math.floor(s / 60)}λΆ„ ${s % 60}초` : `${s}초`; };
217
+
218
+ // ═══════════════════════════════════════════════════════════
219
+ // UI atoms
220
+ // ═══════════════════════════════════════════════════════════
221
+ const SectionTitle = ({ children, right }) => h('div', { className: 'flex items-center justify-between mb-2.5' },
222
+ h('h3', { className: 'text-[13px] font-semibold text-gray-200 tracking-tight' }, children), right || null);
223
+
224
+ const Segmented = ({ options, value, onChange, cols }) => h('div', {
225
+ className: `grid gap-1.5`, style: { gridTemplateColumns: `repeat(${cols || options.length}, minmax(0, 1fr))` } },
226
+ options.map(o => h('button', {
227
+ key: o, type: 'button', onClick: () => onChange(o),
228
+ className: `px-2 py-2 rounded-lg text-[12.5px] font-medium border transition-colors ${value === o
229
+ ? 'bg-brand-blue border-brand-blue text-white'
230
+ : 'bg-[#242424] border-[#333] text-gray-300 hover:border-[#4b5563] hover:text-white'}`
231
+ }, o)));
232
+
233
+ const UploadTile = ({ slot, value, onChange, disabled }) => {
234
+ const inputRef = useRef(null);
235
+ const [drag, setDrag] = useState(false);
236
+ const handleFiles = async (files) => {
237
+ const f = files?.[0]; if (!f || !f.type.startsWith('image/')) return;
238
+ onChange(await fileToDataUrl(f), f.name);
239
+ };
240
+ return h('div', {
241
+ className: `relative rounded-xl border overflow-hidden group ${drag ? 'drop-active' : ''} ${value ? 'border-[#3a3a3a]' : 'border-dashed border-[#3a3a3a] bg-[#212121] hover:border-[#4b5563]'}`,
242
+ style: { aspectRatio: '3 / 4' },
243
+ onDragOver: e => { e.preventDefault(); setDrag(true); }, onDragLeave: () => setDrag(false),
244
+ onDrop: e => { e.preventDefault(); setDrag(false); if (!disabled) handleFiles(e.dataTransfer.files); },
245
+ onClick: () => !disabled && !value && inputRef.current?.click(),
246
+ },
247
+ h('input', { ref: inputRef, type: 'file', accept: 'image/*', className: 'hidden', onChange: e => { handleFiles(e.target.files); e.target.value = ''; } }),
248
+ value
249
+ ? h(React.Fragment, null,
250
+ h('img', { src: value, className: 'w-full h-full object-cover bg-white', alt: slot.label }),
251
+ !disabled && h('button', { type: 'button', onClick: e => { e.stopPropagation(); onChange(null, null); },
252
+ className: 'absolute top-1.5 right-1.5 w-6 h-6 rounded-full bg-black/70 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity' }, h(X, { size: 13 })),
253
+ h('div', { className: 'absolute bottom-0 inset-x-0 px-2 py-1 bg-gradient-to-t from-black/70 to-transparent text-[11px] text-white' }, slot.label))
254
+ : h('div', { className: 'absolute inset-0 flex flex-col items-center justify-center gap-1 text-gray-500 cursor-pointer' },
255
+ h(ImagePlus, { size: 18 }),
256
+ h('span', { className: 'text-[11.5px] text-gray-300' }, slot.label, slot.required && h('span', { className: 'text-brand-blue ml-0.5' }, '*')),
257
+ slot.hint && h('span', { className: 'text-[10px] text-gray-500 px-2 text-center leading-tight' }, slot.hint))
258
+ );
259
+ };
260
+
261
+ const DetailTile = ({ value, onChange, disabled }) => {
262
+ const inputRef = useRef(null);
263
+ const handleFiles = async (files) => {
264
+ const f = files?.[0]; if (!f || !f.type.startsWith('image/')) return;
265
+ onChange(await fileToDataUrl(f, 1024), f.name);
266
+ };
267
+ return h('div', {
268
+ className: `relative w-full rounded-lg overflow-hidden group ${value ? 'border border-[#3a3a3a]' : 'border border-dashed border-[#3a3a3a] bg-[#212121] hover:border-[#4b5563]'} ${disabled ? 'opacity-60 border-[#333]' : ''}`,
269
+ style: { aspectRatio: '1 / 1' },
270
+ onDragOver: e => e.preventDefault(), onDrop: e => { e.preventDefault(); if (!disabled) handleFiles(e.dataTransfer.files); },
271
+ onClick: () => !disabled && !value && inputRef.current?.click(),
272
+ },
273
+ h('input', { ref: inputRef, type: 'file', accept: 'image/*', className: 'hidden', onChange: e => { handleFiles(e.target.files); e.target.value = ''; } }),
274
+ value
275
+ ? h(React.Fragment, null,
276
+ h('img', { src: value, className: 'w-full h-full object-cover bg-white' }),
277
+ !disabled && h('button', { type: 'button', onClick: e => { e.stopPropagation(); onChange(null, null); },
278
+ className: 'absolute top-1 right-1 w-5 h-5 rounded-full bg-black/70 text-white flex items-center justify-center opacity-0 group-hover:opacity-100' }, h(X, { size: 11 })))
279
+ : h('div', { className: 'absolute inset-0 flex items-center justify-center text-gray-600 cursor-pointer' }, h(ImagePlus, { size: 14 })));
280
+ };
281
+
282
+ const FaceTile = ({ preset, selected, onClick }) => h('button', {
283
+ type: 'button', onClick, title: preset.label,
284
+ className: `relative rounded-xl overflow-hidden border-2 transition-colors ${selected ? 'border-brand-blue' : 'border-transparent hover:border-[#4b5563]'}`,
285
+ style: { aspectRatio: '1 / 1' } },
286
+ h('img', { src: preset.url, className: 'w-full h-full object-cover', alt: preset.label }),
287
+ selected && h('div', { className: 'absolute top-1 right-1 w-5 h-5 rounded-full bg-brand-blue flex items-center justify-center' }, h(Check, { size: 12, className: 'text-white' })),
288
+ h('div', { className: 'absolute bottom-0 inset-x-0 px-1.5 py-0.5 bg-black/60 text-[10.5px] text-white text-center' }, preset.label));
289
+
290
+ // ═══════════════════════════════════════════════════════════
291
+ // App
292
+ // ═══════════════════════════════════════════════════════════
293
+ function App() {
294
+ const [user, setUser] = useState({ username: 'anonymous', is_logged_in: false, oauth_enabled: false });
295
+ const [health, setHealth] = useState(null);
296
+
297
+ const age = '성인'; // CLOVIS: 성인 κ³ μ •
298
+ const [facePreset, setFacePreset] = useState('preset_17');
299
+ const [detailKinds, setDetailKinds] = useState({}); // 'outer:a' β†’ kind key
300
+ const [faceUpload, setFaceUpload] = useState(null);
301
+ const [shot, setShot] = useState('μ „μ‹ μ»·');
302
+ const [angle, setAngle] = useState('반츑면');
303
+ const [gaze, setGaze] = useState('μžμ—°μŠ€λŸ¬μš΄ μ‹œμ„ ');
304
+ const [prompt, setPrompt] = useState('');
305
+ const [details, setDetails] = useState(Object.fromEntries(Object.entries(DETAIL_OPTIONS).map(([k, v]) => [k, v.def])));
306
+ const [detailTab, setDetailTab] = useState('top');
307
+ const [images, setImages] = useState({});
308
+ const [imageNames, setImageNames] = useState({}); // μŠ¬λ‘―λ³„ 원본 파일λͺ… (Dataset λ‘œκ·ΈΒ·μŠ€νƒ€μΌμ½”λ“œ μ§‘κ³„μš©)
309
+ const [faceUploadName, setFaceUploadName] = useState(null);
310
+ const [poseSpec, setPoseSpec] = useState(''); // 포즈 μ§€μ‹œ λ¬Έμž₯ (λΉ„μš°λ©΄ GPT 비전이 λ ˆνΌλŸ°μŠ€μ—μ„œ μžλ™ μΆ”μΆœ)
311
+
312
+ const [jobs, setJobs] = useState([]); // μ§„ν–‰ 쀑/μ‹€νŒ¨ μž‘μ—… [{id, jobId, meta, stageLabel, startedAt, error}]
313
+ const [tick, setTick] = useState(0); // κ²½κ³Όμ‹œκ°„ ν‘œμ‹œμš© 1초 타이머
314
+ const [results, setResults] = useState([]); // [{id, imageUrl, meta, elapsedSec}]
315
+ const [current, setCurrent] = useState(null);
316
+ const [error, setError] = useState(null);
317
+ const [aiLabel, setAiLabel] = useState(true);
318
+ const [lightbox, setLightbox] = useState(false); // κ²°κ³Ό 이미지 ν™•λŒ€ 보기
319
+ const [showSpecs, setShowSpecs] = useState(false); // μ˜μƒ 뢄석 κ²°κ³Ό / μ΅œμ’… ν”„λ‘¬ν”„νŠΈ 펼치기
320
+ useEffect(() => {
321
+ if (!lightbox) return;
322
+ const onKey = (e) => { if (e.key === 'Escape') setLightbox(false); };
323
+ window.addEventListener('keydown', onKey);
324
+ return () => window.removeEventListener('keydown', onKey);
325
+ }, [lightbox]);
326
+ const faceFileRef = useRef(null);
327
+
328
+ useEffect(() => {
329
+ fetch('/api/whoami').then(r => r.ok ? r.json() : null).then(d => d && setUser(d)).catch(() => {});
330
+ fetch('/api/comfy/health').then(r => r.ok ? r.json() : { ok: false, error: 'λΈŒλ¦¬μ§€ λΌμš°νŠΈκ°€ μ—†μŠ΅λ‹ˆλ‹€' }).then(setHealth).catch(() => setHealth({ ok: false, error: 'μƒνƒœ 확인 μ‹€νŒ¨' }));
331
+ }, []);
332
+
333
+ const activeJobs = jobs.filter(j => !j.error);
334
+ useEffect(() => {
335
+ if (activeJobs.length === 0) return;
336
+ const id = setInterval(() => setTick(t => t + 1), 1000);
337
+ return () => clearInterval(id);
338
+ }, [activeJobs.length]);
339
+
340
+ const presets = ADULT_FACE_PRESETS;
341
+ const setImg = (key, v, name) => {
342
+ setImages(prev => ({ ...prev, [key]: v })); setImageNames(prev => ({ ...prev, [key]: v ? (name || null) : null }));
343
+ if (key === 'pose' && !v) { if (angle === '레퍼런슀 따름') setAngle('반츑면'); if (gaze === '레퍼런슀 따름') setGaze('μžμ—°μŠ€λŸ¬μš΄ μ‹œμ„ '); }
344
+ };
345
+
346
+ const kindOf = (g, slot) => { // μ €μž₯된 값이 κ·Έ 옷 μ’…λ₯˜μ— μ—†μœΌλ©΄ κΈ°λ³Έκ°’μœΌλ‘œ
347
+ const list = DETAIL_KINDS_BY_GARMENT[g] || [];
348
+ const v = detailKinds[`${g}:${slot}`];
349
+ return list.some(k => k.key === v) ? v : defaultKind(g, slot);
350
+ };
351
+ const detailList = DETAIL_GARMENTS.flatMap(g => DETAIL_SLOTS.map(slot => ({ garment: g.key, kind: kindOf(g.key, slot), image: images[`detail:${g.key}:${slot}`], filename: imageNames[`detail:${g.key}:${slot}`] })))
352
+ .filter(x => x.image && images[x.garment]);
353
+ const detailCount = detailList.length;
354
+ const missing = [];
355
+ if (!images.outer && !images.top && !images.bottom) missing.push('μ˜μƒ 1개 이상 (μ•„μš°ν„°Β·μƒμ˜Β·ν•˜μ˜)');
356
+ const canGenerate = missing.length === 0 && (faceUpload || facePreset) && health?.ok;
357
+
358
+ const handleGenerate = async () => {
359
+ if (user.oauth_enabled && !user.is_logged_in) { alert("둜그인이 ν•„μš”ν•©λ‹ˆλ‹€. 우츑 μƒλ‹¨μ˜ 'Hugging Face둜 둜그인' λ²„νŠΌμ„ λˆŒλŸ¬μ£Όμ„Έμš”."); return; }
360
+ if (!canGenerate) return;
361
+ setError(null);
362
+ const id = Date.now().toString(36) + Math.random().toString(36).slice(2, 5);
363
+ const meta = { shot, angle, gaze, age, prompt, face: faceUpload ? 'μ—…λ‘œλ“œ' : (presets.find(p => p.id === facePreset)?.label || facePreset) };
364
+ const mainImages = Object.fromEntries(Object.entries(images).filter(([k, v]) => v && !k.startsWith('detail:')));
365
+ const payload = { face: faceUpload || facePreset, faceFilename: faceUpload ? faceUploadName : null, images: mainImages, imageFilenames: imageNames,
366
+ details: detailList.slice(0, DETAIL_MAX).map(x => ({ garment: x.garment, kind: x.kind, image: x.image, filename: x.filename || null })),
367
+ poseSpec: (images.pose || poseSpec.trim()) ? poseSpec.trim() : '',
368
+ options: { shot, angle, gaze, age, ...details }, prompt, meta };
369
+ setJobs(prev => [...prev, { id, meta, stageLabel: 'μš”μ²­ 전솑 쀑', startedAt: Date.now() }]);
370
+ const patch = (p) => setJobs(prev => prev.map(j => j.id === id ? { ...j, ...p } : j));
371
+ let jobId;
372
+ try {
373
+ jobId = await submitToComfy(payload);
374
+ } catch (e) {
375
+ patch({ error: e.message }); return;
376
+ }
377
+ patch({ jobId, stageLabel: 'λŒ€κΈ° 쀑' });
378
+ await trackJob(id, jobId, meta, patch);
379
+ };
380
+
381
+ // μ„œλ²„ μž‘μ—…μ„ μ™„λ£ŒκΉŒμ§€ 따라가며 κ²°κ³Ό/μ—λŸ¬λ₯Ό 반영 (μƒˆ μš”μ²­κ³Ό μƒˆλ‘œκ³ μΉ¨ 볡ꡬ λ‘˜ λ‹€ μ‚¬μš©)
382
+ const trackJob = async (id, jobId, meta, patch) => {
383
+ try {
384
+ const j = await pollComfyJob(jobId, (st) => patch({ stageLabel: st.stageLabel, execStartedAt: st.execStartedAt || null }));
385
+ if (!j) { setJobs(prev => prev.filter(x => x.id !== id)); return; } // μ·¨μ†Œλ¨
386
+ const item = { id, imageUrl: j.imageUrl, meta, elapsedSec: j.elapsedSec, createdAt: j.createdAt, garmentSpecs: j.garmentSpecs || null, finalPrompt: j.finalPrompt || null, poseSpec: j.poseSpec || null };
387
+ setResults(prev => prev.some(r => r.id === id) ? prev : [item, ...prev]);
388
+ setCurrent(prev => prev || item);
389
+ setJobs(prev => prev.filter(x => x.id !== id));
390
+ } catch (e) {
391
+ patch({ error: e.message });
392
+ }
393
+ };
394
+ const dismissJob = (id) => setJobs(prev => prev.filter(j => j.id !== id));
395
+ const cancelJob = async (job) => { // μ§„ν–‰ 쀑 μž‘μ—… μ·¨μ†Œ: μ„œλ²„μ— μš”μ²­ ν›„ μΉ΄λ“œ 제거 (폴링도 cancelled λ₯Ό 보고 멈좀)
396
+ setJobs(prev => prev.map(x => x.id === job.id ? { ...x, cancelling: true, stageLabel: 'μ·¨μ†Œ 쀑' } : x));
397
+ try { if (job.jobId) await fetch(`/api/comfy/jobs/${job.jobId}/cancel`, { method: 'POST', headers: apiHeaders() }); } catch {}
398
+ setJobs(prev => prev.filter(x => x.id !== job.id));
399
+ };
400
+
401
+ // μƒˆλ‘œκ³ μΉ¨/μž¬μ ‘μ† μ‹œ μ„œλ²„μ— 남아 μžˆλŠ” λ‚΄ μž‘μ—… 볡ꡬ
402
+ useEffect(() => {
403
+ (async () => {
404
+ try {
405
+ const r = await fetch('/api/comfy/jobs', { headers: apiHeaders() });
406
+ if (!r.ok) return;
407
+ const { jobs: saved } = await r.json();
408
+ const done = saved.filter(j => j.status === 'done' && j.imageUrl)
409
+ .map(j => ({ id: j.id, imageUrl: j.imageUrl, meta: j.meta || {}, elapsedSec: j.elapsedSec, createdAt: j.createdAt, garmentSpecs: j.garmentSpecs || null, finalPrompt: j.finalPrompt || null, poseSpec: j.poseSpec || null }))
410
+ .sort((a, b) => b.createdAt - a.createdAt);
411
+ if (done.length) { setResults(done); setCurrent(prev => prev || done[0]); }
412
+ const pending = saved.filter(j => j.status !== 'done' && j.status !== 'cancelled');
413
+ if (pending.length) {
414
+ setJobs(pending.map(j => ({ id: j.id, jobId: j.id, meta: j.meta || {}, stageLabel: j.stageLabel, startedAt: j.createdAt, execStartedAt: j.execStartedAt || null, error: j.error || null })));
415
+ for (const j of pending.filter(x => x.status === 'running')) {
416
+ const patch = (p) => setJobs(prev => prev.map(x => x.id === j.id ? { ...x, ...p } : x));
417
+ trackJob(j.id, j.id, j.meta || {}, patch);
418
+ }
419
+ }
420
+ } catch {}
421
+ })();
422
+ }, []);
423
+
424
+ // ── Left: settings ────────────────────────────────────────
425
+ const left = h('aside', { className: 'w-full lg:w-[420px] xl:w-[460px] shrink-0 h-full overflow-y-auto border-r border-[#2a2a2a] bg-[#1e1e1e]' },
426
+ h('div', { className: 'p-5 space-y-6' },
427
+
428
+ h('section', null,
429
+ h(SectionTitle, null, 'μ–Όκ΅΄'),
430
+ h('div', { className: 'grid grid-cols-4 gap-2' },
431
+ presets.map(p => h(FaceTile, { key: p.id, preset: p, selected: !faceUpload && facePreset === p.id, onClick: () => { setFaceUpload(null); setFacePreset(p.id); } })),
432
+ h('button', { type: 'button', onClick: () => faceFileRef.current?.click(),
433
+ className: `relative rounded-xl overflow-hidden border-2 ${faceUpload ? 'border-brand-blue' : 'border-dashed border-[#3a3a3a] hover:border-[#4b5563] bg-[#242424]'}`, style: { aspectRatio: '1 / 1' } },
434
+ faceUpload
435
+ ? h(React.Fragment, null, h('img', { src: faceUpload, className: 'w-full h-full object-cover' }),
436
+ h('span', { onClick: e => { e.stopPropagation(); setFaceUpload(null); }, className: 'absolute top-1 right-1 w-5 h-5 rounded-full bg-black/70 flex items-center justify-center' }, h(X, { size: 11 })),
437
+ h('div', { className: 'absolute bottom-0 inset-x-0 py-0.5 bg-black/60 text-[10.5px] text-center' }, 'μ—…λ‘œλ“œ'))
438
+ : h('div', { className: 'absolute inset-0 flex flex-col items-center justify-center gap-1 text-gray-400' }, h(User, { size: 16 }), h('span', { className: 'text-[10.5px]' }, '직접 μ—…λ‘œλ“œ'))),
439
+ h('input', { ref: faceFileRef, type: 'file', accept: 'image/*', className: 'hidden', onChange: async e => { const f = e.target.files?.[0]; if (f) { setFaceUpload(await fileToDataUrl(f, 1024)); setFaceUploadName(f.name); } e.target.value = ''; } }))),
440
+
441
+ h('section', null, h(SectionTitle, null, 'μƒ· 선택'), h(Segmented, { options: SHOT_OPTIONS, value: shot, cols: 3, onChange: setShot })),
442
+ h('section', null,
443
+ h(SectionTitle, { right: images.pose && h('span', { className: 'text-[11px] text-gray-500' }, "'레퍼런슀 따름' = 포즈 μ‚¬μ§„μ˜ μ•΅κΈ€") }, '카메라 μ•΅κΈ€'),
444
+ h(Segmented, { options: images.pose ? ANGLE_OPTIONS : ANGLE_OPTIONS.filter(o => o !== '레퍼런슀 따름'), value: angle, onChange: setAngle, cols: 4 })),
445
+ h('section', null, h(SectionTitle, null, 'μ‹œμ„ '), h(Segmented, { options: images.pose ? GAZE_OPTIONS : GAZE_OPTIONS.filter(o => o !== '레퍼런슀 따름'), value: gaze, onChange: setGaze })),
446
+
447
+ h('section', null,
448
+ h(SectionTitle, null, 'ν”„λ‘¬ν”„νŠΈ μž‘μ„±'),
449
+ h('textarea', { value: prompt, onChange: e => setPrompt(e.target.value), rows: 3,
450
+ placeholder: 'μΆ”κ°€ μ§€μ‹œμ‚¬ν•­ (선택). 예: 손을 μ£Όλ¨Έλ‹ˆμ— λ„£κ³  살짝 λ―Έμ†Œ, μ†Œλ§€λ₯Ό ν•œ 번 μ ‘μ–΄ 올린 μŠ€νƒ€μΌλ§',
451
+ className: 'w-full rounded-xl bg-[#242424] border border-[#333] px-3 py-2.5 text-[13px] text-gray-100 placeholder-gray-500 focus:outline-none focus:border-brand-blue' })),
452
+
453
+ h('section', null,
454
+ h(SectionTitle, { right: h('span', { className: 'text-[11px] text-gray-500' }, 'μ•„μš°ν„°Β·μƒμ˜Β·ν•˜μ˜ 쀑 1개 이상') }, '이미지 μ—…λ‘œλ“œ'),
455
+ h('div', { className: 'grid grid-cols-4 gap-2' },
456
+ IMAGE_SLOTS.map(s => h(UploadTile, { key: s.key, slot: s, value: images[s.key], onChange: (v, name) => setImg(s.key, v, name) })))),
457
+
458
+ (images.pose || poseSpec) && (health?.ok && health.poseText !== false) && h('section', { className: 'animate-fadeIn' },
459
+ h(SectionTitle, { right: h('span', { className: 'text-[11px] text-gray-500' }, 'λΉ„μš°λ©΄ λ ˆνΌλŸ°μŠ€μ—μ„œ μžλ™ μΆ”μΆœ') }, '포즈 μ§€μ‹œ (선택)'),
460
+ h('textarea', { value: poseSpec, onChange: e => setPoseSpec(e.target.value), rows: 3,
461
+ placeholder: '예: 였λ₯ΈνŒ”을 λ“€μ–΄ 손등을 였λ₯Έμͺ½ κ΄€μžλ†€μ΄μ— κ°€λ³κ²Œ λŒ„λ‹€. μ™ΌνŒ”μ€ μžμ—°μŠ€λŸ½κ²Œ 내리고 체쀑은 μ™Όλ°œμ—. λͺΈν†΅μ€ 카메라 μͺ½μœΌλ‘œ 살짝 우츑.',
462
+ className: 'w-full rounded-xl bg-[#242424] border border-[#333] px-3 py-2.5 text-[12.5px] text-gray-100 placeholder-gray-500 focus:outline-none focus:border-brand-blue' }),
463
+ h('p', { className: 'text-[11px] text-gray-500 mt-1.5 leading-relaxed' }, '레퍼런슀 포즈λ₯Ό λ¬Έμž₯으둜 λ°”κΏ” ν”„λ‘¬ν”„νŠΈ 맨 끝에 μ΅œμš°μ„  μ§€μ‹œλ‘œ λ„£μ–΄μš”. κ²°κ³Όκ°€ λ‚˜μ˜€λ©΄ μ•„λž˜ νŒ¨λ„μ—μ„œ μžλ™ μΆ”μΆœλœ λ¬Έμž₯을 ν™•μΈν•˜κ³ , ν‹€λ¦° 뢀뢄을 μ—¬κΈ°μ„œ 고쳐 λ‹€μ‹œ 생성할 수 μžˆμ–΄μš”.')),
464
+
465
+ h('section', null,
466
+ h(SectionTitle, null, '길이 Β· 핏'),
467
+ h('div', { className: 'flex gap-1.5 mb-3' },
468
+ DETAIL_GROUPS.map(g => h('button', {
469
+ key: g.key, type: 'button', onClick: () => setDetailTab(g.key),
470
+ className: `px-3 py-1.5 rounded-lg text-[12.5px] font-semibold transition-colors ${detailTab === g.key
471
+ ? 'bg-brand-blue text-white'
472
+ : (images[g.key] ? 'bg-[#2a2a2a] text-gray-200 hover:bg-[#333]' : 'bg-[#242424] text-gray-500 hover:text-gray-300')}`
473
+ }, g.label, images[g.key] ? h('span', { className: `ml-1.5 inline-block w-1.5 h-1.5 rounded-full align-middle ${detailTab === g.key ? 'bg-white' : 'bg-brand-blue'}` }) : null))),
474
+ (() => {
475
+ const g = DETAIL_GROUPS.find(x => x.key === detailTab);
476
+ const rows = [['길이', g.length], ['핏', g.fit]];
477
+ return h('div', { key: g.key, className: 'space-y-2 animate-fadeIn' },
478
+ rows.map(([label, k]) => h('div', { key: k, className: 'grid grid-cols-[52px_1fr] items-center gap-2' },
479
+ h('span', { className: 'text-[12px] text-gray-400' }, label),
480
+ h('div', { className: 'flex flex-wrap gap-1.5' },
481
+ DETAIL_OPTIONS[k].options.map(o => h('button', {
482
+ key: o, type: 'button', onClick: () => setDetails(d => ({ ...d, [k]: o })),
483
+ className: `px-3 py-1.5 rounded-lg text-[12.5px] font-medium border transition-colors ${details[k] === o
484
+ ? 'bg-brand-blue border-brand-blue text-white'
485
+ : 'bg-[#242424] border-[#333] text-gray-300 hover:border-[#4b5563] hover:text-white'}`
486
+ }, o))))),
487
+ !images[g.key] && h('p', { className: 'text-[11px] text-gray-500 pt-1' }, `${g.label} 이미지λ₯Ό μ˜¬λ¦¬μ§€ μ•ŠμœΌλ©΄ 이 섀정은 μ‚¬μš©λ˜μ§€ μ•Šμ•„μš”.`));
488
+ })()),
489
+
490
+ h('section', null,
491
+ h(SectionTitle, { right: h('span', { className: `text-[11px] ${detailCount >= DETAIL_MAX ? 'text-amber-400' : 'text-gray-500'}` }, `선택 Β· ${detailCount}/${DETAIL_MAX}μž₯`) }, 'λ””ν…ŒμΌ μ°Έμ‘°'),
492
+ health?.ok && health.detailCuts === false
493
+ ? h('p', { className: 'text-[11.5px] text-gray-500' }, 'ν˜„μž¬ 배포된 μ›Œν¬ν”Œλ‘œμš°(workflow_api.json)에 λ””ν…ŒμΌ μ°Έμ‘° μž…λ ₯이 μ—†μ–΄ μ‚¬μš©ν•  수 μ—†μ–΄μš”. v5 μ›Œν¬ν”Œλ‘œμš°λ₯Ό Export (API)ν•΄μ„œ κ΅μ²΄ν•΄μ£Όμ„Έμš”.')
494
+ : h(React.Fragment, null,
495
+ h('p', { className: 'text-[11px] text-gray-500 mb-2.5 leading-relaxed' }, 'ν΄λ‘œμ¦ˆμ—…μ„ 올리고 μ–΄λ–€ λΆ€μœ„μΈμ§€ κ³¨λΌμ£Όμ„Έμš” (옷 μ’…λ₯˜λ³„λ‘œ ν•­λͺ©μ΄ λ‹¬λΌμš”). μ‘°μ§κ°Β·μ†Œμž¬λŠ” 옷 전체에, λ‚˜λ¨Έμ§€λŠ” κ·Έ λΆ€μœ„μ—λ§Œ λ°˜μ˜ν•˜κ³  싀루엣은 메인 사진 κ·ΈλŒ€λ‘œ μœ μ§€ν•˜λ„λ‘ μ „λ‹¬λΌμš”. μ°Έμ‘°κ°€ 많으면 정확도가 λ–¨μ–΄μ Έμ„œ 전체 4μž₯κΉŒμ§€λ§Œ.'),
496
+ h('div', { className: 'grid grid-cols-2 gap-x-4 gap-y-2.5' },
497
+ DETAIL_GARMENTS.map(g => {
498
+ const enabled = !!images[g.key];
499
+ return h('div', { key: g.key, className: 'flex items-center gap-2' },
500
+ h('span', { className: `w-14 shrink-0 text-[12px] ${enabled ? 'text-gray-300' : 'text-gray-600'}`, title: enabled ? '' : `${g.label} 이미지λ₯Ό λ¨Όμ € μ˜¬λ €μ£Όμ„Έμš”` }, g.label),
501
+ DETAIL_SLOTS.map(slot => {
502
+ const id = `${g.key}:${slot}`;
503
+ const cur = images[`detail:${id}`];
504
+ const kind = kindOf(g.key, slot);
505
+ const kindList = DETAIL_KINDS_BY_GARMENT[g.key] || [];
506
+ const kindObj = kindList.find(k => k.key === kind) || kindList[0];
507
+ return h('div', { key: slot, className: 'w-16 flex flex-col items-center gap-1' },
508
+ h(DetailTile, { value: cur, disabled: !enabled || (!cur && detailCount >= DETAIL_MAX), onChange: (v, name) => setImg(`detail:${id}`, v, name) }),
509
+ // μ’…λ₯˜ 선택 μΉ© β€” λ„€μ΄ν‹°λΈŒ select λ₯Ό λ²„νŠΌμ²˜λŸΌ 보이게 (appearance-none + μ»€μŠ€ν…€ ν™”μ‚΄ν‘œ)
510
+ h('div', { className: 'relative w-full', title: enabled ? `${kindObj.label} Β· ν΄λ¦­ν•΄μ„œ λΆ€μœ„ λ³€κ²½` : '' },
511
+ h('select', {
512
+ value: kind, disabled: !enabled,
513
+ onChange: e => setDetailKinds(prev => ({ ...prev, [id]: e.target.value })),
514
+ style: { appearance: 'none', WebkitAppearance: 'none', MozAppearance: 'none' },
515
+ className: `w-full h-6 rounded-md border text-[10.5px] font-medium pl-1.5 pr-5 cursor-pointer focus:outline-none focus:border-brand-blue transition-colors
516
+ ${cur ? 'bg-brand-blue/15 border-brand-blue/60 text-blue-200 hover:bg-brand-blue/25'
517
+ : 'bg-[#2a2a2a] border-[#3f3f3f] text-gray-300 hover:border-[#5a5a5a] hover:bg-[#303030]'}
518
+ disabled:opacity-40 disabled:cursor-default`
519
+ }, kindList.map(k => h('option', { key: k.key, value: k.key, className: 'bg-[#242424] text-gray-200' }, k.short))),
520
+ h(ChevronDown, { size: 12, className: `absolute right-1 top-1/2 -translate-y-1/2 pointer-events-none ${cur ? 'text-blue-200' : 'text-gray-400'}` })));
521
+ }));
522
+ })))),
523
+
524
+ h('div', { className: 'pt-3 pb-3 sticky bottom-0 bg-[#1e1e1e] border-t border-[#2a2a2a] -mx-5 px-5' },
525
+ missing.length > 0 && h('p', { className: 'text-[11.5px] text-gray-500 mb-2' }, `ν•„μš”: ${missing.join(', ')}`),
526
+ activeJobs.length > 0 && missing.length === 0 && h('p', { className: 'text-[11.5px] text-gray-500 mb-2' }, `${activeJobs.length}건 μ§„ν–‰ 쀑 β€” 섀정을 λ°”κΏ” λ°”λ‘œ λ‹€μŒ 컷을 κ±Έμ–΄λ‘˜ 수 μžˆμ–΄μš”`),
527
+ h('button', { type: 'button', onClick: handleGenerate, disabled: !canGenerate,
528
+ className: `w-full h-12 rounded-xl font-semibold text-[14px] flex items-center justify-center gap-2 transition-colors ${canGenerate ? 'bg-brand-blue hover:bg-brand-hover text-white' : 'bg-[#2a2a2a] text-gray-500 cursor-not-allowed'}` },
529
+ h(Sparkles, { size: 16 }),
530
+ activeJobs.length > 0 ? `룩뢁 생성 (${activeJobs.length}건 μ§„ν–‰ 쀑)` : '룩뢁 생성'))));
531
+
532
+ // ── Right: result ─────────────────────────────────────────
533
+ const right = h('main', { className: 'flex-1 h-full overflow-y-auto' },
534
+ h('div', { className: 'max-w-5xl mx-auto p-6 lg:p-8' },
535
+ !health?.ok && health && h('div', { className: 'mb-5 rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-[13px] text-amber-200 flex gap-2' },
536
+ h(AlertTriangle, { size: 16, className: 'shrink-0 mt-0.5' }), h('span', null, health.error || 'Comfy λΈŒλ¦¬μ§€ 섀정을 ν™•μΈν•΄μ£Όμ„Έμš”.')),
537
+ health?.ok && health.loginRequired === false && h('div', { className: 'mb-5 rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-[13px] text-amber-200 flex gap-2' },
538
+ h(AlertTriangle, { size: 16, className: 'shrink-0 mt-0.5' }), h('span', null, 'HF OAuthκ°€ μ—°κ²°λ˜μ§€ μ•Šμ•„ 둜그인 없이 λˆ„κ΅¬λ‚˜ 생성할 수 μžˆλŠ” μƒνƒœμž…λ‹ˆλ‹€. README의 hf_oauth μ„€μ •κ³Ό Space μž¬μ‹œμž‘μ„ ν™•μΈν•΄μ£Όμ„Έμš”.')),
539
+ error && h('div', { className: 'mb-5 rounded-xl border border-red-500/40 bg-red-500/10 px-4 py-3 text-[13px] text-red-200 flex gap-2 animate-fadeIn' },
540
+ h(AlertTriangle, { size: 16, className: 'shrink-0 mt-0.5' }), h('span', { className: 'break-all' }, error)),
541
+
542
+ jobs.length > 0 && h('div', { className: 'mb-5 rounded-xl border border-[#2a2a2a] bg-[#202020] overflow-hidden animate-fadeIn' },
543
+ h('div', { className: 'px-4 py-2.5 border-b border-[#2a2a2a] text-[12.5px] font-semibold text-gray-300 flex items-center gap-2' },
544
+ h(RefreshCw, { size: 13, className: activeJobs.length ? 'animate-spin text-brand-blue' : 'text-gray-500' }),
545
+ `μ§„ν–‰ 쀑 ${activeJobs.length}건`, jobs.length - activeJobs.length > 0 ? h('span', { className: 'text-red-300 font-normal' }, ` Β· μ‹€νŒ¨ ${jobs.length - activeJobs.length}건`) : null),
546
+ jobs.map((j, i) => h('div', { key: j.id, className: `px-4 py-2.5 flex items-center gap-3 text-[12.5px] ${i > 0 ? 'border-t border-[#262626]' : ''}` },
547
+ h('div', { className: `w-1.5 h-1.5 rounded-full shrink-0 ${j.error ? 'bg-red-400' : 'bg-brand-blue pulse-ring relative'}` }),
548
+ h('div', { className: 'flex-1 min-w-0' },
549
+ h('div', { className: 'text-gray-100 truncate' }, `${j.meta.face} Β· ${j.meta.shot} Β· ${j.meta.angle} Β· ${j.meta.gaze}`, j.meta.prompt ? h('span', { className: 'text-gray-500' }, ` Β· "${j.meta.prompt}"`) : null),
550
+ h('div', { className: j.error ? 'text-red-300 break-all' : 'text-gray-400' },
551
+ j.error ? j.error : (j.execStartedAt ? `${j.stageLabel} Β· ${fmtSec((Date.now() - j.execStartedAt) / 1000)}` : `${j.stageLabel} Β· λŒ€κΈ° ${fmtSec((Date.now() - j.startedAt) / 1000)}`))),
552
+ j.error
553
+ ? h('button', { type: 'button', title: 'μ§€μš°κΈ°', onClick: () => dismissJob(j.id), className: 'text-gray-500 hover:text-white' }, h(X, { size: 14 }))
554
+ : h('button', { type: 'button', title: 'μž‘μ—… μ·¨μ†Œ', disabled: j.cancelling, onClick: () => cancelJob(j),
555
+ className: 'shrink-0 text-[11.5px] px-2.5 py-1 rounded-lg border border-[#3a3a3a] text-gray-400 hover:text-red-300 hover:border-red-400/50 disabled:opacity-50 transition-colors' },
556
+ j.cancelling ? 'μ·¨μ†Œ 쀑…' : 'μ·¨μ†Œ')))),
557
+
558
+ h('div', { className: 'grid grid-cols-1 md:grid-cols-[minmax(0,1fr)_200px] gap-6' },
559
+ // 메인 λ·°μ–΄
560
+ h('div', { className: 'rounded-2xl bg-[#202020] border border-[#2a2a2a] overflow-hidden relative', style: { minHeight: '60vh' } },
561
+ !current && activeJobs.length > 0
562
+ ? h('div', { className: 'absolute inset-0 flex flex-col items-center justify-center gap-5' },
563
+ h('div', { className: 'shimmer absolute inset-0 opacity-60' }),
564
+ h('div', { className: 'relative pulse-ring w-14 h-14 rounded-full bg-brand-blue/20 flex items-center justify-center' }, h(Sparkles, { size: 22, className: 'text-brand-blue' })),
565
+ h('div', { className: 'relative text-center' },
566
+ h('div', { className: 'text-[15px] font-semibold text-gray-100' }, activeJobs[0].stageLabel),
567
+ h('div', { className: 'mt-1 text-[12.5px] text-gray-400 flex items-center justify-center gap-1' }, h(Clock, { size: 12 }),
568
+ activeJobs[0].execStartedAt ? `${fmtSec((Date.now() - activeJobs[0].execStartedAt) / 1000)} κ²½κ³Ό Β· 보톡 1~2λΆ„ μ†Œμš”` : 'μ‹€ν–‰ μˆœμ„œλ₯Ό κΈ°λ‹€λ¦¬λŠ” 쀑')),
569
+ h('p', { className: 'relative text-[11.5px] text-gray-500 max-w-xs text-center' }, '이 탭을 λ‹«μ§€ λ§ˆμ„Έμš”. 생성이 λλ‚˜λ©΄ 여기에 이미지가 ν‘œμ‹œλ©λ‹ˆλ‹€.'))
570
+ : current
571
+ ? h('div', { className: 'animate-fadeIn flex flex-col' },
572
+ h('div', { className: 'flex justify-center bg-[#1c1c1c]' },
573
+ h('div', { className: 'relative inline-block' },
574
+ h('img', { src: current.imageUrl, onClick: () => setLightbox(true), title: 'ν΄λ¦­ν•˜λ©΄ 크게 보기',
575
+ className: 'max-h-[78vh] w-auto max-w-full block bg-white cursor-zoom-in', alt: '생성 κ²°κ³Ό' }),
576
+ aiLabel && h('div', { className: 'ai-label-overlay' }, AI_LABEL_TEXT),
577
+ h('button', { type: 'button', onClick: () => setLightbox(true), title: '크게 보기',
578
+ className: 'absolute bottom-3 right-3 w-9 h-9 rounded-lg bg-black/55 hover:bg-black/75 text-white flex items-center justify-center' }, h(Maximize2, { size: 16 })))),
579
+ h('div', { className: 'flex items-center justify-between gap-3 px-4 py-3 border-t border-[#2a2a2a]' },
580
+ h('label', { className: 'flex items-center gap-2 cursor-pointer select-none text-[12.5px] text-gray-300' },
581
+ h('button', { type: 'button', role: 'switch', 'aria-checked': aiLabel, onClick: () => setAiLabel(v => !v),
582
+ className: `relative w-9 h-5 rounded-full transition-colors ${aiLabel ? 'bg-brand-blue' : 'bg-[#3a3a3a]'}` },
583
+ h('span', { className: `absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${aiLabel ? 'translate-x-4' : ''}` })),
584
+ h('span', null, "'AI 생성 이미지' ν‘œκΈ°"),
585
+ h('span', { className: 'text-gray-500' }, aiLabel ? 'ν™”λ©΄Β·λ‹€μš΄λ‘œλ“œμ— 포함' : 'ν‘œκΈ° μ—†μŒ')),
586
+ h('button', { type: 'button', onClick: () => downloadWithLabel(current.imageUrl, `clovis_${current.meta.shot}_${current.meta.angle}_${current.id}.png`, aiLabel),
587
+ className: 'h-10 px-4 rounded-xl bg-brand-blue hover:bg-brand-hover text-white text-[13px] font-semibold flex items-center gap-1.5' }, h(Download, { size: 15 }), 'λ‹€μš΄λ‘œλ“œ')))
588
+ : h('div', { className: 'absolute inset-0 flex flex-col items-center justify-center text-gray-500 gap-2' },
589
+ h(Upload, { size: 28, className: 'opacity-50' }),
590
+ h('p', { className: 'text-[13.5px]' }, 'μ™Όμͺ½μ—μ„œ μ–Όκ΅΄Β·μ˜μƒμ„ κ³ λ₯΄κ³  룩뢁 생성을 λˆ„λ₯΄λ©΄'),
591
+ h('p', { className: 'text-[13.5px]' }, 'ν•œ λ²ˆμ— λͺ¨λΈμ»·μ΄ μƒμ„±λ©λ‹ˆλ‹€.'))),
592
+ // νžˆμŠ€ν† λ¦¬
593
+ h('div', null,
594
+ h('h3', { className: 'text-[13px] font-semibold text-gray-300 mb-2.5' }, `이번 μ„Έμ…˜ κ²°κ³Ό ${results.length ? `(${results.length})` : ''}`),
595
+ results.length === 0
596
+ ? h('p', { className: 'text-[12px] text-gray-500' }, '아직 μ—†μŒ')
597
+ : h('div', { className: 'grid grid-cols-3 md:grid-cols-1 gap-2' },
598
+ results.map(r => h('button', { key: r.id, type: 'button', onClick: () => setCurrent(r),
599
+ className: `relative rounded-xl overflow-hidden border-2 ${current?.id === r.id ? 'border-brand-blue' : 'border-transparent hover:border-[#4b5563]'}` },
600
+ h('img', { src: r.imageUrl, className: 'w-full h-auto block bg-white' }),
601
+ h('div', { className: 'absolute bottom-0 inset-x-0 px-2 py-1 bg-black/65 text-[10.5px] text-left leading-tight' },
602
+ h('div', null, `${r.meta.face ? r.meta.face + ' Β· ' : ''}${r.meta.shot} Β· ${r.meta.angle}`),
603
+ h('div', { className: 'text-gray-300' }, `${r.meta.gaze} Β· ${fmtSec(r.elapsedSec)}`))))))),
604
+
605
+ current && h('div', { className: 'mt-5 text-[12px] text-gray-500' },
606
+ `${current.meta.age} Β· ${current.meta.shot} Β· ${current.meta.angle} Β· ${current.meta.gaze}`, current.meta.prompt ? ` Β· "${current.meta.prompt}"` : ''),
607
+ current && (current.garmentSpecs || current.finalPrompt || current.poseSpec) && h('div', { className: 'mt-3 rounded-xl border border-[#2a2a2a] bg-[#202020]' },
608
+ h('button', { type: 'button', onClick: () => setShowSpecs(v => !v), className: 'w-full flex items-center justify-between px-4 py-2.5 text-[12.5px] font-semibold text-gray-300 hover:text-white' },
609
+ h('span', null, '포즈 뢄석 Β· μ˜μƒ 뢄석 Β· μ΅œμ’… ν”„λ‘¬ν”„νŠΈ'), h('span', { className: 'text-gray-500 font-normal' }, showSpecs ? 'μ ‘κΈ°' : '펼치기')),
610
+ showSpecs && h('div', { className: 'px-4 pb-4 space-y-3 animate-fadeIn' },
611
+ current.poseSpec && h('div', null,
612
+ h('div', { className: 'flex items-center justify-between mb-1' },
613
+ h('div', { className: 'text-[11px] text-gray-500' }, '포즈 뢄석 (레퍼런슀 β†’ λ¬Έμž₯, ν”„λ‘¬ν”„νŠΈ μ΅œμš°μ„  μ§€μ‹œ)'),
614
+ h('button', { type: 'button', onClick: () => { setPoseSpec(current.poseSpec); document.querySelector('aside')?.scrollTo({ top: 0, behavior: 'smooth' }); },
615
+ className: 'text-[11px] text-brand-blue hover:underline' }, '이 λ¬Έμž₯을 μˆ˜μ •ν•΄μ„œ λ‹€μ‹œ 생성')),
616
+ h('pre', { className: 'text-[11.5px] text-gray-200 whitespace-pre-wrap break-words bg-[#1a1a1a] rounded-lg p-3 max-h-40 overflow-y-auto' }, current.poseSpec)),
617
+ current.garmentSpecs && h('div', null,
618
+ h('div', { className: 'text-[11px] text-gray-500 mb-1' }, 'GPT λΉ„μ „ μ˜μƒ 뢄석 (GARMENT SPECS)'),
619
+ h('pre', { className: 'text-[11.5px] text-gray-200 whitespace-pre-wrap break-words bg-[#1a1a1a] rounded-lg p-3 max-h-48 overflow-y-auto' }, current.garmentSpecs)),
620
+ current.finalPrompt && h('div', null,
621
+ h('div', { className: 'text-[11px] text-gray-500 mb-1' }, 'GPT-image에 μ „λ‹¬λœ μ΅œμ’… ν”„λ‘¬ν”„νŠΈ'),
622
+ h('pre', { className: 'text-[11.5px] text-gray-300 whitespace-pre-wrap break-words bg-[#1a1a1a] rounded-lg p-3 max-h-64 overflow-y-auto' }, current.finalPrompt))))));
623
+
624
+ // ── Header ────────────────────────────────────────────────
625
+ const header = h('header', { className: 'h-14 shrink-0 border-b border-[#2a2a2a] bg-[#1a1a1a] flex items-center justify-between px-5' },
626
+ h('div', { className: 'flex items-center gap-5' },
627
+ h('div', { className: 'flex items-center gap-3' },
628
+ h('div', { className: 'w-8 h-8 rounded-lg bg-brand-blue flex items-center justify-center' }, h(Sparkles, { size: 16, className: 'text-white' })),
629
+ h('div', { className: 'text-[15px] font-bold tracking-tight' }, 'CLOVIS AI 룩뢁 생성기')),
630
+ user.oauth_enabled && h('div', { className: 'flex items-center gap-2 text-[12.5px] pl-5 border-l border-[#2a2a2a]' },
631
+ user.is_logged_in
632
+ ? h(React.Fragment, null,
633
+ h('span', { className: 'text-gray-300' }, user.name || user.username),
634
+ h('a', { href: user.logout_url, className: 'text-gray-500 hover:text-white' }, 'λ‘œκ·Έμ•„μ›ƒ'))
635
+ : h('a', { href: user.login_url, className: 'px-3 py-1.5 rounded-lg bg-[#2a2a2a] hover:bg-[#333] text-gray-100' }, 'πŸ€— Hugging Face둜 둜그인'))),
636
+ h('div', null,
637
+ health && !health.ok && h('span', { className: 'inline-flex items-center gap-1.5 text-[12.5px] text-amber-400' },
638
+ h('span', { className: 'w-1.5 h-1.5 rounded-full bg-amber-400' }), 'Comfy μ„€μ • ν•„μš”')));
639
+
640
+ const lightboxEl = lightbox && current && h('div', {
641
+ className: 'fixed inset-0 z-50 bg-black/90 flex items-center justify-center animate-fadeIn cursor-zoom-out',
642
+ onClick: () => setLightbox(false) },
643
+ h('img', { src: current.imageUrl, alt: '생성 κ²°κ³Ό ν™•λŒ€', onClick: e => e.stopPropagation(),
644
+ className: 'max-w-[96vw] max-h-[96vh] object-contain bg-white cursor-default shadow-2xl' }),
645
+ aiLabel && h('div', { className: 'absolute top-4 right-16 text-[12px] text-gray-300 font-light pointer-events-none' }, AI_LABEL_TEXT),
646
+ h('button', { type: 'button', onClick: () => setLightbox(false), title: 'λ‹«κΈ° (Esc)',
647
+ className: 'absolute top-4 right-4 w-10 h-10 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center' }, h(X, { size: 18 })),
648
+ h('div', { className: 'absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2', onClick: e => e.stopPropagation() },
649
+ h('button', { type: 'button', onClick: () => downloadWithLabel(current.imageUrl, `clovis_${current.meta.shot}_${current.meta.angle}_${current.id}.png`, aiLabel),
650
+ className: 'h-10 px-4 rounded-xl bg-brand-blue hover:bg-brand-hover text-white text-[13px] font-semibold flex items-center gap-1.5' }, h(Download, { size: 15 }), 'λ‹€μš΄λ‘œλ“œ')));
651
+
652
+ return h('div', { className: 'h-screen flex flex-col bg-[#1a1a1a]' }, header,
653
+ h('div', { className: 'flex-1 flex flex-col lg:flex-row min-h-0' }, left, right), lightboxEl);
654
+ }
655
+
656
+ ReactDOM.createRoot(document.getElementById('root')).render(h(App));
657
+ </script>
658
+ </body>
659
+ </html>