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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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+EDEgn92kkKAAD4YSQAAAADAAAAGAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAMAAAAAABgAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAAADAAAAGAAAADAAAACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAAAGAAAAMAAAAIABAAAADAAAAGAAAADAAAAAAAYAAAAwAAAAgAEAA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ACAAQAAAAwAAABgAAAAAAMAAAAYAAAAwAAAAIABAAAADAAAAGAAAAAAAwAAABgAAADAAAAAAAYAAAAwAAAAgAEAAAAMAAAAYAAAAMAAAAAABgAAALhlAZ8nCv2Z0MRzAAAAAElFTkSuQmCC"
|
| 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 |
+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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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>
|