"""TailorRig explorer server: static UI, the sample catalog, and on-demand sample extraction. Every sample is one DEFLATE entry inside its subset's zip on the Hub. data/index.json (built by tools/build_index.py) records where each entry starts, so loading a sample is a single HTTP range read against the pinned dataset revision, followed by inflate + repack (rigconv.pack). Packed samples are cached gzipped on local disk with LRU eviction. """ import gzip, json, os, shutil, threading, time from fastapi import FastAPI, HTTPException from fastapi.responses import FileResponse, JSONResponse, Response from fastapi.staticfiles import StaticFiles from huggingface_hub import HfFileSystem import rigconv HERE = os.path.dirname(os.path.abspath(__file__)) DATA = os.path.join(HERE, "data") INDEX = json.load(open(os.path.join(DATA, "index.json"))) REPO, REV = INDEX["repo"], INDEX["revision"] ITEMS = INDEX["items"] BY_KEY = {(it["s"], it["u"]): it for it in ITEMS} CACHE = os.environ.get("SAMPLE_CACHE", "/tmp/samplecache") CACHE_CAP = int(float(os.environ.get("SAMPLE_CACHE_GB", "20")) * 2**30) os.makedirs(CACHE, exist_ok=True) def build_catalog(): """Columnar, compact catalog for client-side search and facets.""" subsets = list(INDEX["subsets"]) groups = sorted({g for it in ITEMS for g in it["x"]}) gid = {g: i for i, g in enumerate(groups)} cols = {k: [] for k in ("s", "u", "v", "f", "j", "b", "nnz", "h", "fing", "toes", "x", "o", "c")} for it in ITEMS: cols["s"].append(subsets.index(it["s"])) cols["x"].append([gid[g] for g in it["x"]]) for k in ("u", "v", "f", "j", "b", "nnz", "h", "fing", "toes"): cols[k].append(it[k]) cols["o"].append(it["off"]) cols["c"].append(it["cs"]) cat = {"repo": REPO, "revision": REV, "thumb": INDEX["thumb"], "subsets": subsets, "groups": groups, "cols": cols} return gzip.compress(json.dumps(cat, separators=(",", ":")).encode(), 6) CATALOG_GZ = build_catalog() fs = HfFileSystem() _locks, _locks_guard = {}, threading.Lock() _sem = threading.Semaphore(4) def _lock(key): with _locks_guard: return _locks.setdefault(key, threading.Lock()) def _evict(): entries = [] for e in os.scandir(CACHE): if e.is_file(): st = e.stat() entries.append((st.st_atime, st.st_size, e.path)) total = sum(e[1] for e in entries) for _, size, p in sorted(entries): if total <= CACHE_CAP: break try: os.remove(p) total -= size except OSError: pass def cache_path(it): safe = it["u"].replace("/", "_") return os.path.join(CACHE, f"{it['s']}__{safe}.trig.gz") def ensure_sample(it): p = cache_path(it) if os.path.exists(p): return p with _lock(p): if os.path.exists(p): return p t = time.time() path = f"datasets/{REPO}@{REV}/{it['s']}/npz_public.zip" start, end = rigconv.entry_range(it["off"], it["cs"]) with _sem: for attempt in range(4): try: blob = fs.cat_file(path, start=start, end=end) break except Exception as e: # transient Hub errors if attempt == 3: raise HTTPException(502, f"Could not read the sample from the Hub: {e}") time.sleep(1.5 * 2**attempt) t_fetch = time.time() - t d = rigconv.load_npz(rigconv.inflate_entry(blob, it["cs"])) packed = rigconv.pack(d, it["s"]) tmp = p + ".part" with gzip.open(tmp, "wb", compresslevel=4) as f: f.write(packed) os.replace(tmp, p) print(f"sample {it['s']}/{it['u']}: {it['cs']/1e6:.1f} MB fetched in {t_fetch:.2f}s, " f"packed {len(packed)/1e6:.1f} MB, total {time.time()-t:.2f}s", flush=True) _evict() return p app = FastAPI(docs_url=None, redoc_url=None) @app.get("/api/sample/{subset}/{uuid}") def sample(subset: str, uuid: str): it = BY_KEY.get((subset, uuid)) if not it: raise HTTPException(404, "No such sample.") p = ensure_sample(it) return FileResponse(p, media_type="application/octet-stream", headers={ "Content-Encoding": "gzip", "Cache-Control": "public, max-age=604800, immutable"}) @app.get("/data/catalog.json") def catalog(): return Response(CATALOG_GZ, media_type="application/json", headers={"Content-Encoding": "gzip", "Cache-Control": "public, max-age=3600"}) @app.get("/api/health") def health(): du = shutil.disk_usage(CACHE) n = sum(1 for e in os.scandir(CACHE) if e.name.endswith(".trig.gz")) return JSONResponse({"repo": REPO, "revision": REV, "items": len(ITEMS), "subsets": {k: v["count"] for k, v in INDEX["subsets"].items()}, "cached_samples": n, "disk_free_gb": round(du.free / 2**30, 1)}) class CachedStatic(StaticFiles): def __init__(self, *a, long_cache=("vendor/",), **kw): super().__init__(*a, **kw) self.long_cache = long_cache async def get_response(self, path, scope): r = await super().get_response(path, scope) if path.startswith(self.long_cache): r.headers["Cache-Control"] = "public, max-age=86400" return r app.mount("/thumbs", CachedStatic(directory=os.path.join(DATA, "thumbs"), long_cache=("",)), name="thumbs") app.mount("/", CachedStatic(directory=os.path.join(HERE, "static"), html=True), name="static")