Spaces:
Running on Zero

monet-retrieval / app.py
baubin's picture
Point to v1.2.0
661164c
Raw History Blame Contribute Delete
104 kB
"""Gradio app: upload an image, find nearest neighbours among MONET embeddings. Three embedders are wired up β€” DINOv2 ViT-G/14 (general retrieval), OpenCLIP ViT-B/32 (image / text alignment) and SSCD (copy-detection). They share a single row ordering, so one alignment parquet at the bucket root maps ``row_id β†’ (id, local_path, hash_perceptual)`` for all of them:: <DATA_ROOT>/ β”œβ”€β”€ aligned_paths.parquet # shared row_id -> (id, path, hash) β”œβ”€β”€ dinov2/ β”‚ β”œβ”€β”€ embedding_dinov2-vitg14.faiss β”‚ └── meta.json β”œβ”€β”€ clip/ … └── sscd/ … The alignment file is built once offline by ``scripts/build_alignment.py`` and synced to the bucket; the app just memory-maps it at startup. There is no runtime fallback that rebuilds the alignment from per-model hashes β€” the bucket MUST ship ``aligned_paths.parquet``. Hot path on every search: 1. Embed the query image on the GPU worker (``@spaces.GPU``). 2. FAISS search the chosen index. 3. For each neighbour, range-read a single row group from its dataset parquet on the Hub (no full file download), extract the ``thumbnail`` blob and metadata. Results are LRU-cached so repeat searches are instant. """ from __future__ import annotations import base64 import io import json import logging import mimetypes import os import re import shutil import sys import threading import time from collections import OrderedDict from collections.abc import Iterator from concurrent.futures import ThreadPoolExecutor, as_completed from functools import lru_cache from pathlib import Path from string import Template from typing import Literal, get_args # CPython 3.12 has a known bug where BaseEventLoop.__del__ raises # "ValueError: Invalid file descriptor: -1" when GC'ing an event loop whose # self-pipe was already closed (e.g. by httpx / spaces / forked workers). # These tracebacks are harmless but spam the logs via sys.unraisablehook. # https://github.com/python/cpython/issues/114177 _default_unraisablehook = sys.unraisablehook def _silence_loop_fd_unraisable(unraisable: "sys.UnraisableHookArgs") -> None: exc = unraisable.exc_value if ( isinstance(exc, ValueError) and "Invalid file descriptor: -1" in str(exc) and getattr(unraisable.object, "__qualname__", "") == "BaseEventLoop.__del__" ): return _default_unraisablehook(unraisable) sys.unraisablehook = _silence_loop_fd_unraisable import faiss import gradio as gr import numpy as np import pyarrow as pa import pyarrow.parquet as pq import spaces from huggingface_hub import HfFileSystem, hf_hub_download from PIL import Image from embedders import ( MODEL_DIMS, MODEL_LABELS, TEXT_CAPABLE, compute_embedding, compute_text_embedding, preload, ) logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", ) # Silence per-request HTTP chatter from upstream libraries (huggingface_hub, # datasets, fsspec, etc.). They emit one INFO line per parquet/range fetch, # which floods the terminal during gallery loads. for _noisy in ("httpx", "httpcore", "urllib3", "hf_transfer", "huggingface_hub"): logging.getLogger(_noisy).setLevel(logging.WARNING) logger = logging.getLogger("MONET-retrieval.app") ROOT = Path(__file__).parent BUCKET_MOUNT = Path(os.environ.get("MONET_BUCKET_MOUNT", "/data")) # Subdirectory inside the mounted bucket where this revision's files live. # The ``jasperai/monet-retrieval-storage`` bucket is versioned at the root # (``v1.2.0/``, ``v1.2.0/``, ...), so when the whole bucket is mounted at # ``/data`` the actual files are under ``/data/v1.2.0/dinov2/...`` etc. # Set ``MONET_BUCKET_PREFIX=""`` if a future deployment mounts the version # subdirectory directly. VERSION = "v1.2.0" BUCKET_PREFIX = os.environ.get("MONET_BUCKET_PREFIX", VERSION).strip("/") BUCKET_ROOT = (BUCKET_MOUNT / BUCKET_PREFIX) if BUCKET_PREFIX else BUCKET_MOUNT DATA_ROOT = Path(os.environ.get("MONET_DATA_ROOT", str(ROOT))).resolve() # ``MONET_SKIP_SYNC=1`` (recommended on HF Spaces) bypasses the rsync-style # copy from the bucket mount into local writable storage and reads files # directly from the mount. The default-on copy is appropriate when the # bucket is on slow remote storage and you want fast FAISS reads off the # local disk, but on HF Spaces it (a) burns 24+ GB of the ~50 GB ephemeral # disk and (b) can take many minutes during which the watchdog sees no # output and may kill the build. Reading directly is fine because every # heavy file (FAISS index, alignment parquet) is loaded once into RAM at # startup β€” no hot-path FUSE reads. SKIP_SYNC = os.environ.get("MONET_SKIP_SYNC", "0").lower() in ("1", "true", "yes") if SKIP_SYNC: if BUCKET_ROOT.is_dir(): DATA_ROOT = BUCKET_ROOT.resolve() logger.info( "MONET_SKIP_SYNC=1 β€” DATA_ROOT pointed at bucket mount %s " "(no copy will run).", DATA_ROOT, ) else: logger.warning( "MONET_SKIP_SYNC=1 but %s is not a directory yet; the sync " "will run anyway against the configured DATA_ROOT.", BUCKET_ROOT, ) SKIP_SYNC = False # Shared alignment parquet (row_id -> id, local_path, hash_perceptual). Lives # at the bucket root and is reused by every model since they share the same # row ordering. Built offline by ``scripts/build_alignment.py``. ALIGNED_PATHS_NAME = os.environ.get("MONET_ALIGNED_PATHS_NAME", "aligned_paths.parquet") ALIGNED_PATHS_PATH = DATA_ROOT / ALIGNED_PATHS_NAME EXAMPLE_IMAGES = [str(p) for p in (ROOT / "examples").glob("*") if p.is_file()] LOGO_PATH = ROOT / "assets" / "logo_retrieval.png" def _file_to_data_url(path: Path) -> str | None: """Return ``data:<mime>;base64,...`` for ``path``, or ``None`` on miss. Used for the hero wordmark; callers fall back to a plain text title when this returns ``None`` so a missing asset is recoverable. """ if not path.is_file(): return None mime, _ = mimetypes.guess_type(path.name) if mime is None: mime = "application/octet-stream" try: b64 = base64.b64encode(path.read_bytes()).decode("ascii") except OSError as e: logger.warning("Failed to inline asset %s: %s", path, e) return None return f"data:{mime};base64,{b64}" _HERO_LOGO_DATA_URL = _file_to_data_url(LOGO_PATH) if _HERO_LOGO_DATA_URL is None: logger.warning( "Hero logo missing at %s β€” falling back to text wordmark.", LOGO_PATH, ) HF_DATASET_REPO = os.environ.get("MONET_HF_REPO", "jasperai/monet") HF_DATASET_PREFIX = os.environ.get("MONET_HF_PREFIX", VERSION) # Git revision (branch, tag, or commit SHA) of the dataset repo to read from. # Defaults to ``None`` so the Hub resolves the repo's default branch (``main``), # preserving prior behaviour when unset. HF_DATASET_REVISION = os.environ.get("MONET_HF_REVISION") or None HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_HUB_TOKEN") DOWNLOAD_WORKERS = int(os.environ.get("MONET_DOWNLOAD_WORKERS", "16")) # Image / metadata source. # # The dataset ships every shard twice on the Hub: ``{shard}.parquet`` (with a # ~256 px ``thumbnail`` blob baked in β€” the cheap, low-res path used by the # default streaming reader) AND ``{shard}.tar`` (a webdataset-style archive # of raw ``{id}.jpg`` + ``{id}.json`` samples β€” the full-resolution path). # The shared alignment parquet only stores the parquet-side ``local_path``; # the tar path is derived by swapping the extension. # # ``MONET_DEFAULT_SOURCE`` controls which source the UI radio defaults to. # Both sources go through the same fetch entry point and decode JPEG bytes # only once the matching row is found (no PIL involvement during tar # iteration), so switching is a single-flag operation. Source = Literal["parquet", "tar"] SOURCE_PARQUET: Source = "parquet" SOURCE_TAR: Source = "tar" SOURCE_CHOICES: tuple[Source, ...] = get_args(Source) def _resolve_source(value: str) -> Source: """Return ``value`` as a known :data:`Source`, falling back to parquet.""" normalized = (value or "").strip().lower() if normalized in SOURCE_CHOICES: return normalized # type: ignore[return-value] logger.warning("Invalid source %r; falling back to %r", value, SOURCE_PARQUET) return SOURCE_PARQUET DEFAULT_SOURCE: Source = _resolve_source( os.environ.get("MONET_DEFAULT_SOURCE", SOURCE_PARQUET) ) # ----------------------------------------------------------------------------- # Fallback parquet cache (disk) # ----------------------------------------------------------------------------- # The hot path is a streaming HTTP range read that never touches disk. The # *fallback* path (``hf_hub_download``) downloads the whole parquet β€” these # files are ~500 MB each, and HF Spaces ship with only ~50 GB of writable # storage (already mostly taken by FAISS indexes), so an unbounded cache # fills the disk after a handful of misses. We route every fallback through # a dedicated cache dir we control, track the files in an LRU, and enforce # a byte budget + a disk-free-space safety net. # # Tuning knobs: # MONET_PARQUET_CACHE_DIR β€” where to store fallback downloads # (default: ``<repo>/.parquet_cache``). # MONET_PARQUET_CACHE_BUDGET_GB β€” max GB to keep on disk; 0 disables the # persistent cache entirely and we still # download/read/delete each fallback # (default: 8). # MONET_PARQUET_CACHE_FREE_FLOOR_GB β€” if free disk drops below this, evict # aggressively even under budget # (default: 2). PARQUET_CACHE_DIR = Path( os.environ.get("MONET_PARQUET_CACHE_DIR", str(ROOT / ".parquet_cache")) ).resolve() PARQUET_CACHE_BUDGET_BYTES = int( float(os.environ.get("MONET_PARQUET_CACHE_BUDGET_GB", "20")) * (1024**3) ) PARQUET_CACHE_FREE_FLOOR_BYTES = int( float(os.environ.get("MONET_PARQUET_CACHE_FREE_FLOOR_GB", "2")) * (1024**3) ) # Same shape as the parquet cache, but for the tar (high-res) shards. Tars are # ~order-of-magnitude bigger than parquets and they cannot be range-read by # member name, so we always pull the whole shard locally before iterating with # webdataset. Bigger default budget + bigger free-disk floor reflect that. # # Tuning knobs: # MONET_TAR_CACHE_DIR β€” where to keep downloaded tar shards # (default: ``<repo>/.tar_cache``). # MONET_TAR_CACHE_BUDGET_GB β€” max GB to keep on disk; 0 disables the # persistent cache (default: 40). # MONET_TAR_CACHE_FREE_FLOOR_GB β€” if free disk drops below this, evict # aggressively even under budget # (default: 5). TAR_CACHE_DIR = Path( os.environ.get("MONET_TAR_CACHE_DIR", str(ROOT / ".tar_cache")) ).resolve() TAR_CACHE_BUDGET_BYTES = int( float(os.environ.get("MONET_TAR_CACHE_BUDGET_GB", "100")) * (1024**3) ) TAR_CACHE_FREE_FLOOR_BYTES = int( float(os.environ.get("MONET_TAR_CACHE_FREE_FLOOR_GB", "5")) * (1024**3) ) # Per-result JPEGs that the Gradio Gallery serves. Writing them to disk with # a stable, content-meaningful filename (``{hash_perceptual}.jpg``) is what # gives the browser's "download" button a useful name β€” passing PIL images # instead would have Gradio mint random UUIDs. Content-addressed names mean # repeated searches hit the same files (idempotent writes), so the cache # grows slowly and a missing eviction policy is acceptable in practice. IMAGE_CACHE_DIR = Path( os.environ.get("MONET_IMAGE_CACHE_DIR", str(ROOT / ".image_cache")) ).resolve() # Parallelism for the bucket -> DATA_ROOT sync. ``MONET_SYNC_WORKERS`` is the # preferred name; ``MONET_COPY_WORKERS`` is accepted as a back-compat alias. SYNC_WORKERS = int( os.environ.get("MONET_SYNC_WORKERS") or os.environ.get("MONET_COPY_WORKERS", "4") ) # When true, the sync also deletes local files that are no longer part of the # plan (inside managed subdirs and the alignment file at the root). Off by # default β€” turn on if you reshuffle MONET_MODELS and want a clean DATA_ROOT. SYNC_PRUNE = os.environ.get("MONET_SYNC_PRUNE", "0").lower() in ("1", "true", "yes") # Per-model files. Each model lives in its own subdirectory of DATA_ROOT # (and of the bucket mount). The runtime only needs the FAISS index per # model; the alignment parquet is shared across models and lives at the # bucket root (see ``ALIGNED_PATHS_NAME`` above). MODEL_FILES: dict[str, dict[str, str]] = { "dinov2": { "subdir": "dinov2", "faiss": "embedding_dinov2-vitg14.faiss", }, "clip": { "subdir": "clip", "faiss": "embedding_clip-vit-base-patch32.faiss", }, "sscd": { "subdir": "sscd", "faiss": "embedding_sscd.faiss", }, } # Models actually exposed in the UI. Override with MONET_MODELS=dinov2,clip ENABLED_MODELS: tuple[str, ...] = tuple( m.strip() for m in os.environ.get("MONET_MODELS", "clip,dinov2,sscd").split(",") if m.strip() ) # On HF ZeroGPU we MUST NOT initialize CUDA in the main process (no # ``torch.cuda.*`` calls, no ``faiss.index_cpu_to_all_gpus``) β€” the ZeroGPU # worker would then fail to attach a GPU on the first request with # ``RuntimeError: No CUDA GPUs are available``. We keep FAISS on CPU there. _IS_ZEROGPU = bool(os.environ.get("SPACES_ZERO_GPU") or os.environ.get("SPACE_ID")) # Helpers to resolve the bucket-side and local-side paths for a given model. # Bucket paths live under ``BUCKET_ROOT`` (= ``BUCKET_MOUNT / BUCKET_PREFIX``), # since the storage bucket is versioned at its root (``v1.2.0/`` etc.). def _bucket_dir(kind: str) -> Path: return BUCKET_ROOT / MODEL_FILES[kind]["subdir"] def _local_dir(kind: str) -> Path: return DATA_ROOT / MODEL_FILES[kind]["subdir"] def _bucket_file(kind: str, key: str) -> Path: return _bucket_dir(kind) / MODEL_FILES[kind][key] def _local_file(kind: str, key: str) -> Path: return _local_dir(kind) / MODEL_FILES[kind][key] # Decide what to sync from the bucket: each enabled model's FAISS index + # meta.json, plus the single shared alignment parquet at the bucket root. # The alignment parquet MUST be present in the bucket β€” there is no runtime # rebuild path. def _build_default_sync_plan() -> list[Path]: """Return the list of *bucket* paths the runtime needs locally. Each source preserves its relative position under ``BUCKET_ROOT`` when mirrored to ``DATA_ROOT`` β€” a file at ``<BUCKET_ROOT>/dinov2/foo`` lands at ``<DATA_ROOT>/dinov2/foo``. ``BUCKET_ROOT`` already accounts for the revision prefix (e.g. ``/data/{VERSION}``). """ sources: list[Path] = [] for kind in ENABLED_MODELS: if kind not in MODEL_FILES: continue bdir = _bucket_dir(kind) if not bdir.is_dir(): logger.warning( "Model %r: bucket subdir %s missing β€” skipping in sync plan", kind, bdir, ) continue for name in (MODEL_FILES[kind]["faiss"], "meta.json"): src = bdir / name if src.is_file(): sources.append(src) alignment_src = BUCKET_ROOT / ALIGNED_PATHS_NAME if alignment_src.is_file(): sources.append(alignment_src) else: logger.warning( "Shared alignment parquet missing at %s β€” models won't load. " "Run scripts/build_alignment.py and sync the result to the bucket.", alignment_src, ) seen: set[Path] = set() unique: list[Path] = [] for s in sources: if s not in seen: seen.add(s) unique.append(s) return unique # Allow override: MONET_SYNC_FILES (legacy alias: MONET_COPY_FILES) is a # comma-separated list of paths *relative to BUCKET_ROOT* (e.g. # "dinov2/embedding_dinov2-vitg14.faiss,aligned_paths.parquet"). _DEFAULT_SOURCES = _build_default_sync_plan() _SYNC_OVERRIDE = ( os.environ.get("MONET_SYNC_FILES", "").strip() or os.environ.get("MONET_COPY_FILES", "").strip() ) if _SYNC_OVERRIDE: SYNC_SOURCES: tuple[Path, ...] = tuple( BUCKET_ROOT / name.strip() for name in _SYNC_OVERRIDE.split(",") if name.strip() ) else: SYNC_SOURCES = tuple(_DEFAULT_SOURCES) # ----------------------------------------------------------------------------- # Sync bucket contents into local storage (rsync-style: size + mtime aware, # atomic, with optional pruning of stale entries). # ----------------------------------------------------------------------------- def _is_up_to_date(src_stat: os.stat_result, dst: Path) -> bool: """Return True if ``dst`` already mirrors ``src_stat``. A file is "up to date" iff it exists and (size, mtime-as-int) match the source. We round mtime to an int to dodge sub-second drift introduced by filesystems that don't preserve fractional seconds. """ if not dst.exists(): return False dst_stat = dst.stat() return dst_stat.st_size == src_stat.st_size and int(dst_stat.st_mtime) == int( src_stat.st_mtime ) def _sync_bucket() -> None: """rsync-style mirror of bucket files into ``DATA_ROOT``. The ``jasperai/monet-retrieval-storage`` bucket is mounted at ``BUCKET_MOUNT`` and the active revision lives under ``BUCKET_ROOT = BUCKET_MOUNT / BUCKET_PREFIX``. For every source in :data:`SYNC_SOURCES` we mirror ``<BUCKET_ROOT>/x/y/z`` to ``<DATA_ROOT>/x/y/z`` when the destination is missing or its (size, mtime) doesn't match. Mtime is preserved so a later sync of the same revision is a true no-op. With ``MONET_SYNC_PRUNE=1`` we also delete files under the managed subdirs that aren't in the current plan. On HF Spaces set ``MONET_SKIP_SYNC=1`` to bypass the copy entirely β€” the runtime reads the FAISS index + alignment parquet straight from the mount (each loaded once at startup, so FUSE speed only matters during boot). """ if SKIP_SYNC: logger.info( "Bucket sync skipped (MONET_SKIP_SYNC=1); reading directly from %s.", BUCKET_ROOT, ) return if not BUCKET_MOUNT.is_dir(): raise RuntimeError( f"Bucket mount {BUCKET_MOUNT} not found. " "Set MONET_BUCKET_MOUNT or mount the bucket at that path." ) if BUCKET_PREFIX and not BUCKET_ROOT.is_dir(): raise RuntimeError( f"Bucket revision dir {BUCKET_ROOT} not found. " f"Check MONET_BUCKET_PREFIX (currently {BUCKET_PREFIX!r}) β€” " f"contents of {BUCKET_MOUNT}: " f"{sorted(p.name for p in BUCKET_MOUNT.iterdir())[:20]}" ) DATA_ROOT.mkdir(parents=True, exist_ok=True) sources: list[Path] = [] missing: list[Path] = [] for src in SYNC_SOURCES: if src.is_file(): sources.append(src) else: missing.append(src) if missing: # We don't hard-fail here β€” the model-availability resolver below will # decide which models are actually loadable. logger.info( "Bucket sync: %d source(s) absent: %s", len(missing), ", ".join(str(m) for m in missing), ) planned_dsts: set[Path] = set() pending: list[tuple[Path, os.stat_result]] = [] up_to_date = 0 for src in sources: src_stat = src.stat() rel = src.relative_to(BUCKET_ROOT) dst = DATA_ROOT / rel planned_dsts.add(dst.resolve()) dst.parent.mkdir(parents=True, exist_ok=True) if _is_up_to_date(src_stat, dst): up_to_date += 1 continue pending.append((src, src_stat)) if up_to_date: logger.info("Bucket sync: %d file(s) already up to date", up_to_date) if SYNC_PRUNE: _prune_stale(planned_dsts) if not pending: logger.info( "Bucket sync: nothing to transfer (%d source(s) in plan)", len(sources) ) return workers = max(1, min(SYNC_WORKERS, len(pending))) total_bytes = sum(st.st_size for _, st in pending) total_gb = total_bytes / 1e9 # Disk-space sanity check: if the writable filesystem doesn't have at # least the transfer size plus a small safety margin, fail fast with a # helpful message instead of letting the copy stall on ENOSPC. On HF # Spaces this is the typical cause of a "stuck" sync. try: st = os.statvfs(DATA_ROOT) free_bytes = st.f_bavail * st.f_frsize if free_bytes < total_bytes + (1 << 30): # +1 GB margin raise RuntimeError( f"Bucket sync would need {total_gb:.2f} GB but only " f"{free_bytes / 1e9:.2f} GB free at {DATA_ROOT}. Set " f"MONET_SKIP_SYNC=1 to read directly from the mount, or " f"point MONET_DATA_ROOT at a larger filesystem." ) except OSError: pass logger.info( "Syncing %d file(s) (%.2f GB) from %s -> %s with %d worker(s)", len(pending), total_gb, BUCKET_ROOT, DATA_ROOT, workers, ) t0 = time.perf_counter() # In-flight tracking so a stalled copy is visible in the logs instead # of leaving the build watchdog with nothing to chew on. in_flight: dict[str, Path] = {} in_flight_lock = threading.Lock() stop_progress = threading.Event() def _progress_logger() -> None: # Log every 15 s while at least one copy is in flight. while not stop_progress.wait(15.0): with in_flight_lock: snapshot = list(in_flight.items()) if not snapshot: continue lines = [] for name, tmp in snapshot: try: cur = tmp.stat().st_size except OSError: cur = 0 lines.append(f"{name} {cur / 1e9:.2f} GB") logger.info("Bucket sync in flight: %s", "; ".join(lines)) prog = threading.Thread(target=_progress_logger, daemon=True) prog.start() def _sync_one(src: Path, src_stat: os.stat_result) -> tuple[Path, float]: ts = time.perf_counter() rel = src.relative_to(BUCKET_ROOT) dst = DATA_ROOT / rel dst.parent.mkdir(parents=True, exist_ok=True) # Atomic-ish: write to a temp file in the same dir then rename, so a # crashed sync doesn't leave a wrong-sized file that the (size, mtime) # check above would later mistake for "already present". tmp = dst.with_suffix(dst.suffix + ".part") with in_flight_lock: in_flight[str(rel)] = tmp try: shutil.copyfile(src, tmp) # Preserve mtime so subsequent syncs short-circuit on the stat check. os.utime(tmp, ns=(src_stat.st_atime_ns, src_stat.st_mtime_ns)) os.replace(tmp, dst) finally: with in_flight_lock: in_flight.pop(str(rel), None) return src, time.perf_counter() - ts errors: list[tuple[Path, BaseException]] = [] try: with ThreadPoolExecutor(max_workers=workers) as ex: futures = {ex.submit(_sync_one, s, st): s for s, st in pending} for fut in as_completed(futures): src = futures[fut] try: _, dt = fut.result() logger.info( " synced %s (%.2f GB) in %.1f s", src.relative_to(BUCKET_ROOT), src.stat().st_size / 1e9, dt, ) except BaseException as e: # noqa: BLE001 errors.append((src, e)) logger.error( " failed to sync %s: %s", src.relative_to(BUCKET_ROOT), e ) finally: stop_progress.set() prog.join(timeout=1.0) if errors: names = ", ".join(str(s.relative_to(BUCKET_ROOT)) for s, _ in errors) raise RuntimeError(f"Bucket sync failed for: {names}") logger.info( "Bucket sync done in %.1f s (%.0f MB/s aggregate)", time.perf_counter() - t0, total_gb * 1024 / max(time.perf_counter() - t0, 1e-9), ) def _prune_stale(planned_dsts: set[Path]) -> None: """Delete local files under managed paths that aren't in the plan. "Managed" means: each model subdir we know about, plus the alignment file at ``DATA_ROOT``. We deliberately never touch files outside those locations (so unrelated stuff alongside ``app.py`` is safe). Empty managed subdirs are also removed. """ managed_dirs: list[Path] = [] for kind, files in MODEL_FILES.items(): managed_dirs.append(DATA_ROOT / files["subdir"]) removed = 0 for d in managed_dirs: if not d.is_dir(): continue for path in d.rglob("*"): if not path.is_file(): continue # Skip in-flight ``.part`` artefacts; the next sync will overwrite. if path.suffix == ".part": continue if path.resolve() in planned_dsts: continue try: path.unlink() removed += 1 logger.info(" pruned %s", path.relative_to(DATA_ROOT)) except OSError as e: logger.warning(" failed to prune %s: %s", path, e) # Remove the directory itself if it's now empty. try: next(d.iterdir()) except StopIteration: try: d.rmdir() logger.info(" pruned empty dir %s", d.relative_to(DATA_ROOT)) except OSError: pass except FileNotFoundError: pass alignment_dst = (DATA_ROOT / ALIGNED_PATHS_NAME).resolve() if alignment_dst.exists() and alignment_dst not in planned_dsts: try: alignment_dst.unlink() removed += 1 logger.info(" pruned %s", ALIGNED_PATHS_NAME) except OSError as e: logger.warning(" failed to prune %s: %s", alignment_dst, e) if removed: logger.info("Bucket sync: pruned %d stale file(s)", removed) # ----------------------------------------------------------------------------- # Index + alignment loaded once at startup, per model # ----------------------------------------------------------------------------- def _load_index(faiss_path: Path) -> faiss.Index: logger.info("Loading FAISS index from %s ...", faiss_path) t0 = time.perf_counter() index = faiss.read_index(str(faiss_path)) logger.info( "FAISS index loaded on CPU: ntotal=%d dim=%d in %.1f s", index.ntotal, index.d, time.perf_counter() - t0, ) if _IS_ZEROGPU: logger.info("ZeroGPU detected β€” keeping FAISS index on CPU.") return index n_gpus = faiss.get_num_gpus() if hasattr(faiss, "get_num_gpus") else 0 if n_gpus <= 0: logger.warning("No FAISS GPU support detected β€” searching on CPU.") return index logger.info("Moving FAISS index to %d GPU(s) ...", n_gpus) t1 = time.perf_counter() co = faiss.GpuMultipleClonerOptions() co.shard = n_gpus > 1 co.useFloat16 = True try: gpu_index = faiss.index_cpu_to_all_gpus(index, co=co) except Exception as e: logger.warning("Falling back to CPU search (GPU clone failed: %s)", e) return index logger.info("Index on GPU in %.1f s", time.perf_counter() - t1) return gpu_index # ----------------------------------------------------------------------------- # Bundle = a FAISS index + (shared) alignment arrays. # ----------------------------------------------------------------------------- class _ModelBundle: """One FAISS index plus its row_id β†’ (id, local_path, hash) alignment.""" __slots__ = ("kind", "index", "ids", "local_paths", "hashes") def __init__( self, kind: str, index: faiss.Index, ids: np.ndarray, local_paths: np.ndarray, hashes: np.ndarray, ) -> None: self.kind = kind self.index = index self.ids = ids self.local_paths = local_paths self.hashes = hashes @lru_cache(maxsize=1) def _load_alignment_arrays() -> tuple[np.ndarray, np.ndarray, np.ndarray]: """Load the shared ``(ids, local_paths, hashes)`` arrays from disk. The alignment parquet is a single bucket-root file shared across every model β€” they all use the same row ordering, so one read covers all of them. Cached for the process lifetime. """ if not ALIGNED_PATHS_PATH.is_file(): raise RuntimeError( f"Shared alignment parquet missing at {ALIGNED_PATHS_PATH}. " f"Run scripts/build_alignment.py and sync " f"{ALIGNED_PATHS_NAME} to the bucket root." ) logger.info("Loading shared alignment from %s ...", ALIGNED_PATHS_PATH) t0 = time.perf_counter() table = pq.read_table(ALIGNED_PATHS_PATH) ids = table.column("id").to_numpy(zero_copy_only=False) paths = table.column("local_path").to_numpy(zero_copy_only=False) if "hash_perceptual" in table.column_names: hashes = table.column("hash_perceptual").to_numpy(zero_copy_only=False) else: logger.warning( "Shared alignment lacks 'hash_perceptual'; serving with empty " "hash values. Rebuild with scripts/build_alignment.py to embed it.", ) hashes = np.full(len(ids), "", dtype=object) logger.info( "Shared alignment loaded: %d rows in %.1f s", len(ids), time.perf_counter() - t0, ) return ids, paths, hashes _sync_bucket() # NOTE: ``_parquet_cache.bootstrap()`` and ``_tar_cache.bootstrap()`` run # further down once those caches are constructed; they only need to fire # before the first user search reaches them. # Resolve which models actually have a usable FAISS index on disk. _AVAILABLE: list[str] = [] for _kind in ENABLED_MODELS: if _kind not in MODEL_FILES: logger.warning("Skipping unknown model %r", _kind) continue if not _local_file(_kind, "faiss").is_file(): logger.warning( "Skipping %s: FAISS index missing at %s", _kind, _local_file(_kind, "faiss"), ) continue _AVAILABLE.append(_kind) if not _AVAILABLE: raise RuntimeError( "No models could be loaded. Check MONET_MODELS / MONET_COPY_FILES." ) try: _SHARED_IDS, _SHARED_PATHS, _SHARED_HASHES = _load_alignment_arrays() except Exception as e: raise RuntimeError(f"Failed to load shared alignment: {e}") from e BUNDLES: dict[str, _ModelBundle] = {} for _kind in _AVAILABLE: faiss_path = _local_file(_kind, "faiss") index = _load_index(faiss_path) expected = MODEL_DIMS[_kind] if index.d != expected: raise RuntimeError( f"{_kind}: FAISS index dim {index.d} != embedder dim {expected}" ) if index.ntotal != len(_SHARED_IDS): logger.warning( "%s: index ntotal %d != alignment rows %d", _kind, index.ntotal, len(_SHARED_IDS), ) BUNDLES[_kind] = _ModelBundle( _kind, index, _SHARED_IDS, _SHARED_PATHS, _SHARED_HASHES ) if not BUNDLES: raise RuntimeError("No models could be loaded.") DEFAULT_MODEL = next(iter(BUNDLES)) preload(*BUNDLES.keys()) # ----------------------------------------------------------------------------- # Hub parquet β†’ thumbnail + metadata, with row-group pruning + caching # ----------------------------------------------------------------------------- # Columns we always exclude from the metadata pane (embeddings are huge and # never user-facing; thumbnail is shown in the gallery, not as JSON). _METADATA_FIELDS_BLOCKLIST = { "thumbnail", "embedding_clip-vit-base-patch32", "embedding_dinov2-vitg14", "embedding_sscd", "embedding_vae-dc-sana1p5-1p6b-1024px-tiling-128-resolution-512x512", } # Always-fetch columns we need for the gallery + identifiers. Everything else # in the parquet schema (caption, scores, source, ...) is fetched too β€” except # the giant embedding columns, which we skip explicitly. _REQUIRED_COLUMNS: tuple[str, ...] = ("id", "thumbnail") _EMBEDDING_PREFIX = "embedding_" @lru_cache(maxsize=1) def _hf_fs() -> HfFileSystem: """A single shared HfFileSystem for range-reading parquets over HTTPS.""" return HfFileSystem(token=HF_TOKEN) def _hf_uri(local_path: str) -> str: """Return an ``hf://`` URI for the dataset parquet at ``local_path``.""" repo = HF_DATASET_REPO if HF_DATASET_REVISION: repo = f"{repo}@{HF_DATASET_REVISION}" return f"hf://datasets/{repo}/{HF_DATASET_PREFIX}/{local_path}" def _stat_to_str(value: object) -> str | None: """Coerce a parquet ``Statistics.min/max`` to a printable string. Stats may come back as ``bytes`` (binary columns), ``str``, or ``None`` β€” we always want a Python string for lex comparison against ``sample_id``. """ if value is None: return None if isinstance(value, bytes): try: return value.decode("utf-8", errors="replace") except Exception: return None return str(value) # Per-parquet footer cache: parsing the parquet footer over HTTP costs a few # range reads (and tens to hundreds of ms). Once we have the schema + row-group # statistics we can reuse them for every row read from the same file. We cache # the lightweight derived data (schema, list of row groups with id min/max) # rather than the live ``ParquetFile`` handle so it's safe to share across # threads. _FooterCache = tuple[pa.Schema, list[tuple[int, str | None, str | None]]] _footer_cache: dict[str, _FooterCache] = {} _footer_lock = threading.Lock() def _get_footer(local_path: str) -> _FooterCache: """Return ``(schema, [(rg_idx, id_min, id_max), ...])`` for a Hub parquet.""" cached = _footer_cache.get(local_path) if cached is not None: return cached with _footer_lock: cached = _footer_cache.get(local_path) if cached is not None: return cached fs = _hf_fs() uri = _hf_uri(local_path) with fs.open(uri, mode="rb") as f: pf = pq.ParquetFile(f) schema = pf.schema_arrow meta = pf.metadata rgs: list[tuple[int, str | None, str | None]] = [] for rg in range(meta.num_row_groups): rgm = meta.row_group(rg) lo: str | None = None hi: str | None = None for c in range(rgm.num_columns): col = rgm.column(c) if col.path_in_schema != "id": continue stats = col.statistics if stats is not None and stats.has_min_max: lo = _stat_to_str(stats.min) hi = _stat_to_str(stats.max) break rgs.append((rg, lo, hi)) cached = (schema, rgs) _footer_cache[local_path] = cached return cached # Source-aware payload cache shared between the parquet and tar paths. # We memoize SUCCESSFUL fetches only; ``functools.lru_cache`` would also # remember ``None``/empty results, which is exactly the negative-caching # bug we used to hit (a transient miss would poison subsequent searches). _PayloadKey = tuple[Source, str, str] _Payload = tuple[bytes | None, dict] class _PayloadCache: """Process-wide bounded cache for ``(image_bytes, metadata)`` payloads. Keyed on ``(source, local_path, sample_id)`` so parquet (low-res thumbnail) and tar (high-res JPEG) payloads never overwrite each other. Empty payloads are dropped instead of cached. """ def __init__(self, maxsize: int) -> None: self._maxsize = maxsize self._data: dict[_PayloadKey, _Payload] = {} self._lock = threading.Lock() def get(self, key: _PayloadKey) -> _Payload | None: return self._data.get(key) def put(self, key: _PayloadKey, payload: _Payload) -> None: if payload[0] is None and not payload[1]: return with self._lock: if len(self._data) >= self._maxsize: self._data.pop(next(iter(self._data)), None) self._data[key] = payload _payload_cache = _PayloadCache(maxsize=4096) # ----------------------------------------------------------------------------- # Bounded LRU on-disk cache for ``hf_hub_download`` results # ----------------------------------------------------------------------------- # Both image sources (parquet thumbnails, tar high-res JPEGs) route their # full-shard downloads through a managed disk cache. HF Spaces ship with # only ~50 GB of writable storage and the FAISS indexes already eat a big # chunk; an unbounded HF cache would fill the disk after a handful of # misses. The cache enforces a byte budget and a free-disk safety floor, # evicts oldest-first, and bootstraps from leftover files after a restart # so a crashed run doesn't permanently squat on the disk. def _blob_size(path: Path) -> int: """Size in bytes of the blob at ``path`` (follows symlinks).""" try: return path.resolve().stat().st_size except OSError: try: return path.stat().st_size except OSError: return 0 def _delete_blob(path: Path) -> int: """Remove an ``hf_hub_download`` artifact and return bytes freed. ``hf_hub_download`` returns a symlink under ``snapshots/`` that points at a content-addressed blob under ``blobs/``. Real disk usage lives in the blob, so we delete both β€” unlinking the symlink alone leaks the blob. """ freed = 0 target: Path | None = None try: if path.is_symlink() or path.exists(): try: target = path.resolve() except OSError: target = None except OSError: target = None if target is not None and target.is_file() and target != path: try: freed = target.stat().st_size target.unlink() except OSError as e: logger.warning("cache: failed to remove blob %s: %s", target, e) try: if path.is_symlink() or path.is_file(): if freed == 0: try: freed = path.stat().st_size except OSError: pass path.unlink() except OSError as e: logger.warning("cache: failed to remove %s: %s", path, e) return freed class DiskShardCache: """Bounded LRU on-disk cache for one kind of ``hf_hub_download`` shard. Two instances exist: one for ``.parquet`` shards (low-res thumbnails) and one for ``.tar`` shards (high-res JPEGs via webdataset). Both enforce two limits before every download: * ``budget_bytes`` β€” total bytes the cache may keep on disk (set to 0 to disable persistence; the next bootstrap reclaims). * ``free_floor_bytes`` β€” if the filesystem has less than this free, evict aggressively even when under the byte budget. The just-downloaded entry is protected from eviction so the caller can finish reading it. """ def __init__( self, *, name: str, cache_dir: Path, budget_bytes: int, free_floor_bytes: int, suffix: str, ) -> None: self.name = name self.cache_dir = cache_dir self.budget_bytes = budget_bytes self.free_floor_bytes = free_floor_bytes self.suffix = suffix self._lru: "OrderedDict[str, tuple[Path, int]]" = OrderedDict() self._lock = threading.Lock() def get(self, local_path: str) -> Path: """Return a local path for ``local_path``, downloading on miss.""" with self._lock: existing = self._lru.get(local_path) if existing is not None and existing[0].exists(): self._lru.move_to_end(local_path) return existing[0] if existing is not None: # File vanished from under us β€” drop the stale entry. self._lru.pop(local_path, None) self.cache_dir.mkdir(parents=True, exist_ok=True) self._make_room() t0 = time.perf_counter() path = Path( hf_hub_download( repo_id=HF_DATASET_REPO, filename=f"{HF_DATASET_PREFIX}/{local_path}", repo_type="dataset", revision=HF_DATASET_REVISION, token=HF_TOKEN, cache_dir=str(self.cache_dir), ) ) size = _blob_size(path) logger.info( "%s cache: downloaded %s (%.1f MB) in %.1f s", self.name, local_path, size / 1e6, time.perf_counter() - t0, ) with self._lock: self._lru[local_path] = (path, size) self._lru.move_to_end(local_path) if self.budget_bytes > 0: self._evict(self.budget_bytes) return path def bootstrap(self) -> None: """Reseed the LRU from leftover shards on disk after a restart. The HF cache layout is ``<root>/datasets--<owner>--<name>/snapshots/<rev>/<path>``, so we enumerate ``*<suffix>`` under ``cache_dir`` only (never touching unrelated HF caches), seed the LRU oldest-first by mtime, then evict to fit the budget. """ if not self.cache_dir.is_dir(): return snapshots = list(self.cache_dir.glob("datasets--*/snapshots/*")) if not snapshots: return found: list[tuple[float, str, Path, int]] = [] for snap in snapshots: for f in snap.rglob(f"*{self.suffix}"): try: size = _blob_size(f) if size <= 0: continue rel = f.relative_to(snap) # Strip the dataset-prefix segment (e.g. ``v1.2.0/``) so # the key matches the ``local_path`` callers pass in. parts = rel.parts if parts and parts[0] == HF_DATASET_PREFIX: parts = parts[1:] key = "/".join(parts) if parts else str(rel) found.append((f.stat().st_mtime, key, f, size)) except OSError: continue found.sort(key=lambda t: t[0]) with self._lock: for _, key, f, size in found: self._lru[key] = (f, size) if self.budget_bytes > 0: self._evict(self.budget_bytes, protect_newest=False) current = self._size() logger.info( "%s cache bootstrap: %d file(s), %.2f GB on disk " "(budget %.2f GB, free %.2f GB).", self.name, len(self._lru), current / 1e9, self.budget_bytes / 1e9, self._free_bytes() / 1e9, ) def _size(self) -> int: return sum(sz for _, sz in self._lru.values()) def _free_bytes(self) -> int: try: st = os.statvfs(self.cache_dir) return st.f_bavail * st.f_frsize except OSError: return 1 << 62 # "plenty" β€” disable the floor check if unsupported def _make_room(self) -> None: """Pre-emptively evict to budget headroom and the free-disk floor. Two passes β€” relative (budget) and absolute (free disk floor) β€” because both matter. Open headroom now so the download doesn't blow past the budget mid-write. """ if self.budget_bytes > 0: with self._lock: self._evict(int(self.budget_bytes * 0.75)) if self.free_floor_bytes > 0: free = self._free_bytes() if free < self.free_floor_bytes: logger.warning( "%s cache: free disk %.2f GB below floor %.2f GB; " "evicting aggressively.", self.name, free / 1e9, self.free_floor_bytes / 1e9, ) with self._lock: self._evict(0, protect_newest=False) def _evict(self, target_bytes: int, *, protect_newest: bool = True) -> int: """Evict oldest entries until the cache fits in ``target_bytes``. With ``protect_newest=True`` we leave at least one entry alive, so a caller that just downloaded a file gets to read it before eviction can reclaim it. """ freed_total = 0 while self._lru: if protect_newest and len(self._lru) <= 1: break if self._size() <= target_bytes: break key, (path, _sz) = self._lru.popitem(last=False) freed = _delete_blob(path) freed_total += freed logger.info( "%s cache: evicted %s (freed %.1f MB; now %.2f / %.2f GB)", self.name, key, freed / 1e6, self._size() / 1e9, self.budget_bytes / 1e9, ) return freed_total _parquet_cache = DiskShardCache( name="parquet", cache_dir=PARQUET_CACHE_DIR, budget_bytes=PARQUET_CACHE_BUDGET_BYTES, free_floor_bytes=PARQUET_CACHE_FREE_FLOOR_BYTES, suffix=".parquet", ) _tar_cache = DiskShardCache( name="tar", cache_dir=TAR_CACHE_DIR, budget_bytes=TAR_CACHE_BUDGET_BYTES, free_floor_bytes=TAR_CACHE_FREE_FLOOR_BYTES, suffix=".tar", ) _parquet_cache.bootstrap() _tar_cache.bootstrap() def _row_payload_cached(local_path: str, sample_id: str) -> tuple[bytes | None, dict]: """Range-read the row group of ``sample_id`` from the Hub and return its row. Streaming read first (single ranged HTTP GET into the right row group); falls back to a full ``hf_hub_download`` if streaming raises *or* returns an empty result (unknown row group, stats lied, etc.). Successful results are cached process-wide; misses are NOT cached, so a transient failure won't poison subsequent searches. """ cached = _payload_cache.get((SOURCE_PARQUET, local_path, sample_id)) if cached is not None: return cached thumb: bytes | None = None meta: dict = {} streaming_err: Exception | None = None try: thumb, meta = _row_payload_streaming(local_path, sample_id) except Exception as e: # noqa: BLE001 streaming_err = e if thumb is None and not meta: if streaming_err is not None: logger.warning( "streaming read failed for %s id=%s (%s); falling back to " "full download.", local_path, sample_id, streaming_err, ) else: logger.warning( "streaming read returned empty for %s id=%s; falling back to " "full download.", local_path, sample_id, ) try: full = _parquet_cache.get(local_path) thumb, meta = _row_payload_local(full, sample_id) except Exception as e2: # noqa: BLE001 logger.warning( "full-download fallback failed for %s id=%s: %s", local_path, sample_id, e2, ) return None, {} if thumb is None and not meta: # Even the full-download fallback came back empty β€” the row really # isn't there. Don't cache so a re-search has a chance to retry. logger.warning( "row not found in %s for id=%s (after streaming + full download)", local_path, sample_id, ) return None, {} _payload_cache.put((SOURCE_PARQUET, local_path, sample_id), (thumb, meta)) return thumb, meta def _select_columns(schema: pa.Schema) -> list[str]: """All columns except embeddings β€” we want the full metadata in the UI. Embedding columns can be hundreds of MB per row group; skipping them is crucial for the streaming HTTP read to stay fast. ``id`` is moved to the front so we can match without scanning all columns. """ cols = [n for n in schema.names if not n.startswith(_EMBEDDING_PREFIX)] if "id" in cols: cols.remove("id") cols.insert(0, "id") return cols def _candidate_row_groups( rgs: list[tuple[int, str | None, str | None]], sample_id: str ) -> list[int]: """Pick row groups whose ``id`` min/max bracket ``sample_id``. Robust to: - row groups missing stats (always included) - stats whose lex order doesn't match the id encoding (we widen to all row groups if the bracket-search comes back empty) - comparison errors from oddly-typed stats (treated as "include") """ any_stats = False candidates: list[int] = [] for rg, lo, hi in rgs: if lo is None or hi is None: candidates.append(rg) continue any_stats = True try: if lo <= sample_id <= hi: candidates.append(rg) except Exception: # Stats are some weird type we can't compare β€” include. candidates.append(rg) if not any_stats or not candidates: # Stats lied (or there were none). Don't narrow to nothing. return [rg for rg, _, _ in rgs] return candidates def _row_payload_streaming( local_path: str, sample_id: str ) -> tuple[bytes | None, dict]: """Read just the row group containing ``sample_id`` from the Hub via HTTP. Reuses the cached parquet footer (schema + row-group ``id`` stats) so the second-and-later reads from the same parquet skip the metadata round trip. If the stats-pruned candidate row groups don't yield the id (e.g. min/max stats encoded in a way that disagrees with our string compare), falls back to scanning every row group before giving up. """ schema, rgs = _get_footer(local_path) cols = _select_columns(schema) pruned = _candidate_row_groups(rgs, sample_id) all_rgs = [rg for rg, _, _ in rgs] # If pruning left us anything narrower than "all", try the narrow set # first; if it doesn't find the row, retry the rest. rest = [rg for rg in all_rgs if rg not in pruned] fs = _hf_fs() uri = _hf_uri(local_path) with fs.open(uri, mode="rb") as f: pf = pq.ParquetFile(f) for rg_list in (pruned, rest): for rg in rg_list: tbl = pf.read_row_group(rg, columns=cols) ids = tbl.column("id").to_pylist() if "id" in tbl.column_names else [] for i, rid in enumerate(ids): if str(rid) == sample_id: row = {c: tbl.column(c)[i].as_py() for c in tbl.column_names} return _split_row(row) return None, {} def _row_payload_local(parquet_path: Path, sample_id: str) -> tuple[bytes | None, dict]: """Local-file fallback: filter pushdown directly on the parquet file.""" schema = pq.ParquetFile(parquet_path).schema_arrow table = pq.read_table( parquet_path, columns=_select_columns(schema), filters=[("id", "=", sample_id)], ) if table.num_rows == 0: return None, {} row = {c: table.column(c)[0].as_py() for c in table.column_names} return _split_row(row) def _split_row(row: dict) -> tuple[bytes | None, dict]: thumb = row.get("thumbnail") meta = { k: v for k, v in row.items() if k not in _METADATA_FIELDS_BLOCKLIST and v is not None } return thumb if isinstance(thumb, (bytes, bytearray)) else None, meta # ----------------------------------------------------------------------------- # Tar / webdataset path: high-resolution JPEGs # ----------------------------------------------------------------------------- # Each parquet shard ``{shard}.parquet`` has a sibling ``{shard}.tar`` # laid out as a webdataset: per-sample ``{id}.jpg`` + ``{id}.json`` files, # sorted by basename. We stream the tar (no random access by name), match # samples by ``__key__`` first (which equals the dataset id) with a json # fallback, and short-circuit as soon as every requested id has been # collected. JPEG bytes are kept *as bytes* β€” no PIL involvement here β€” # and only decoded once a match is returned to the search loop. def _tar_path_for(parquet_local_path: str) -> str: """Map a parquet-shard relative path to its sibling tar shard.""" if parquet_local_path.endswith(".parquet"): return parquet_local_path[: -len(".parquet")] + ".tar" return parquet_local_path + ".tar" def _decode_tar_json(blob: bytes | str | None) -> dict: """Best-effort JSON decode of a tar entry; ``{}`` on any failure.""" if not blob: return {} if isinstance(blob, (bytes, bytearray)): blob = bytes(blob).decode("utf-8", errors="replace") try: parsed = json.loads(blob) except (ValueError, TypeError): return {} return parsed if isinstance(parsed, dict) else {"value": parsed} def _scan_tar( local_path: str, sample_ids: set[str], ) -> dict[str, tuple[bytes | None, dict]]: """Iterate one webdataset tar shard and pull out every requested ``id``. The shard is downloaded once to a managed local cache (``_tar_cache``) and then walked sequentially with webdataset. We stop early once every wanted id has been seen. JPEG bytes come back raw β€” decoding to PIL happens later, only for matches. Why local-first instead of streaming over ``HfFileSystem``: a tar can't be range-read by member name, so iterating it from a remote file object triggers many small range reads (one per fsspec block) for every shard, each costing an HTTP round-trip. One large GET into the disk cache collapses that into a single transfer, and subsequent searches that touch the same shard hit the LRU and skip the network entirely. """ if not sample_ids: return {} # Lazy import: keeps the parquet-only path zero-dependency on webdataset. try: from webdataset.tariterators import group_by_keys, tar_file_iterator except ImportError as e: # pragma: no cover raise RuntimeError( "Tar (high-res) source requires the 'webdataset' package. " "pip install webdataset" ) from e tar_local_path = _tar_path_for(local_path) tar_path = _tar_cache.get(tar_local_path) wanted = set(sample_ids) found: dict[str, tuple[bytes | None, dict]] = {} # ``tar_file_iterator`` yields ``{"fname": ..., "data": ...}`` entries, # but ``group_by_keys`` (and webdataset's error reporter) reaches for # ``__url__`` on each one; without it we get ``KeyError: ('__url__', # None, None)`` on the first sample. Wrap to inject the source URL. tar_url = str(tar_path) def _annotated(stream): for entry in stream: entry["__url__"] = tar_url yield entry with open(tar_path, "rb") as f: for sample in group_by_keys(_annotated(tar_file_iterator(f))): key = sample.get("__key__", "") sid: str | None = None if key in wanted: sid = key else: # Tars in this dataset *should* be keyed by ``id``, but if the # producer ever changes the convention, fall back to checking # the json's ``id`` field. We pay the json parse only when # the cheap key match misses. meta_probe = _decode_tar_json(sample.get("json")) cand = str(meta_probe.get("id", "")) if cand and cand in wanted: sid = cand if sid is None: continue jpg = sample.get("jpg") jpg_bytes = jpg if isinstance(jpg, (bytes, bytearray)) else None meta = _decode_tar_json(sample.get("json")) found[sid] = (jpg_bytes, meta) wanted.discard(sid) if not wanted: break return found _StreamItem = tuple[str, str, _Payload] def _stream_payloads( pairs: list[tuple[str, str]], *, source: Source = SOURCE_PARQUET, ) -> Iterator[_StreamItem]: """Yield ``(local_path, sample_id, (image_bytes, meta))`` as they're ready. Dispatches to the parquet (low-res thumbnail, HTTP range read) path or the tar (high-res JPEG, sequential webdataset stream) path. Both honour the source-aware payload cache and decode images only at the call site. Items are yielded in completion order, not in the input order β€” callers must look up the result slot by ``(local_path, sample_id)``. """ if not pairs: return if source == SOURCE_TAR: yield from _stream_payloads_tar(pairs) else: yield from _stream_payloads_parquet(pairs) def _stream_payloads_parquet(pairs: list[tuple[str, str]]) -> Iterator[_StreamItem]: """Parquet path β€” thumbnail + full row metadata via HTTP range reads. Two-stage pipeline: 1. **Prefetch parquet footers in parallel** β€” each distinct ``local_path`` gets one HTTP round trip to read the parquet metadata + row-group statistics. Cached process-wide so repeat searches skip this entirely. 2. **Stream rows in parallel** β€” once footers are warm, every row read is a single ranged HTTP GET into the right row group. Each completed fetch is yielded immediately, so the UI can render results as they arrive instead of waiting for the slowest one. """ distinct_paths = list({lp for lp, _ in pairs}) uncached = [lp for lp in distinct_paths if lp not in _footer_cache] if uncached: with ThreadPoolExecutor(max_workers=min(DOWNLOAD_WORKERS, len(uncached))) as ex: futs = {ex.submit(_get_footer, lp): lp for lp in uncached} for fut in as_completed(futs): lp = futs[fut] try: fut.result() except Exception as e: # noqa: BLE001 logger.warning("footer prefetch failed for %s: %s", lp, e) workers = min(DOWNLOAD_WORKERS, max(1, len(pairs))) with ThreadPoolExecutor(max_workers=workers) as ex: futures = { ex.submit(_row_payload_cached, lp, sid): (lp, sid) for lp, sid in pairs } for fut in as_completed(futures): lp, sid = futures[fut] try: payload = fut.result() except Exception as e: # noqa: BLE001 logger.warning("row fetch failed for %s/%s: %s", lp, sid, e) payload = (None, {}) yield lp, sid, payload def _stream_payloads_tar(pairs: list[tuple[str, str]]) -> Iterator[_StreamItem]: """Tar (webdataset) path β€” group ids by shard, scan each shard once. A tar shard can't be range-read by name, so the per-row parallelism we use for parquet would be pure waste here (every miss would re-stream the whole shard from byte 0). Instead we group requested ids by shard and dispatch one scan per distinct shard, in parallel across shards. Cache hits are yielded synchronously up front; per-shard completions yield each contained id as soon as the shard finishes scanning. """ by_shard: "OrderedDict[str, list[str]]" = OrderedDict() for lp, sid in pairs: hit = _payload_cache.get((SOURCE_TAR, lp, sid)) if hit is not None: yield lp, sid, hit continue by_shard.setdefault(lp, []).append(sid) if not by_shard: return workers = min(DOWNLOAD_WORKERS, max(1, len(by_shard))) with ThreadPoolExecutor(max_workers=workers) as ex: futures = { ex.submit(_scan_tar, lp, set(sids)): (lp, sids) for lp, sids in by_shard.items() } for fut in as_completed(futures): lp, sids = futures[fut] try: results = fut.result() except Exception as e: # noqa: BLE001 logger.warning("tar scan failed for %s: %s", lp, e) results = {} for sid in sids: payload = results.get(sid, (None, {})) _payload_cache.put((SOURCE_TAR, lp, sid), payload) yield lp, sid, payload def _safe_json(value: object) -> object: """Recursively convert numpy / arrow types into JSON-serializable values.""" if isinstance(value, (np.floating,)): return float(value) if isinstance(value, (np.integer,)): return int(value) if isinstance(value, dict): return {str(k): _safe_json(v) for k, v in value.items()} if isinstance(value, (list, tuple)): return [_safe_json(v) for v in value] if isinstance(value, (bytes, bytearray)): return f"<{len(value)} bytes>" return value # ----------------------------------------------------------------------------- # Search # ----------------------------------------------------------------------------- @spaces.GPU(duration=120) def _embed_query( image: Image.Image | None, text: str | None, model_kind: str ) -> tuple[np.ndarray, str, float, str]: """Run the chosen embedder on the GPU worker. Exactly one of ``image`` / ``text`` must be provided. Text queries are only valid for CLIP-family models (see :data:`TEXT_CAPABLE`). Returns ``(vec, device, ms, query_kind)`` where ``query_kind`` is ``"image"`` or ``"text"``. """ import torch # local import: safe inside @spaces.GPU t0 = time.perf_counter() if text is not None: vec = compute_text_embedding(text, model_kind=model_kind) kind = "text" else: assert image is not None vec = compute_embedding(image, model_kind=model_kind) kind = "image" vec = vec.reshape(1, -1).astype(np.float32) return ( vec, ("cuda" if torch.cuda.is_available() else "cpu"), (time.perf_counter() - t0) * 1000, kind, ) # ----------------------------------------------------------------------------- # Brand palette # ----------------------------------------------------------------------------- BRAND_STOPS: list[tuple[float, str]] = [ (0.00, "#355B9A"), # Dusk Blue (0.10, "#44617E"), # Blue Slate (0.22, "#8FA5BD"), # Cool Steel (0.34, "#A2B8A3"), # Ash Grey (0.46, "#86A49A"), # Muted Teal (0.58, "#B5C77A"), # Soft Willow Green (0.69, "#F1C31A"), # Saffron (single peak β€” interpolation passes through) (0.80, "#B8858A"), # Dusty Rose (0.92, "#D5BEB5"), # Almond Silk (1.00, "#EFE8D0"), # Vanilla Cream ] def _hex_to_rgb_tuple(hex_color: str) -> tuple[int, int, int]: h = hex_color.lstrip("#") return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16) def _brand_gradient_css(angle: int = 135) -> str: """Build a CSS ``linear-gradient(...)`` string from :data:`BRAND_STOPS`.""" parts = [f"{color} {pos * 100:g}%" for pos, color in BRAND_STOPS] return f"linear-gradient({angle}deg, " + ", ".join(parts) + ")" # Anchor hexes pulled from BRAND_STOPS, used for the painterly hero # washes, pill dots and CTA shadows. Keeping them as named constants # makes the generated CSS readable and lets us derive rgba() variants # once. Only the three anchors and the primary-button hover survive β€” the # rest of the palette is delivered as the BRAND_GRADIENT below. BRAND_ROSE = "#B8858A" # Dusty Rose BRAND_BLUE = "#355B9A" # Dusk Blue BRAND_GREEN = "#B5C77A" # Soft Willow Green BRAND_HOVER = "#44617E" # Blue Slate, used as the primary-button hover # UI accent β€” the teal that drives links, the slider, input-focus rings # and the loading spinner. Kept separate from the BRAND_* palette so the # accent and the brand identity can evolve independently. Mirrors the # ``--accent`` / ``slider_color`` / ``link_text_color`` values further # down in the CSS + Gradio theme. ACCENT_TEAL = "#0d9488" # teal-600 BRAND_GRADIENT = _brand_gradient_css(135) _BRAND_ROSE_RGB = ",".join(str(c) for c in _hex_to_rgb_tuple(BRAND_ROSE)) _BRAND_BLUE_RGB = ",".join(str(c) for c in _hex_to_rgb_tuple(BRAND_BLUE)) _BRAND_GREEN_RGB = ",".join(str(c) for c in _hex_to_rgb_tuple(BRAND_GREEN)) # Two stable on-disk placeholders so every yield reuses the same files # (no random UUIDs from Gradio's auto-temp path) and the slot shows up # the moment the browser receives the first frame: # # * ``_LOADER_PATH`` β€” transparent animated SVG, used for slots whose # payload hasn't arrived yet ("still loading"). SMIL # ``<animateTransform>`` runs natively when the file # is loaded via ``<img src>`` in every modern browser. # * ``_FAILED_PATH`` β€” transparent static SVG with a muted "image-off" # glyph, used when a payload arrived but had no # usable bytes (so failed slots don't spin forever, # which would look like "still loading"). # # Both are SVGs with no background fill, so they inherit whatever the # gallery thumbnail surface happens to be β€” no more dark squares on a # light theme. IMAGE_CACHE_DIR.mkdir(parents=True, exist_ok=True) _LOADER_PATH = IMAGE_CACHE_DIR / "_loader.svg" _FAILED_PATH = IMAGE_CACHE_DIR / "_failed.svg" def _render_loader_svg( path: Path, *, n_bars: int = 12, period_s: float = 1.2, color: str = ACCENT_TEAL, ) -> None: """Write a transparent, brand-coloured loading spinner as an SVG file. Design: an iOS-style segmented chase spinner β€” ``n_bars`` rounded radial bars arranged around a center point, each fading from full opacity down to ~20% over the same period, but with their phase staggered by 1/N of the cycle so the "lit" segment appears to chase around the ring. The bar colour defaults to :data:`ACCENT_TEAL` (``teal-600``, the same hue used for links, the slider thumb and input-focus rings) so the spinner reads as part of the same accent family as the rest of the UI rather than competing with the Dusk-Blue brand identity. SMIL animations are self-contained so the spinner runs natively inside ``<img src>`` (no JS, no CSS, no external assets). Geometry note: bars sit between radius 22 and 44 in a 200Γ—200 viewBox (i.e. spinner takes ~44% of the cell), with rounded caps and a 6 px stroke-equivalent width. """ bars: list[str] = [] for i in range(n_bars): angle = i * (360.0 / n_bars) # Each bar starts at a different phase so they appear to chase. # Negative begin offsets put every bar already mid-animation at # SVG load time β€” no "all bars opaque" flash on first paint. begin_s = -(period_s - i * period_s / n_bars) bars.append( f' <rect x="-3" y="-44" width="6" height="22" rx="3" ' f'fill="{color}" transform="rotate({angle:g})">' f'<animate attributeName="opacity" values="1;0.22" ' f'dur="{period_s:g}s" begin="{begin_s:.3f}s" ' f'repeatCount="indefinite"/></rect>' ) bars_xml = "\n".join(bars) svg = f"""<?xml version="1.0" encoding="UTF-8"?> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" preserveAspectRatio="xMidYMid meet" role="img" aria-label="Loading"> <g transform="translate(100 100)"> {bars_xml} </g> </svg> """ path.write_text(svg, encoding="utf-8") def _render_failed_svg(path: Path) -> None: """Write a transparent 'image unavailable' placeholder as an SVG file. A muted Blue Slate image-frame glyph with a Dusty Rose diagonal slash, all stroke-only on a transparent canvas. Same 6 px stroke weight and rounded geometry as the loader so failed and loading slots feel like one icon family rather than two unrelated states. """ svg = f"""<?xml version="1.0" encoding="UTF-8"?> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" preserveAspectRatio="xMidYMid meet" role="img" aria-label="Image unavailable"> <g fill="none" stroke="{BRAND_HOVER}" stroke-opacity="0.32" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"> <rect x="54" y="60" width="92" height="80" rx="12"/> <circle cx="82" cy="88" r="7"/> <path d="M60 132 L92 102 L120 124 L142 108"/> </g> <line x1="58" y1="58" x2="142" y2="142" stroke="{BRAND_ROSE}" stroke-opacity="0.55" stroke-width="6" stroke-linecap="round"/> </svg> """ path.write_text(svg, encoding="utf-8") # Always regenerate on startup so brand-palette tweaks (BRAND_STOPS) take # effect without manual cache cleanup. The files are <2 kB each. _render_loader_svg(_LOADER_PATH) _render_failed_svg(_FAILED_PATH) # Best-effort cleanup of legacy raster placeholders from older builds; a # stale ``_loader.gif`` left in the cache dir would otherwise sit forever # next to the new SVG and confuse anyone inspecting the directory. for _legacy in (IMAGE_CACHE_DIR / "_loader.gif", IMAGE_CACHE_DIR / "_failed.jpg"): try: _legacy.unlink() except FileNotFoundError: pass except OSError as _e: logger.debug("failed to remove legacy placeholder %s: %s", _legacy, _e) # Register the cache dir as a static-paths root so the gallery can serve # ``{hash}.jpg`` files directly. Gradio 6 removed ``allowed_paths`` from # ``gr.Blocks(...)``; ``set_static_paths`` is the module-level replacement # and works regardless of how the app is launched (local ``.launch()`` # *and* HF Spaces, which calls ``.launch()`` itself with no kwargs). gr.set_static_paths([str(IMAGE_CACHE_DIR)]) _FILENAME_SAFE_RE = re.compile(r"[^0-9A-Za-z._-]") def _safe_filename_stem(*candidates: object) -> str: """Return the first non-empty candidate, sanitized for a filesystem path.""" for c in candidates: if not c: continue stem = _FILENAME_SAFE_RE.sub("_", str(c))[:120] if stem: return stem return "image" def _save_result_jpeg( img_bytes: bytes | None, hash_perceptual: str, sample_id: str, ) -> str: """Write ``img_bytes`` to ``{hash_perceptual}.jpg`` and return its path. Falls back to ``{sample_id}.jpg`` when the hash is missing, and to the static *failed* placeholder (not the spinner) when the bytes are missing or invalid β€” that way real failures don't visually look like "still loading forever". JPEG bytes are written verbatim when they already start with the JPEG SOI marker; everything else is decoded with PIL and re-encoded as JPEG so the on-disk extension is honest. """ if not img_bytes: return str(_FAILED_PATH) stem = _safe_filename_stem(hash_perceptual, sample_id) path = IMAGE_CACHE_DIR / f"{stem}.jpg" if path.exists(): return str(path) try: if img_bytes[:3] == b"\xff\xd8\xff": path.write_bytes(img_bytes) else: Image.open(io.BytesIO(img_bytes)).convert("RGB").save( path, format="JPEG", quality=92, ) except Exception as e: # noqa: BLE001 logger.warning("failed to materialise %s: %s", path.name, e) return str(_FAILED_PATH) return str(path) _SearchYield = tuple[ list[tuple[str, str]], list[dict[str, object]], str, ] def search( image: Image.Image | str | None, text: str | None, k: int, model_kind: str, source: str = DEFAULT_SOURCE, ) -> Iterator[_SearchYield]: """Find nearest neighbours and stream their thumbnails + metadata. This is a *generator*: it yields ``(gallery, metadata, status)`` tuples progressively so the UI can render each result as soon as its payload is fetched, instead of waiting for the slowest one. Either an ``image`` or a ``text`` query must be provided. Text queries are only supported by models in :data:`TEXT_CAPABLE` (CLIP today). ``source`` selects the image / metadata source: ``"parquet"`` reads the low-res thumbnail baked into the dataset parquet, ``"tar"`` streams the sibling webdataset shard for the full-resolution JPEG. Yield shape: * **First yield** (after FAISS): all ``k`` slots populated with rank + similarity + a placeholder image, ready for the user to see the shape of the result set. * **Per-completion yields**: each slot's image + full metadata are filled in as their payload arrives. Callers see ``"fetched X / N"`` progress in the status line. * **Final yield**: same gallery + metadata, with a complete timing summary in the status line. """ src = _resolve_source(source) text_q = (text or "").strip() or None if model_kind not in BUNDLES: # Fall back to whatever we did load, rather than 500ing the user. logger.warning( "Model %r not loaded; falling back to %r", model_kind, DEFAULT_MODEL ) model_kind = DEFAULT_MODEL bundle = BUNDLES[model_kind] # Decide which query branch to take. # - Text + text-capable model -> text query. # - Text + non-text-capable model -> ignore the (likely stale) text and # try the image. Only error if neither is usable. # - No text -> image query. if text_q is not None and model_kind in TEXT_CAPABLE: image_arg = None else: if text_q is not None: logger.info( "Ignoring stale text query %r for non-text-capable model %r", text_q[:60], model_kind, ) text_q = None if image is None: raise gr.Error( "Please upload an image (or pick CLIP and enter a text query)." ) if isinstance(image, str): image = Image.open(image) image_arg = image query, embed_device, embed_ms, query_kind = _embed_query( image_arg, text_q, model_kind ) t1 = time.perf_counter() scores, ids = bundle.index.search(query, int(k)) search_ms = (time.perf_counter() - t1) * 1000 keep: list[tuple[int, int, float]] = [] for rank, (row_id, score) in enumerate(zip(ids[0], scores[0]), start=1): if row_id < 0: continue keep.append((rank, int(row_id), float(score))) # Pre-build one slot per FAISS hit (duplicates included). Each slot # gets a placeholder image and the metadata we already know β€” rank, # similarity, identifiers β€” so the layout is stable from yield #1 # and every slot is clickable even before its payload arrives. placeholder_path = str(_LOADER_PATH) gallery: list[tuple[str, str]] = [] metadata: list[dict[str, object]] = [] pair_hashes: dict[tuple[str, str], str] = {} pair_to_slots: dict[tuple[str, str], list[int]] = {} pairs: list[tuple[str, str]] = [] seen_pair: set[tuple[str, str]] = set() for slot, (rank, row_id, score) in enumerate(keep): local_path = str(bundle.local_paths[row_id]) sample_id = str(bundle.ids[row_id]) h = bundle.hashes[row_id] if isinstance(h, bytes): h = h.decode("utf-8", errors="replace") h_str = str(h) gallery.append((placeholder_path, f"#{rank} Β· sim={score:.3f} Β· loading…")) metadata.append( { "rank": rank, "model": model_kind, "similarity": round(score, 4), "row_id": row_id, "id": sample_id, "hash_perceptual": h_str, "local_path": local_path, "loading": True, } ) pair_to_slots.setdefault((local_path, sample_id), []).append(slot) # Remember the hash that should drive the download filename for # this pair (FAISS duplicates of the same id share one hash). pair_hashes.setdefault((local_path, sample_id), h_str) if local_path and sample_id and (local_path, sample_id) not in seen_pair: seen_pair.add((local_path, sample_id)) pairs.append((local_path, sample_id)) query_label = "text" if query_kind == "text" else "image" source_label = "tar (high-res)" if src == SOURCE_TAR else "parquet (low-res)" base_status = ( f"**{MODEL_LABELS.get(model_kind, model_kind)}** " f"({query_label} query Β· {source_label}) Β· " f"Embedded in {embed_ms:.0f} ms on {embed_device} Β· " f"FAISS searched {bundle.index.ntotal:,} vectors in {search_ms:.0f} ms" ) if not pairs: yield list(gallery), list(metadata), f"{base_status} Β· no results." return # Show the placeholder layout immediately; the user sees the result # count + ranks while the first payload is still in flight. yield list(gallery), list(metadata), f"{base_status} Β· fetching 0/{len(pairs)}…" t2 = time.perf_counter() completed = 0 for local_path, sample_id, (img_bytes, meta) in _stream_payloads(pairs, source=src): # Materialise the JPEG on disk under the perceptual hash so the # browser's "download" button picks up ``{hash_perceptual}.jpg`` # (Gradio uses the file's basename for the download filename). h_str = pair_hashes.get((local_path, sample_id), "") img_path = _save_result_jpeg(img_bytes, h_str, sample_id) for slot in pair_to_slots.get((local_path, sample_id), []): rank = metadata[slot]["rank"] score = metadata[slot]["similarity"] gallery[slot] = (img_path, f"#{rank} Β· sim={score:.3f}") slot_meta = {k: v for k, v in metadata[slot].items() if k != "loading"} slot_meta.update({k: _safe_json(v) for k, v in meta.items()}) metadata[slot] = slot_meta completed += 1 # Yield fresh list copies so Gradio sees a new reference each time # and re-renders the gallery / metadata panels reliably. yield ( list(gallery), list(metadata), f"{base_status} Β· fetched {completed}/{len(pairs)} " f"({(time.perf_counter() - t2) * 1000:.0f} ms)…", ) fetch_ms = (time.perf_counter() - t2) * 1000 yield ( list(gallery), list(metadata), f"{base_status} Β· fetched {len(pairs)} row(s) in {fetch_ms:.0f} ms Β· " f"{len(gallery)} result(s).", ) def _on_select( metadata: list[dict[str, object]], evt: gr.SelectData ) -> dict[str, object]: """Return the metadata dict for the gallery item the user clicked on.""" if not metadata: return {} idx = int(evt.index) if evt.index is not None else 0 if idx < 0 or idx >= len(metadata): return {} return metadata[idx] # ----------------------------------------------------------------------------- # UI # ----------------------------------------------------------------------------- # (The brand palette is defined further up β€” before the loader SVG renderer # that consumes it. The CSS below uses those constants via Template # substitution.) # # The CSS is a ``string.Template`` so we can drop the brand colors above # straight into it without escaping every CSS brace. ``${name}`` is the # substitution syntax (CSS has no native ``$``, so there is no clash). _CSS_TEMPLATE = """ /* Refined teal theme with a NymphΓ©as-inspired rose / blue / green gradient * used as the signature accent on the hero and a few selected elements. */ :root { --bg: #f6f9fb; --surface: #ffffff; --surface-2: #f1f5f9; --border: #e2e8f0; --border-soft: #eef2f6; --text: #0b1f23; --muted: #5b6b78; /* Teal β€” used for links, slider, status emphasis. */ --accent: #0d9488; /* teal-600 */ --accent-deep: #115e59; /* teal-800 */ --accent-hover: #0f766e; /* teal-700 */ /* Brand palette (mirrors BRAND_STOPS in app.py). The anchors are the * three painterly washes used on the hero card; the full gradient is * the primary CTA fill. */ --nym-rose: ${brand_rose}; --nym-blue: ${brand_blue}; --nym-green: ${brand_green}; --nym-gradient: ${brand_gradient}; } body, .gradio-container { background: var(--bg) !important; } /* Force light surfaces even when Gradio adds a ``.dark`` class (e.g. when * the visitor's OS / browser is in dark mode). Without this, inputs, * dropdowns and gallery panels render with Gradio's dark palette. */ html.dark, body.dark, .dark .gradio-container { color-scheme: light !important; } .dark, .dark * { --background-fill-primary: #ffffff !important; --background-fill-secondary: #f1f5f9 !important; --body-background-fill: #f8fafc !important; --block-background-fill: #ffffff !important; --block-border-color: #e2e8f0 !important; --input-background-fill: #ffffff !important; --input-border-color: #e2e8f0 !important; --panel-background-fill: #ffffff !important; --body-text-color: #0f172a !important; --block-label-text-color: #64748b !important; --block-title-text-color: #0f172a !important; } .gradio-container { max-width: 100% !important; width: 100% !important; padding: 28px 32px 32px 32px !important; margin: 0 !important; color: var(--text) !important; } .gradio-container a { color: var(--accent); text-decoration: none; font-weight: 500; } .gradio-container a:hover { color: var(--accent-hover); text-decoration: underline; } /* ----- Hero / title bbox ------------------------------------------------- */ /* Painterly NymphΓ©as card: layered radial highlights (rose top-right, * pond-blue mid, sage bottom-left) painted on a white base, with a thicker * gradient spine on the left edge and an inner highlight that lifts the * card off the page. */ #hero { position: relative; background: radial-gradient(60% 90% at 96% 8%, rgba(${brand_rose_rgb},0.28) 0%, rgba(${brand_rose_rgb},0) 60%), radial-gradient(55% 90% at 55% 50%, rgba(${brand_blue_rgb},0.22) 0%, rgba(${brand_blue_rgb},0) 60%), radial-gradient(55% 90% at 6% 95%, rgba(${brand_green_rgb},0.28) 0%, rgba(${brand_green_rgb},0) 60%), #ffffff; border: 1px solid rgba(15,23,42,0.06); border-radius: 20px; padding: 40px 44px 36px 52px; margin-bottom: 24px; box-shadow: inset 0 1px 0 rgba(255,255,255,0.9), 0 1px 2px rgba(15,23,42,0.04), 0 18px 40px -28px rgba(${brand_blue_rgb},0.45); overflow: hidden; } /* Subtle painterly grain so the wash doesn't look like a flat CSS gradient. */ #hero::after { content: ""; position: absolute; inset: 0; background-image: radial-gradient(rgba(15,23,42,0.05) 1px, transparent 1.4px); background-size: 18px 18px; opacity: 0.18; pointer-events: none; mix-blend-mode: multiply; } /* Signature spine: full rose -> blue -> green gradient. */ #hero::before { content: ""; position: absolute; left: 0; top: 0; bottom: 0; width: 6px; background: linear-gradient(180deg, var(--nym-rose) 0%, var(--nym-blue) 50%, var(--nym-green) 100%); } #hero > * { position: relative; z-index: 1; } /* Wordmark image. Sized by height so the brand-gradient bitmap stays * crisp at any viewport; ``width: auto`` preserves the source aspect * ratio, ``max-width: 100%`` keeps it from overflowing the hero card on * narrow screens, and the drop-shadow lifts the (transparent-PNG) logo * off the painterly background just enough to read as foreground. */ #hero .hero-logo { display: block; height: 56px; width: auto; max-width: 100%; margin: 0 0 18px 0; user-select: none; -webkit-user-drag: none; filter: drop-shadow(0 2px 6px rgba(15,23,42,0.08)); } @media (max-width: 720px) { #hero .hero-logo { height: 44px; } } #hero .subtitle { color: var(--muted); font-size: 15.5px; line-height: 1.6; max-width: 880px; } #hero .badges { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 18px; } #hero .badges a { display: inline-flex; line-height: 0; border-radius: 4px; transition: transform 120ms ease, filter 120ms ease; } #hero .badges a:hover { transform: translateY(-1px); filter: brightness(1.05); } #hero .badges img { height: 20px; display: block; } #hero .stats { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 14px; } #hero .pill { display: inline-flex; align-items: center; gap: 8px; padding: 7px 14px; background: rgba(255,255,255,0.78); border: 1px solid rgba(15,23,42,0.08); border-radius: 999px; font-size: 12.5px; color: var(--text); backdrop-filter: blur(6px); -webkit-backdrop-filter: blur(6px); } #hero .pill .label { color: var(--muted); } #hero .pill .value { color: var(--accent-deep); font-weight: 600; font-variant-numeric: tabular-nums; letter-spacing: -0.005em; } #hero .pill .dot { width: 7px; height: 7px; border-radius: 50%; display: inline-block; } #hero .pill .dot.rose { background: var(--nym-rose); box-shadow: 0 0 0 3px rgba(${brand_rose_rgb},0.22); } #hero .pill .dot.blue { background: var(--nym-blue); box-shadow: 0 0 0 3px rgba(${brand_blue_rgb},0.22); } #hero .pill .dot.green { background: var(--nym-green); box-shadow: 0 0 0 3px rgba(${brand_green_rgb},0.22); } /* "Indexed N vectors" pill: keep the same translucent style as the other * pills but emphasize the count itself. */ #hero .pill.solid { padding: 7px 14px; } #hero .pill.solid .label { font-weight: 500; } #hero .pill.solid .value { color: var(--text); font-weight: 700; font-size: 13.5px; } #hero .hero-cta { margin-top: 16px; font-size: 13px; line-height: 1.55; color: var(--muted); } #hero .hero-cta a { font-weight: 500; } /* ----- Panels ------------------------------------------------------------ */ .panel { background: var(--surface) !important; border: 1px solid var(--border) !important; border-radius: 14px !important; padding: 18px !important; box-shadow: inset 0 1px 0 rgba(255,255,255,0.7), 0 1px 2px rgba(15,23,42,0.03), 0 10px 24px -20px rgba(15,23,42,0.18); } .panel-title { font-size: 11px; font-weight: 700; letter-spacing: 0.14em; text-transform: uppercase; color: var(--muted); margin: 2px 4px 14px 4px; display: flex; align-items: center; gap: 10px; } .panel-title::before { content: ""; width: 16px; height: 3px; border-radius: 2px; background: var(--nym-gradient); } /* ----- Status bar -------------------------------------------------------- */ #status-bar { position: relative; font-family: ui-monospace, "JetBrains Mono", SFMono-Regular, Menlo, monospace; font-size: 12.5px; background: linear-gradient(90deg, rgba(${brand_rose_rgb},0.07) 0%, rgba(${brand_blue_rgb},0.07) 50%, rgba(${brand_green_rgb},0.07) 100%), var(--surface); border: 1px solid var(--border-soft); border-radius: 8px; padding: 10px 14px 10px 18px; color: var(--muted); overflow: hidden; } #status-bar::before { content: ""; position: absolute; left: 0; top: 0; bottom: 0; width: 3px; background: var(--nym-gradient); } #status-bar strong { color: var(--accent-deep); font-weight: 600; } /* ----- Misc -------------------------------------------------------------- */ /* Search button: vibrant NymphΓ©as gradient on the primary CTA. */ #search-btn { font-weight: 600 !important; letter-spacing: 0.01em; background: var(--nym-gradient) !important; border: none !important; color: #ffffff !important; text-shadow: 0 1px 1px rgba(15,23,42,0.18); box-shadow: 0 1px 2px rgba(15,23,42,0.08), 0 8px 22px -10px rgba(${brand_blue_rgb},0.55), 0 8px 22px -14px rgba(${brand_rose_rgb},0.45) !important; transition: filter 120ms ease, transform 120ms ease, box-shadow 160ms ease; } #search-btn:hover { filter: brightness(1.05) saturate(1.05); box-shadow: 0 1px 2px rgba(15,23,42,0.10), 0 12px 28px -10px rgba(${brand_blue_rgb},0.70), 0 12px 28px -14px rgba(${brand_rose_rgb},0.55) !important; } #search-btn:active { transform: translateY(1px); } /* Dropdown clearance: reserve room on the right for Gradio's caret icon so * long option labels (e.g. "DINOv2 ViT-G/14 (general)") never collide with * it and render with a phantom strikethrough on narrow columns. */ .gradio-container [data-testid="dropdown"] input, .gradio-container .wrap.svelte-1ipelgc input, .gradio-container .secondary-wrap input { padding-right: 36px !important; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; } #meta-pane { max-height: 520px; overflow: auto; background: var(--surface-2) !important; border: 1px solid var(--border) !important; border-radius: 10px !important; } /* Gallery thumbs: soft rounded corners and a tiny lift on hover so the * grid feels less like a flat image dump and more like a result set. */ .gradio-container .gallery .thumbnail-item, .gradio-container .grid-wrap .thumbnail-item { border-radius: 10px !important; overflow: hidden; border: 1px solid var(--border) !important; box-shadow: 0 1px 2px rgba(15,23,42,0.04); transition: transform 140ms ease, box-shadow 140ms ease; } .gradio-container .gallery .thumbnail-item:hover, .gradio-container .grid-wrap .thumbnail-item:hover { transform: translateY(-2px); box-shadow: 0 8px 20px -10px rgba(${brand_blue_rgb},0.55); } footer { display: none !important; } """ CSS = Template(_CSS_TEMPLATE).safe_substitute( brand_rose=BRAND_ROSE, brand_blue=BRAND_BLUE, brand_green=BRAND_GREEN, brand_gradient=BRAND_GRADIENT, brand_rose_rgb=_BRAND_ROSE_RGB, brand_blue_rgb=_BRAND_BLUE_RGB, brand_green_rgb=_BRAND_GREEN_RGB, ) def build_ui() -> gr.Blocks: model_choices = [(MODEL_LABELS.get(k, k), k) for k in BUNDLES] default_total = BUNDLES[DEFAULT_MODEL].index.ntotal text_capable_in_ui = sorted(set(BUNDLES) & TEXT_CAPABLE) def _text_visible(kind: str) -> bool: return kind in TEXT_CAPABLE # Every light-mode token is duplicated as ``_dark`` so the UI looks # identical regardless of the visitor's OS / browser dark-mode setting. theme = gr.themes.Base( primary_hue=gr.themes.colors.teal, secondary_hue=gr.themes.colors.slate, neutral_hue=gr.themes.colors.slate, font=( gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif", ), font_mono=( gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "monospace", ), ).set( body_background_fill="#f8fafc", body_background_fill_dark="#f8fafc", body_text_color="#0f172a", body_text_color_dark="#0f172a", body_text_color_subdued="#64748b", body_text_color_subdued_dark="#64748b", background_fill_primary="#ffffff", background_fill_primary_dark="#ffffff", background_fill_secondary="#f1f5f9", background_fill_secondary_dark="#f1f5f9", border_color_primary="#e2e8f0", border_color_primary_dark="#e2e8f0", border_color_accent="#0d9488", border_color_accent_dark="#0d9488", block_background_fill="#ffffff", block_background_fill_dark="#ffffff", block_border_color="#e2e8f0", block_border_color_dark="#e2e8f0", block_label_background_fill="#ffffff", block_label_background_fill_dark="#ffffff", block_label_text_color="#64748b", block_label_text_color_dark="#64748b", block_title_text_color="#0f172a", block_title_text_color_dark="#0f172a", block_info_text_color="#64748b", block_info_text_color_dark="#64748b", panel_background_fill="#ffffff", panel_background_fill_dark="#ffffff", panel_border_color="#e2e8f0", panel_border_color_dark="#e2e8f0", input_background_fill="#ffffff", input_background_fill_dark="#ffffff", input_background_fill_focus="#ffffff", input_background_fill_focus_dark="#ffffff", input_background_fill_hover="#ffffff", input_background_fill_hover_dark="#ffffff", input_border_color="#e2e8f0", input_border_color_dark="#e2e8f0", input_border_color_focus="#0d9488", input_border_color_focus_dark="#0d9488", input_placeholder_color="#94a3b8", input_placeholder_color_dark="#94a3b8", button_primary_background_fill=BRAND_BLUE, button_primary_background_fill_dark=BRAND_BLUE, button_primary_background_fill_hover=BRAND_HOVER, button_primary_background_fill_hover_dark=BRAND_HOVER, button_primary_text_color="#ffffff", button_primary_text_color_dark="#ffffff", button_secondary_background_fill="#f1f5f9", button_secondary_background_fill_dark="#f1f5f9", button_secondary_background_fill_hover="#e2e8f0", button_secondary_background_fill_hover_dark="#e2e8f0", button_secondary_text_color="#0f172a", button_secondary_text_color_dark="#0f172a", slider_color="#0d9488", slider_color_dark="#0d9488", color_accent="#0d9488", color_accent_soft="#ccfbf1", color_accent_soft_dark="#ccfbf1", link_text_color="#0d9488", link_text_color_dark="#0d9488", link_text_color_active="#0f766e", link_text_color_active_dark="#0f766e", link_text_color_hover="#0f766e", link_text_color_hover_dark="#0f766e", link_text_color_visited="#0d9488", link_text_color_visited_dark="#0d9488", ) # Strip Gradio's auto-applied ``.dark`` class on load. Without this, # visitors whose browser prefers dark mode would see input/gallery # backgrounds default to Gradio's dark palette even when our theme # tokens specify light values. force_light_js = """ () => { const root = document.documentElement; const body = document.body; root.classList.remove('dark'); body && body.classList.remove('dark'); document.querySelectorAll('.dark').forEach(el => el.classList.remove('dark')); try { localStorage.setItem('theme', 'light'); } catch (e) {} } """ with gr.Blocks( title="MONET retrieval", css=CSS, theme=theme, fill_width=True, js=force_light_js, ) as demo: if _HERO_LOGO_DATA_URL is not None: hero_wordmark = ( f'<img class="hero-logo" src="{_HERO_LOGO_DATA_URL}" ' f'alt="MONET Retrieval" />' ) else: hero_wordmark = ( '<div class="hero-logo" role="img" aria-label="MONET Retrieval" ' 'style="height:auto;font-size:40px;font-weight:700;' 'letter-spacing:-0.02em;color:var(--text);">' "MONET Retrieval</div>" ) gr.HTML(f""" <div id="hero"> {hero_wordmark} <div class="subtitle"> Nearest-neighbour search over the <a href="https://huggingface.co/datasets/jasperai/monet" target="_blank" rel="noopener noreferrer">MONET dataset</a>. Choose an embedder, drop a query image (or a text prompt for CLIP), then click any result for its full metadata. Backed by <a href="https://github.com/facebookresearch/faiss" target="_blank" rel="noopener noreferrer">FAISS</a> indexes hosted on <a href="https://huggingface.co/buckets/jasperai/monet-retrieval-storage" target="_blank" rel="noopener noreferrer">HF Storage</a>. </div> <div class="stats"> <span class="pill solid"> <span class="label">Indexed</span> <span class="value">{default_total:,}</span> <span class="label">vectors</span> </span> <span class="pill solid"> <span class="label">Version</span> <span class="value">{VERSION}</span> </span> <span class="pill"><span class="dot rose"></span><span class="label">DINOv2</span><span class="value">scene similarity</span></span> <span class="pill"><span class="dot blue"></span><span class="label">CLIP</span><span class="value">image &amp; text</span></span> <span class="pill"><span class="dot green"></span><span class="label">SSCD</span><span class="value">copy detection</span></span> </div> <div class="badges"> <a href="https://arxiv.org/abs/2605.21272" target="_blank" rel="noopener noreferrer"><img src="https://img.shields.io/badge/arXiv-2605.21272-b31b1b.svg?logo=arxiv&amp;logoColor=white" alt="Paper" /></a> <a href="https://huggingface.co/datasets/jasperai/monet" target="_blank" rel="noopener noreferrer"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Dataset-MONET-ffcc4d" alt="MONET Dataset" /></a> <a href="https://huggingface.co/spaces/jasperai/monet-umap" target="_blank" rel="noopener noreferrer"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Space-MONET%20UMAP-ffcc4d" alt="MONET UMAP" /></a> <a href="https://github.com/gojasper/nano-t2i" target="_blank" rel="noopener noreferrer"><img src="https://img.shields.io/badge/GitHub-nano--t2i-181717?logo=github&amp;logoColor=white" alt="nano-t2i" /></a> <a href="https://gojasper.github.io/monet/"><img src='https://img.shields.io/badge/Project-page-blue' /> </div> <div class="hero-cta"> Curious how Jasper Research is used in production?<br> <a href="https://developers.jasper.ai/docs/using-images?utm_source=JResearch&amp;utm_medium=CTA&amp;utm_campaign=MONET" target="_blank" rel="noopener noreferrer" aria-label="Discover Jasper APIs for image workflows">Discover Jasper APIs for image workflows</a> </div> </div> """) with gr.Row(equal_height=False): with gr.Column(scale=4, min_width=320, elem_classes=["panel"]): gr.HTML('<div class="panel-title">Query</div>') img_in = gr.Image( type="pil", label="Query image", height=320, sources=["upload", "clipboard"], ) text_in = gr.Textbox( label="…or query by text (CLIP only)", placeholder=( 'e.g. "a watercolor of a fox in a snowy forest"' if text_capable_in_ui else "Enable CLIP to use text queries" ), lines=2, visible=_text_visible(DEFAULT_MODEL), interactive=bool(text_capable_in_ui), ) gr.HTML( '<div class="panel-title" style="margin-top:14px;">Settings</div>' ) model = gr.Dropdown( choices=model_choices, value=DEFAULT_MODEL, label="Embedder", interactive=len(model_choices) > 1, ) k = gr.Slider(1, 50, value=12, step=1, label="k neighbours") source_in = gr.Radio( choices=[ ("Low-res (parquet thumbnails, fast)", SOURCE_PARQUET), ("High-res (tar / webdataset, slower)", SOURCE_TAR), ], value=DEFAULT_SOURCE, label="Image source", info=( "Parquet streams a baked-in thumbnail per row; tar " "reads the full-resolution JPEG from the sibling " "webdataset shard." ), ) btn = gr.Button( "Search", variant="primary", size="lg", elem_id="search-btn" ) if EXAMPLE_IMAGES: gr.HTML( '<div class="panel-title" style="margin-top:14px;">Examples</div>' ) gr.Examples( examples=EXAMPLE_IMAGES, inputs=[img_in], label="", examples_per_page=6, ) with gr.Column(scale=8, min_width=480): with gr.Column(elem_classes=["panel"]): gr.HTML('<div class="panel-title">Nearest neighbours</div>') gallery = gr.Gallery( label=None, show_label=False, columns=4, rows=3, object_fit="cover", height=620, allow_preview=True, preview=False, ) status = gr.Markdown( "Ready. Pick an embedder and drop a query to begin.", elem_id="status-bar", ) with gr.Column(elem_classes=["panel"]): gr.HTML('<div class="panel-title">Selected item metadata</div>') meta_state = gr.State([]) meta_view = gr.JSON( label=None, show_label=False, elem_id="meta-pane" ) # Show the text box only when a text-capable model is selected. # Show the text box only for text-capable models, AND clear its # value on every switch β€” otherwise a leftover prompt from a CLIP # session would silently override a subsequent image search on # DINOv2 / SSCD. def _on_model_change(kind: str) -> dict: if _text_visible(kind): return gr.update(visible=True) return gr.update(visible=False, value="") model.change(_on_model_change, inputs=[model], outputs=[text_in]) btn.click( search, inputs=[img_in, text_in, k, model, source_in], outputs=[gallery, meta_state, status], ) # Submitting via Enter in the text box runs the same search. text_in.submit( search, inputs=[img_in, text_in, k, model, source_in], outputs=[gallery, meta_state, status], ) gallery.select(_on_select, inputs=[meta_state], outputs=[meta_view]) return demo demo = build_ui().queue(max_size=16) if __name__ == "__main__": demo.launch( server_name="0.0.0.0", server_port=7860, share=False, allowed_paths=[str(IMAGE_CACHE_DIR)], )
"""Gradio app: upload an image, find nearest neighbours among MONET embeddings.
Three embedders are wired up β€” DINOv2 ViT-G/14 (general retrieval), OpenCLIP
ViT-B/32 (image / text alignment) and SSCD (copy-detection). They share a
single row ordering, so one alignment parquet at the bucket root maps
``row_id β†’ (id, local_path, hash_perceptual)`` for all of them::
<DATA_ROOT>/
β”œβ”€β”€ aligned_paths.parquet # shared row_id -> (id, path, hash)
β”œβ”€β”€ dinov2/
β”‚ β”œβ”€β”€ embedding_dinov2-vitg14.faiss
β”‚ └── meta.json
β”œβ”€β”€ clip/ …
└── sscd/ …
The alignment file is built once offline by ``scripts/build_alignment.py``
and synced to the bucket; the app just memory-maps it at startup. There is
no runtime fallback that rebuilds the alignment from per-model hashes β€”
the bucket MUST ship ``aligned_paths.parquet``.
Hot path on every search:
1. Embed the query image on the GPU worker (``@spaces.GPU``).
2. FAISS search the chosen index.
3. For each neighbour, range-read a single row group from its dataset parquet
on the Hub (no full file download), extract the ``thumbnail`` blob and
metadata. Results are LRU-cached so repeat searches are instant.
"""
from __future__ import annotations
import base64
import io
import json
import logging
import mimetypes
import os
import re
import shutil
import sys
import threading
import time
from collections import OrderedDict
from collections.abc import Iterator
from concurrent.futures import ThreadPoolExecutor, as_completed
from functools import lru_cache
from pathlib import Path
from string import Template
from typing import Literal, get_args
# CPython 3.12 has a known bug where BaseEventLoop.__del__ raises
# "ValueError: Invalid file descriptor: -1" when GC'ing an event loop whose
# self-pipe was already closed (e.g. by httpx / spaces / forked workers).
# These tracebacks are harmless but spam the logs via sys.unraisablehook.
# https://github.com/python/cpython/issues/114177
_default_unraisablehook = sys.unraisablehook
def _silence_loop_fd_unraisable(unraisable: "sys.UnraisableHookArgs") -> None:
exc = unraisable.exc_value
if (
isinstance(exc, ValueError)
and "Invalid file descriptor: -1" in str(exc)
and getattr(unraisable.object, "__qualname__", "") == "BaseEventLoop.__del__"
):
return
_default_unraisablehook(unraisable)
sys.unraisablehook = _silence_loop_fd_unraisable
import faiss
import gradio as gr
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import spaces
from huggingface_hub import HfFileSystem, hf_hub_download
from PIL import Image
from embedders import (
MODEL_DIMS,
MODEL_LABELS,
TEXT_CAPABLE,
compute_embedding,
compute_text_embedding,
preload,
)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
)
# Silence per-request HTTP chatter from upstream libraries (huggingface_hub,
# datasets, fsspec, etc.). They emit one INFO line per parquet/range fetch,
# which floods the terminal during gallery loads.
for _noisy in ("httpx", "httpcore", "urllib3", "hf_transfer", "huggingface_hub"):
logging.getLogger(_noisy).setLevel(logging.WARNING)
logger = logging.getLogger("MONET-retrieval.app")