diff --git a/.gitignore b/.gitignore index 12446d8..b0e7397 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ # User data /resources +/model_index /workflows/*.yaml # Byte-compiled / optimized / DLL files diff --git a/__init__.py b/__init__.py index 99c8793..50e7afa 100644 --- a/__init__.py +++ b/__init__.py @@ -1,36 +1,42 @@ -from server import PromptServer -from .progress import add_progress_hook -from .routes import SetupRoutes -from .workflows import * -from . import resources +""" +ImageLab v3 — ComfyUI custom node entrypoint. -# Apply the send_sync patch to broadcast progress to all WebSocket clients -# add_progress_hook() -# print("[ImageLab] progress patch applied successfully") +This is a clean-slate rebuild. For now it does two things: hash all model +files on startup (in the background) and expose the hash cache over a small +HTTP API. Functionality will be added back in pieces. -# Register API routes -SetupRoutes(PromptServer.instance) -print("[ImageLab] routes registered successfully") +The previous entrypoint is preserved as `__init__.py.legacy`, alongside the +other legacy modules (`routes.py`, `workflows.py`, `imagelab_nodes.py`, +`resources.py`, ...) — kept for reference, not loaded. +""" +import threading -# Optional: Index all new models at startup -AUTO_INDEX_ON_STARTUP = True +from . import hashing +from . import api -if AUTO_INDEX_ON_STARTUP: - import threading - def index_on_startup(): - print("[ImageLab] Starting background indexing of new models...") - try: - indexed = resources.index_all_new_models() - if indexed: - print(f"[ImageLab] Indexed models: {indexed}") - else: - print("[ImageLab] No new models to index") - except Exception as e: - print(f"[ImageLab] Error during startup indexing: {e}") - - # Run in background thread to not block startup - threading.Thread(target=index_on_startup, daemon=True).start() +# No custom nodes yet — ComfyUI still expects these symbols to exist. +NODE_CLASS_MAPPINGS = {} +NODE_DISPLAY_NAME_MAPPINGS = {} -print("[ImageLab] Initialization complete") +# Register the HTTP API (synchronous — routes must exist before the server +# finishes starting; this is just dict insertion, it does not block). +api.setup_routes() -from .imagelab_nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS \ No newline at end of file + +def _hash_on_startup(): + print("[ImageLab] Building model-hash index in the background ...") + try: + counts = hashing.build_index() + if counts: + print(f"[ImageLab] Hashed: {counts}") + else: + print("[ImageLab] No new models to hash") + version, entries = hashing.get_snapshot() + print(f"[ImageLab] Index ready: {len(entries)} models (version {version})") + except Exception as e: + print(f"[ImageLab] Error during startup hashing: {e}") + + +threading.Thread(target=_hash_on_startup, daemon=True).start() + +print("[ImageLab] v3 loaded") diff --git a/__init__.py.legacy b/__init__.py.legacy new file mode 100644 index 0000000..99c8793 --- /dev/null +++ b/__init__.py.legacy @@ -0,0 +1,36 @@ +from server import PromptServer +from .progress import add_progress_hook +from .routes import SetupRoutes +from .workflows import * +from . import resources + +# Apply the send_sync patch to broadcast progress to all WebSocket clients +# add_progress_hook() +# print("[ImageLab] progress patch applied successfully") + +# Register API routes +SetupRoutes(PromptServer.instance) +print("[ImageLab] routes registered successfully") + +# Optional: Index all new models at startup +AUTO_INDEX_ON_STARTUP = True + +if AUTO_INDEX_ON_STARTUP: + import threading + def index_on_startup(): + print("[ImageLab] Starting background indexing of new models...") + try: + indexed = resources.index_all_new_models() + if indexed: + print(f"[ImageLab] Indexed models: {indexed}") + else: + print("[ImageLab] No new models to index") + except Exception as e: + print(f"[ImageLab] Error during startup indexing: {e}") + + # Run in background thread to not block startup + threading.Thread(target=index_on_startup, daemon=True).start() + +print("[ImageLab] Initialization complete") + +from .imagelab_nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS \ No newline at end of file diff --git a/api.py b/api.py new file mode 100644 index 0000000..746e9fa --- /dev/null +++ b/api.py @@ -0,0 +1,43 @@ +""" +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 + + +def setup_routes() -> None: + """Register API routes with the running ComfyUI server.""" + routes = PromptServer.instance.routes + + @routes.get("/imagelab/hashes") + async def get_hashes(request: web.Request) -> web.Response: + """ + Return the full model-hash cache in one shot: + + { "version": "", "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"}, + ) + + print("[ImageLab] API routes registered") diff --git a/hashing.py b/hashing.py new file mode 100644 index 0000000..0fc8640 --- /dev/null +++ b/hashing.py @@ -0,0 +1,177 @@ +""" +Model hashing. + +Computes SHA256 hashes for ComfyUI model files and caches the result so a +model is only ever hashed once. The cache is a tree of per-model `.index` +JSON sidecar files under `model_index/`, keyed by the model's path *relative +to ComfyUI's models directory* (e.g. `checkpoints/SDXL/foo.safetensors`) so +that two models sharing a bare filename in different folders never collide. + +It also keeps an in-memory snapshot of every known model's hash (`_INDEX`) +plus a cheap content version token (`_VERSION`). This is what the API layer +serves to the frontend in a single request — building the response is then +just a dict read, with no disk I/O per request. + +This is the first piece of the rebuilt extension — intentionally small. The +legacy entrypoint and modules (`__init__.py.legacy`, `resources.py`, etc.) +are kept for reference until their functionality is rebuilt. +""" +import os +import json +import time +import hashlib +import threading +from typing import Dict, List, Optional, Tuple + +import folder_paths + +# Per-model `.index` sidecar cache. Mirrors the models-dir tree so the files +# stay human-browsable. Gitignored — this is local user data. +INDEX_DIR = os.path.join(os.path.dirname(__file__), "model_index") + +# Model folder types to scan on startup. +MODEL_TYPES = [ + "checkpoints", "loras", "vae", "embeddings", "upscale_models", + "controlnet", "clip", "clip_vision", "diffusion_models", +] + +# In-memory snapshot of every known model: cache_key -> index dict. +# Guarded by _LOCK because it is populated by the background startup thread +# while the API layer may read it from the aiohttp event loop. +_INDEX: Dict[str, Dict] = {} +_VERSION: str = "empty" +_LOCK = threading.Lock() + + +def cache_key(filepath: str) -> str: + """ + Stable, collision-free cache key for a model file: its path relative to + ComfyUI's models directory. Models living outside that directory (extra + registered paths) fall back to their absolute path with leading separators + stripped, which is still unique and still safe to use as a relative path. + """ + abspath = os.path.abspath(filepath) + rel = os.path.relpath(abspath, folder_paths.models_dir) + if rel.startswith(".." + os.sep) or rel == "..": + # Outside models_dir — use the absolute path, made relative-safe. + rel = abspath.lstrip(os.sep) + if os.name == "nt": # strip a drive colon, e.g. C:\ -> C\ + rel = rel.replace(":", "", 1) + return rel.replace(os.sep, "/") + + +def _index_path(key: str) -> str: + """Filesystem path of the `.index` sidecar for a given cache key.""" + path = os.path.join(INDEX_DIR, *key.split("/")) + ".index" + os.makedirs(os.path.dirname(path), exist_ok=True) + return path + + +def calculate_sha256(filepath: str) -> str: + """Calculate the SHA256 hash of a file.""" + sha256 = hashlib.sha256() + with open(filepath, "rb") as f: + for block in iter(lambda: f.read(1024 * 1024), b""): + sha256.update(block) + return sha256.hexdigest() + + +def load_index(key: str) -> Optional[Dict]: + """Return the cached index for a key, or None if it hasn't been hashed.""" + path = os.path.join(INDEX_DIR, *key.split("/")) + ".index" + if os.path.exists(path): + try: + with open(path, "r") as f: + return json.load(f) + except (json.JSONDecodeError, OSError): + pass + return None + + +def save_index(key: str, data: Dict) -> None: + """Write the index sidecar for a key.""" + with open(_index_path(key), "w") as f: + json.dump(data, f, indent=2) + + +def _compute_version(index: Dict[str, Dict]) -> str: + """A cheap, stable content token over (key, hash) pairs — used as an ETag.""" + if not index: + return "empty" + digest = hashlib.sha256() + for key in sorted(index): + digest.update(key.encode()) + digest.update(b"\0") + digest.update((index[key].get("hash") or "").encode()) + digest.update(b"\0") + return digest.hexdigest()[:16] + + +def _remember(entry: Dict) -> None: + """Add/replace an entry in the in-memory index and refresh the version.""" + global _VERSION + with _LOCK: + _INDEX[entry["key"]] = entry + _VERSION = _compute_version(_INDEX) + + +def hash_model(filepath: str, key: Optional[str] = None) -> Dict: + """ + Ensure a model file is hashed. Returns its index dict. If the model has + already been hashed (its `.index` sidecar exists), this is a cheap no-op. + Either way the result is recorded in the in-memory index. + """ + if key is None: + key = cache_key(filepath) + + index = load_index(key) + if not (index and index.get("hash")): + print(f"[ImageLab] Hashing {key} ...") + index = { + "key": key, + "filename": os.path.basename(filepath), + "hash": calculate_sha256(filepath), + "hashed_at": time.time(), + } + save_index(key, index) + + _remember(index) + return index + + +def build_index() -> Dict[str, int]: + """ + Scan every model folder, hash anything not yet hashed, and populate the + in-memory index from the (now complete) on-disk cache. Run once at startup. + Returns a per-type count of files newly hashed this run. + """ + counts: Dict[str, int] = {} + + for model_type in MODEL_TYPES: + if model_type not in folder_paths.folder_names_and_paths: + continue + + for filename in folder_paths.get_filename_list(model_type): + filepath = folder_paths.get_full_path(model_type, filename) + if not filepath: + continue + key = cache_key(filepath) + already_hashed = load_index(key) is not None + try: + hash_model(filepath, key) + if not already_hashed: + counts[model_type] = counts.get(model_type, 0) + 1 + except Exception as e: + print(f"[ImageLab] Error hashing {filename}: {e}") + + return counts + + +def get_snapshot() -> Tuple[str, List[Dict]]: + """ + Return `(version, entries)` for the API layer. `version` is an ETag-style + content token; `entries` is the list of `{key, filename, hash, hashed_at}` + dicts. Cheap — a lock-guarded copy, no disk I/O. + """ + with _LOCK: + return _VERSION, list(_INDEX.values())