sunyoung00 commited on
Commit
22db8fa
·
verified ·
1 Parent(s): 343637d

Delete comfy_routes.py

Browse files
Files changed (1) hide show
  1. comfy_routes.py +0 -330
comfy_routes.py DELETED
@@ -1,330 +0,0 @@
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
- }
48
-
49
-
50
- def _parse_data_url(data_url: Optional[str]) -> Optional[bytes]:
51
- if not data_url or not isinstance(data_url, str):
52
- return None
53
- if data_url.startswith("data:") and ";base64," in data_url:
54
- return base64.b64decode(data_url.split(";base64,", 1)[1])
55
- return None
56
-
57
-
58
- def _safe_name(name: Optional[str], fallback: str) -> str:
59
- """원본 파일명은 최대한 유지하되 HF 경로에 안전하게 (server._sanitize_upload_filename 과 동일 규칙)."""
60
- raw = (name or "").strip() if isinstance(name, str) else ""
61
- base = os.path.basename(raw.replace("\\", "/")) if raw else ""
62
- if not base or base in (".", ".."):
63
- return fallback
64
- cleaned = re.sub(r"[^\w.\-가-힣]+", "_", base, flags=re.UNICODE).strip("._") or fallback
65
- cleaned = cleaned.replace("..", "_")
66
- if len(cleaned) > 120:
67
- stem, ext = os.path.splitext(cleaned)
68
- cleaned = stem[:100] + ext[:20]
69
- return cleaned
70
-
71
-
72
- def _update(job_id: str, **kw) -> None:
73
- with _JOBS_LOCK:
74
- if job_id in _JOBS:
75
- _JOBS[job_id].update(kw)
76
-
77
-
78
- def _gc_jobs() -> None:
79
- now = time.time()
80
- with _JOBS_LOCK:
81
- for jid in [j for j, v in _JOBS.items() if v.get("finished_at") and now - v["finished_at"] > _JOB_TTL_SEC]:
82
- _JOBS.pop(jid, None)
83
-
84
-
85
- def build_comfy_router(
86
- get_current_user: Callable[[Request], dict],
87
- require_login: Callable[[dict], None],
88
- face_preset_cache: Dict[str, dict],
89
- push_to_hub_background: Optional[Callable] = None,
90
- ) -> APIRouter:
91
- router = APIRouter(prefix="/api/comfy")
92
-
93
- def _run_pipeline(job_id: str, payload: dict, user: dict) -> None:
94
- started = time.time()
95
- with _SEM:
96
- try:
97
- uploads = payload.get("images") or {}
98
- combos = {k: v for k, v in (payload.get("options") or {}).items() if v}
99
- if not uploads.get("pose") and combos.get("shot") == "레퍼런스 구도 그대로":
100
- raise cc.ComfyError("'레퍼런스 구도 그대로'를 선택하면 레퍼런스 포즈 이미지가 필요합니다.")
101
- if not any(_parse_data_url(uploads.get(k)) for k in ("outer", "top", "bottom")):
102
- raise cc.ComfyError("아우터·상의·하의 중 최소 한 개의 의상 이미지가 필요합니다.")
103
-
104
- _update(job_id, stage="uploading")
105
- images: Dict[str, str] = {}
106
-
107
- # ── 얼굴: 프리셋 id 또는 업로드 data URL ──
108
- face = payload.get("face")
109
- face_bytes: Optional[bytes] = None
110
- if isinstance(face, str) and face.startswith("preset_") and face in face_preset_cache:
111
- face_bytes = base64.b64decode(face_preset_cache[face]["data"])
112
- else:
113
- face_bytes = _parse_data_url(face)
114
- if not face_bytes:
115
- raise cc.ComfyError("얼굴 프리셋을 선택하거나 얼굴 이미지를 업로드해주세요.")
116
- images["face"] = cc.ensure_uploaded(face_bytes, "face")
117
-
118
- # ── 의상/배경/포즈 슬롯 ──
119
- for key in ["outer", "top", "bottom", "shoes", "inner", "belt", "pose"]:
120
- b = _parse_data_url(uploads.get(key))
121
- images[key] = cc.ensure_uploaded(b, key) if b else cc.ensure_uploaded(cc.placeholder_image_bytes("blank"), f"{key}-empty")
122
- # 디테일 참조(조직감/로고): 최대 4장, v5 워크플로우일 때만 (아니면 조용히 무시)
123
- details_in = payload.get("details") if isinstance(payload.get("details"), list) else []
124
- details: list = []
125
- if cc.supports_detail_cuts():
126
- for item in details_in[:4]:
127
- if not isinstance(item, dict):
128
- continue
129
- b = _parse_data_url(item.get("image"))
130
- if not b or not uploads.get(item.get("garment")):
131
- continue # 주컷 없는 의상의 디테일은 무시
132
- details.append({"name": cc.ensure_uploaded(b, f"detail:{item.get('garment')}:{item.get('kind')}"),
133
- "garment": item.get("garment"), "kind": item.get("kind") or "texture",
134
- "image": item.get("image"), "filename": item.get("filename")})
135
- detail_count = len(details)
136
- bg = _parse_data_url(uploads.get("background"))
137
- if not bg and os.path.exists("background.png"):
138
- with open("background.png", "rb") as f:
139
- bg = f.read()
140
- images["background"] = cc.ensure_uploaded(bg, "background") if bg else cc.ensure_uploaded(cc.placeholder_image_bytes("studio"), "background-empty")
141
- images["_blank"] = cc.ensure_blank_slot_uploaded()
142
-
143
- prompt = (payload.get("prompt") or "").strip()
144
-
145
- _update(job_id, stage="submitting")
146
- quality = payload.get("quality") if payload.get("quality") in ("low", "medium", "high") else None
147
- wf = cc.build_workflow(images, combos, prompt, details, quality, has_pose=bool(uploads.get("pose")))
148
- prompt_id = cc.submit(wf)
149
- _update(job_id, stage="submitted", promptId=prompt_id)
150
- print(f"[COMFY] job {job_id} → prompt_id {prompt_id} (user={user.get('username')})")
151
-
152
- def on_status(st: str) -> None:
153
- patch = {"stage": st if st in STAGE_LABEL else "executing", "comfyStatus": st}
154
- with _JOBS_LOCK:
155
- started = _JOBS.get(job_id, {}).get("exec_started_at")
156
- # 실제 워크플로우 실행이 시작된 시점(대기열·GPU 준비 제외)부터 소요시간을 잰다
157
- if st not in ("submitted", "queued_waiting", "queued_limited", "preparing") and not started:
158
- patch["exec_started_at"] = time.time()
159
- _update(job_id, **patch)
160
-
161
- img_bytes = cc.wait_for_result(prompt_id, on_status=on_status)
162
- texts = cc.job_texts(prompt_id) # v6~: 의상 분석 결과 / 최종 프롬프트
163
- if texts.get("garment_specs"):
164
- print(f"[COMFY] job {job_id} garment specs: {texts['garment_specs'][:300]}")
165
- _update(job_id, stage="downloading", garmentSpecs=texts.get("garment_specs"), finalPrompt=texts.get("final_prompt"))
166
- b64 = base64.b64encode(img_bytes).decode("utf-8")
167
- data_url = f"data:image/png;base64,{b64}"
168
- with _JOBS_LOCK:
169
- exec_started = _JOBS.get(job_id, {}).get("exec_started_at") or started
170
- elapsed = round(time.time() - exec_started, 1) # 순수 생성 시간
171
- waited = round(exec_started - started, 1) # 업로드+대기열 시간
172
- _update(job_id, waitedSec=waited)
173
- _update(job_id, status="done", stage="done", imageUrl=data_url, elapsedSec=elapsed, finished_at=time.time())
174
- print(f"[COMFY] job {job_id} done in {elapsed}s ({len(img_bytes):,} bytes)")
175
-
176
- # ── HF Dataset 기록 (기존 로직 재사용, 실패해도 무시) ──
177
- if push_to_hub_background:
178
- try:
179
- now = datetime.datetime.now()
180
- ts = now.strftime("%Y%m%d_%H%M%S_%f")[:-3]
181
- names = payload.get("imageFilenames") if isinstance(payload.get("imageFilenames"), dict) else {}
182
- garment_keys = ["outer", "top", "bottom", "shoes", "inner", "belt"]
183
- present = [k for k in garment_keys if uploads.get(k)]
184
- product_b64 = [uploads[k] for k in present] + [x["image"] for x in details]
185
- product_names = [_safe_name(names.get(k), f"{k}.png") for k in present] + \
186
- [_safe_name(x.get("filename"), f"{x['garment']}_{x['kind']}.png") for x in details]
187
- ref_keys = [k for k in ("background", "pose") if uploads.get(k)]
188
- ref_b64 = [uploads[k] for k in ref_keys]
189
- ref_names = [_safe_name(names.get(k), f"{k}.png") for k in ref_keys]
190
- is_preset = isinstance(face, str) and face.startswith("preset_")
191
- face_filename = f"{face}.png" if is_preset else _safe_name(payload.get("faceFilename"), "face_upload.png")
192
- push_to_hub_background(
193
- record={
194
- "timestamp": now.strftime("%Y-%m-%d %H:%M:%S"), "ts": ts,
195
- "app": "spao-comfy-lookbook", "engine": "comfy-cloud",
196
- "shot_label": combos.get("shot", ""), "camera_angle": combos.get("angle", ""),
197
- "gaze": combos.get("gaze", ""), "age_group": combos.get("age", ""),
198
- "user_username": user.get("username"), "user_name": user.get("name"),
199
- "user_email": user.get("email"), "user_logged_in": user.get("is_logged_in"),
200
- "custom_prompt": prompt or "(none)", "comfy_prompt_id": prompt_id, "mode": "COMFY",
201
- "model_face": face if is_preset else "user_upload", "model_face_filename": face_filename,
202
- "has_reference": bool(uploads.get("pose")), "has_background": bool(uploads.get("background")),
203
- "elapsed_sec": elapsed, "elapsed_ms": int(elapsed * 1000), "waited_sec": waited,
204
- "product_image_filenames": product_names,
205
- "slot_filenames": {k: _safe_name(names.get(k), f"{k}.png") for k in present + ref_keys},
206
- "options": combos, "detail_refs": [{"garment": x["garment"], "kind": x["kind"]} for x in details],
207
- "garment_specs": texts.get("garment_specs"), "final_prompt": texts.get("final_prompt"),
208
- "gpt_quality": quality or "workflow-default",
209
- },
210
- image_bytes=img_bytes, ts=ts,
211
- product_images_b64=product_b64, product_filenames=product_names,
212
- face_b64=base64.b64encode(face_bytes).decode("utf-8"), face_filename=face_filename,
213
- sub_product_images_b64=ref_b64, sub_product_filenames=ref_names,
214
- )
215
- except Exception as hub_err:
216
- print(f"[HUB] comfy push failed: {hub_err}")
217
- except cc.ComfyError as e:
218
- print(f"[COMFY] job {job_id} error: {e}")
219
- _update(job_id, status="error", stage="error", error=str(e), finished_at=time.time())
220
- except Exception as e: # noqa: BLE001
221
- traceback.print_exc()
222
- _update(job_id, status="error", stage="error", error=f"예기치 못한 오류: {str(e)[:200]}", finished_at=time.time())
223
-
224
- def _prewarm() -> None:
225
- """서버 시작 시 얼굴 프리셋·기본 배경·빈 슬롯 이미지를 미리 올려 첫 요청을 빠르게."""
226
- try:
227
- for pid, v in list(face_preset_cache.items()):
228
- cc.ensure_uploaded(base64.b64decode(v["data"]), f"preset:{pid}")
229
- if os.path.exists("background.png"):
230
- with open("background.png", "rb") as f:
231
- cc.ensure_uploaded(f.read(), "background")
232
- cc.ensure_uploaded(cc.placeholder_image_bytes("blank"), "empty-slot")
233
- cc.ensure_blank_slot_uploaded()
234
- print("[COMFY] prewarm done")
235
- except Exception as e: # noqa: BLE001
236
- print(f"[COMFY] prewarm skipped: {e}")
237
-
238
- if cc.API_KEY and os.environ.get("COMFY_PREWARM", "true").lower() in ("1", "true", "yes", "on"):
239
- threading.Thread(target=_prewarm, daemon=True).start()
240
-
241
- @router.get("/health")
242
- def comfy_health(request: Request):
243
- st = cc.workflow_status()
244
- user = get_current_user(request)
245
- st["oauthAttached"] = bool(user.get("is_logged_in")) or _oauth_attached()
246
- st["loginRequired"] = _login_required()
247
- return st
248
-
249
- def _oauth_attached() -> bool:
250
- try:
251
- import server # noqa: WPS433 — 런타임 상태 조회
252
- return bool(getattr(server, "_OAUTH_ATTACHED", False))
253
- except Exception:
254
- return False
255
-
256
- def _login_required() -> bool:
257
- try:
258
- import server
259
- return bool(getattr(server, "REQUIRE_LOGIN", True) and getattr(server, "_OAUTH_ATTACHED", False))
260
- except Exception:
261
- return False
262
-
263
- def _owner_of(request: Request, user: dict) -> str:
264
- """로그인 사용자는 계정명, 비로그인은 브라우저가 보내는 X-Client-Id 로 작업 소유자를 식별."""
265
- if user.get("is_logged_in") and user.get("username"):
266
- return f"user:{user['username']}"
267
- cid = (request.headers.get("x-client-id") or "").strip()[:64]
268
- return f"client:{cid}" if cid else "anonymous"
269
-
270
- def _job_view(job_id: str, snap: Dict[str, Any], with_image: bool = True) -> Dict[str, Any]:
271
- stage = snap.get("stage", "")
272
- return {
273
- "id": job_id,
274
- "status": snap.get("status"),
275
- "stage": stage,
276
- "stageLabel": STAGE_LABEL.get(stage, stage),
277
- "createdAt": int(snap["created_at"] * 1000),
278
- # elapsedSec: 워크플로우 실행 시작 이후 경과(대기 중이면 null). 완료 시엔 순수 생성 시간.
279
- "elapsedSec": snap.get("elapsedSec") if snap.get("status") == "done"
280
- else (round(time.time() - snap["exec_started_at"], 1) if snap.get("exec_started_at") else None),
281
- "execStartedAt": int(snap["exec_started_at"] * 1000) if snap.get("exec_started_at") else None,
282
- "waitedSec": snap.get("waitedSec"),
283
- "meta": snap.get("meta") or {},
284
- "imageUrl": snap.get("imageUrl") if with_image else None,
285
- "garmentSpecs": snap.get("garmentSpecs"),
286
- "finalPrompt": snap.get("finalPrompt"),
287
- "error": snap.get("error"),
288
- "promptId": snap.get("promptId"),
289
- }
290
-
291
- @router.get("/jobs")
292
- def comfy_list_jobs(request: Request):
293
- """이 사용자의 작업(진행 중 + 보관 기간 내 완료/실패)을 오래된 순으로 반환."""
294
- user = get_current_user(request)
295
- require_login(user)
296
- owner = _owner_of(request, user)
297
- _gc_jobs()
298
- with _JOBS_LOCK:
299
- items = [(jid, dict(v)) for jid, v in _JOBS.items() if v.get("owner") == owner]
300
- items.sort(key=lambda kv: kv[1]["created_at"])
301
- return {"jobs": [_job_view(jid, v) for jid, v in items]}
302
-
303
- @router.post("/generate")
304
- async def comfy_generate(request: Request, payload: Dict = Body(...)):
305
- user = get_current_user(request)
306
- require_login(user)
307
- st = cc.workflow_status()
308
- if not st["ok"]:
309
- raise HTTPException(status_code=500, detail=st["error"])
310
- if not st["api_key"]:
311
- raise HTTPException(status_code=500, detail="COMFY_CLOUD_API_KEY 가 설정되지 않았습니다.")
312
- _gc_jobs()
313
- job_id = uuid.uuid4().hex[:12]
314
- meta = payload.get("meta") if isinstance(payload.get("meta"), dict) else {}
315
- with _JOBS_LOCK:
316
- _JOBS[job_id] = {"status": "running", "stage": "queued_local", "created_at": time.time(),
317
- "user": user.get("username"), "owner": _owner_of(request, user), "meta": meta}
318
- threading.Thread(target=_run_pipeline, args=(job_id, payload, user), daemon=True).start()
319
- return {"jobId": job_id}
320
-
321
- @router.get("/jobs/{job_id}")
322
- def comfy_job(job_id: str):
323
- with _JOBS_LOCK:
324
- job = _JOBS.get(job_id)
325
- if job is None:
326
- raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다 (서버가 재시작되었을 수 있습니다).")
327
- snap = dict(job)
328
- return _job_view(job_id, snap)
329
-
330
- return router