Archived
downloads.py: streamed CivitAI downloads into the right ComfyUI folder, in-memory progress (polled), cancel, and local model deletion. Adapted from the legacy civitai.py — trimmed to download/cancel/delete and wired into the new hash index: - destination folder is derived from CivitAI's model type unless forced - finished downloads are hashed into the index (shows in /imagelab/hashes) - deletes drop the model from the index via hashing.forget() - skip-if-present so persistent-volume pods don't re-download - IMAGELAB_AUTO_DOWNLOAD env var: comma/newline list of version ids, CivitAI URLs, model:<id>, or <folder>::<entry> — queued on startup api.py: POST/GET/DELETE /imagelab/downloads + DELETE /imagelab/models/... hashing.py: forget() — remove a model's .index sidecar + in-memory entry __init__.py: queue startup downloads via the aiohttp on_startup hook Token via CIVITAI_TOKEN env var. Legacy civitai*.py / websocket.py left untouched as reference. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
107 lines
4.7 KiB
Python
107 lines
4.7 KiB
Python
"""
|
|
HTTP API surface for the rebuilt extension.
|
|
|
|
Registered on ComfyUI's PromptServer (aiohttp). Kept deliberately minimal —
|
|
routes get added back here piece by piece. Legacy `routes.py` /
|
|
`civitai_routes.py` are left untouched for reference, not loaded.
|
|
"""
|
|
from aiohttp import web
|
|
|
|
from server import PromptServer
|
|
|
|
from . import hashing
|
|
from . import downloads
|
|
|
|
|
|
def setup_routes() -> None:
|
|
"""Register API routes with the running ComfyUI server."""
|
|
routes = PromptServer.instance.routes
|
|
|
|
# ── model hash index ───────────────────────────────────────────────────
|
|
|
|
@routes.get("/imagelab/hashes")
|
|
async def get_hashes(request: web.Request) -> web.Response:
|
|
"""
|
|
Return the full model-hash cache in one shot:
|
|
|
|
{ "version": "<etag>", "models": [ {key, filename, hash, hashed_at}, ... ] }
|
|
|
|
`version` is a content token over every (key, hash) pair. Clients
|
|
should send it back via `If-None-Match`; when nothing has changed the
|
|
endpoint replies `304 Not Modified` with no body, so repeat loads are
|
|
essentially free. The payload itself is served straight from memory —
|
|
no per-request disk I/O.
|
|
"""
|
|
version, entries = hashing.get_snapshot()
|
|
etag = f'"{version}"'
|
|
|
|
if request.headers.get("If-None-Match") == etag:
|
|
return web.Response(status=304, headers={"ETag": etag})
|
|
|
|
return web.json_response(
|
|
{"version": version, "models": entries},
|
|
headers={"ETag": etag, "Cache-Control": "no-cache"},
|
|
)
|
|
|
|
# ── CivitAI downloads ──────────────────────────────────────────────────
|
|
|
|
@routes.post("/imagelab/downloads")
|
|
async def start_download(request: web.Request) -> web.Response:
|
|
"""
|
|
Start a CivitAI download.
|
|
|
|
body: { version_id: int, folder?: str, filename?: str }
|
|
|
|
`folder` is a ComfyUI folder name (e.g. "checkpoints"); omit it to let
|
|
the destination be derived from CivitAI's model type. Returns
|
|
immediately — the download runs in the background; poll
|
|
`GET /imagelab/downloads` for progress.
|
|
"""
|
|
try:
|
|
body = await request.json()
|
|
except Exception:
|
|
return web.json_response({"error": "Invalid JSON body", "code": "VALIDATION_ERROR"}, status=400)
|
|
|
|
version_id = body.get("version_id")
|
|
if version_id is None:
|
|
return web.json_response(
|
|
{"error": "version_id is required", "code": "VALIDATION_ERROR"},
|
|
status=400,
|
|
)
|
|
|
|
try:
|
|
downloads.start_download(int(version_id), body.get("folder"), body.get("filename"))
|
|
except downloads.CivitaiError as e:
|
|
return web.json_response({"error": e.message, "code": e.code}, status=e.status)
|
|
except (TypeError, ValueError):
|
|
return web.json_response({"error": "version_id must be an integer", "code": "VALIDATION_ERROR"}, status=400)
|
|
|
|
return web.json_response({"version_id": int(version_id), "status": "started"})
|
|
|
|
@routes.get("/imagelab/downloads")
|
|
async def list_downloads(request: web.Request) -> web.Response:
|
|
"""List every tracked download — active, completed, failed, cancelled."""
|
|
return web.json_response({"downloads": downloads.list_downloads()})
|
|
|
|
@routes.delete("/imagelab/downloads/{version_id}")
|
|
async def cancel_download(request: web.Request) -> web.Response:
|
|
"""Cancel an in-flight download, or dismiss a finished/failed row."""
|
|
try:
|
|
version_id = int(request.match_info["version_id"])
|
|
except ValueError:
|
|
return web.json_response({"error": "version_id must be an integer", "code": "VALIDATION_ERROR"}, status=400)
|
|
return web.json_response(downloads.cancel_download(version_id))
|
|
|
|
# ── local model deletion ───────────────────────────────────────────────
|
|
|
|
@routes.delete("/imagelab/models/{model_type}/{filename:.*}")
|
|
async def delete_model(request: web.Request) -> web.Response:
|
|
"""Delete a local model file and drop it from the hash index."""
|
|
try:
|
|
downloads.delete_model(request.match_info["model_type"], request.match_info["filename"])
|
|
except downloads.CivitaiError as e:
|
|
return web.json_response({"error": e.message, "code": e.code}, status=e.status)
|
|
return web.json_response({"deleted": True})
|
|
|
|
print("[ImageLab] API routes registered")
|