Spaces:
Running
Running
Deploy eval-entity-registry service
Browse filesFiles changed (2)
20 unmodified lines2122232425262728293031323334353637383940414243444546474849505152535455565758596061626364340 unmodified lines4054064074084094104114124134144154164174184194204214224234244254264274284294304314327 unmodified lines44044144244344444544644744844945045145245345445545645745845946046146246346420 unmodified linesfrom datetime import datetime, datefrom typing import Optional# Live-lookup source for the deployed Space's `HubStatsClient` ONLY. This is# the HF parquet-converter endpoint, which answers 400 for several minutes after# ANY commit to the upstream dataset (daily, ~13:18β13:36 UTC) while the# dataset-viewer rebuilds `refs/convert/parquet`. The bulk scripts (refresh /# index / freeze) therefore do NOT read it: they download a pinned snapshot of# `main/models.parquet` via `services/hub_stats_snapshot.py` (same bytes; see# specs/hub-stats-snapshot-fetch.md). The client tolerates the window because a# lookup failure degrades to "no enrichment".PARQUET_URL = ("https://huggingface.co/api/datasets/cfahlgren1/hub-stats/parquet/models/train/0.parquet")# Offline read path: when HUB_STATS_LOCAL_PARQUET points at a local hub-stats# parquet, every# hub-stats query (bulk refresh + live HubStatsClient lookup) reads that file# instead of streaming the live URL. CI / the deployed Space leave the env unset# and keep the live path. The env var is read at call time (not import time) so# tests can set/unset it per-test without reimporting the module.HUB_STATS_LOCAL_PARQUET_ENV = "HUB_STATS_LOCAL_PARQUET"def resolve_parquet_source(parquet_url: str = PARQUET_URL) -> str:"""Return the parquet source DuckDB should `read_parquet()` from.Prefers the local file at `$HUB_STATS_LOCAL_PARQUET` when that env var isset and the file exists (offline mode); otherwise the passed-in live URL.A set-but-missing path falls through to the live URL so a stale env varnever silently breaks the live path."""local = os.environ.get(HUB_STATS_LOCAL_PARQUET_ENV)if local and os.path.exists(local):return localreturn parquet_urldef is_local_parquet() -> bool:"""True when the offline local-parquet read path is active."""local = os.environ.get(HUB_STATS_LOCAL_PARQUET_ENV)return bool(local and os.path.exists(local))# Columns the queries fetch. Centralized so the bulk and lookup paths# parse the same row shape.340 unmodified linesclass HubStatsClient:"""Single-id lookup against the hub-stats parquet via DuckDB.Materializes the remote parquet into a local DuckDB table on firstuse, then serves all subsequent lookups against the local copy.Trade-off: one bulk fetch (large but a single HTTP transaction)instead of N per-id range-fetch queries (small but rate-limit-pronewhen N is in the thousands β `huggingface.co` 429s aggressively onthe parquet API even with auth, and DuckDB's range-fetch patterncounts as multiple HTTP HEAD/GET requests per logical query).On bulk-fetch failure, falls back to per-id remote queries (olderbehaviour) so the client degrades gracefully rather than goingsilent. Per-id fallback retains the same in-process cache.Failure mode: any DuckDB error (network down, parquet schema drift,etc.) returns None from `lookup()` and is logged. Callers musthandle None as "no enrichment data available" β never raise."""def __init__(self, parquet_url: str = PARQUET_URL) -> None:# Resolve the offline local-parquet path here (at construction) AND# again at query time β the env-aware `resolve_parquet_source` makes the# offline switch transparent to all the `read_parquet('{self.parquet_url}')`# call sites below without touching their SQL.self.parquet_url = resolve_parquet_source(parquet_url)self._con = Noneself._local_table_ready: bool = Falseself._local_table_failed: bool = False7 unmodified lines# the duckdb import cost.import osimport duckdbcon = duckdb.connect()# Reading a LOCAL parquet needs no httpfs / HF auth β skip the network# extension install so the offline path works with no connectivity.if is_local_parquet():self._con = conreturn concon.execute("INSTALL httpfs; LOAD httpfs;")# Authenticate parquet fetches when HF_TOKEN is in the environment# (typical on the deployed Space). Unauth limit is 500 req/5min;# one DuckDB read_parquet against the remote file streams via# several range requests and a sync that auto-creates many drafts# can brush that ceiling. With auth the ceiling is ~30k/5min.hf_token = os.environ.get("HF_TOKEN")if hf_token:escaped = hf_token.replace("'", "''")con.execute(f"CREATE SECRET hf_auth (TYPE HTTP, BEARER_TOKEN '{escaped}', "f"SCOPE 'https://huggingface.co');")self._con = conreturn con20 unmodified lines212223242526272829303132333435363738394041424344454647484950515253545556340 unmodified lines3973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304317 unmodified lines43944044144244344444544644744844945045145245345445545645745845946046146246346446546646720 unmodified linesfrom datetime import datetime, datefrom typing import Optional# Where hub-stats bytes come from β NEVER the HF parquet-converter endpoint# (the `/api/datasets/<repo>/parquet/<config>/<split>/<n>.parquet` URL), which# answers 400 for several minutes after ANY commit to the upstream dataset# (daily, ~13:18β13:36 UTC) while the dataset-viewer rebuilds# `refs/convert/parquet`. Every reader pins a commit sha of `main/models.parquet`# (same bytes) via `services/hub_stats_snapshot.py`: the bulk scripts download# it; the live `HubStatsClient` below range-reads the pinned `hf://` path. See# specs/hub-stats-snapshot-fetch.md.# Offline read path: when HUB_STATS_LOCAL_PARQUET points at a local hub-stats# parquet, every hub-stats query (bulk refresh + live HubStatsClient lookup)# reads that file instead of the pinned remote snapshot. CI / the deployed Space# leave the env unset. The env var is read at call time (not import time) so# tests can set/unset it per-test without reimporting the module.HUB_STATS_LOCAL_PARQUET_ENV = "HUB_STATS_LOCAL_PARQUET"def local_parquet_path() -> Optional[str]:"""The offline local parquet path when `$HUB_STATS_LOCAL_PARQUET` is setAND the file exists; else None. A set-but-missing path is ignored so astale env var never silently breaks the live path."""local = os.environ.get(HUB_STATS_LOCAL_PARQUET_ENV)if local and os.path.exists(local):return localreturn Nonedef is_local_parquet() -> bool:"""True when the offline local-parquet read path is active."""return local_parquet_path() is not None# Columns the queries fetch. Centralized so the bulk and lookup paths# parse the same row shape.340 unmodified linesclass HubStatsClient:"""Single-id lookup against the hub-stats parquet via DuckDB.Used only by draft enrichment (`_auto_create_entity`), i.e. in WRITEmode β a `sync` run. The deployed read-only Space never instantiates it(read-only resolves confirm HF ids against the published`hub_stats_index` table instead).Source: a PINNED commit of `cfahlgren1/hub-stats` `main/models.parquet`,resolved on first use (`hf://datasets/<repo>@<sha>/models.parquet`), orthe local file at `$HUB_STATS_LOCAL_PARQUET`. Never the HFparquet-converter endpoint (400s after every upstream commit β see themodule comment). Pinning means a mid-sync upstream commit cannot swapthe file under the bulk load.Materializes the parquet into a local DuckDB table on first use, thenserves all subsequent lookups against the local copy. Trade-off: onebulk fetch instead of N per-id range-fetch queries (rate-limit-prone whenN is in the thousands; the Hub's `ratelimit-policy` header gives theper-bucket limits). On bulk-fetch failure, falls back to per-id remotequeries against the same pinned source so the client degrades gracefullyrather than going silent. Per-id fallback retains the same in-processcache.Failure mode: any DuckDB / network error (incl. failing to resolve thesnapshot) returns None from `lookup()` and is logged. Callers musthandle None as "no enrichment data available" β never raise."""def __init__(self, parquet_url: Optional[str] = None) -> None:# Explicit source > offline local file > (lazily, on first use) the# pinned remote snapshot. Construction never touches the network.self.parquet_url: Optional[str] = parquet_url or local_parquet_path()self._con = Noneself._local_table_ready: bool = Falseself._local_table_failed: bool = False7 unmodified lines# the duckdb import cost.import osimport duckdbfrom eval_entity_registry.services.hub_stats_snapshot import (hf_source,is_remote_source,resolve_snapshot,)hf_token = os.environ.get("HF_TOKEN")if self.parquet_url is None:# One resolver-bucket HEAD; pins the sha for this client's lifetime.self.parquet_url = hf_source(resolve_snapshot(token=hf_token))con = duckdb.connect()# Reading a LOCAL parquet needs no httpfs / HF auth β skip the network# extension install so the offline path works with no connectivity.if not is_remote_source(self.parquet_url):self._con = conreturn concon.execute("INSTALL httpfs; LOAD httpfs;")# Authenticate the `hf://` reads when HF_TOKEN is in the environment# (typical on a sync host): DuckDB's HUGGINGFACE secret type sends the# bearer to the resolve endpoint and not to the CDN redirect target.if hf_token:escaped = hf_token.replace("'", "''")con.execute(f"CREATE SECRET hf_auth (TYPE HUGGINGFACE, TOKEN '{escaped}');")self._con = conreturn con
12345678910111213141516171819"""Pinned, local snapshot of `cfahlgren1/hub-stats` for the bulk scripts.Why this exists (see specs/hub-stats-snapshot-fetch.md): the HF parquet-converterendpoint (`/api/datasets/<repo>/parquet/<config>/<split>/<n>.parquet`, the`PARQUET_URL` the live `HubStatsClient` still uses) answers 400 for severalminutes after *any* commit to the upstream dataset β the dataset-viewer deletesand rebuilds the whole `refs/convert/parquet` branch. Upstream commits six filesevery day around 13:18β13:36 UTC, and the crons regularly fired inside thatwindow. The raw `main/models.parquet` is byte-identical to the converted fileand lives on a path the viewer never touches.The scripts therefore (1) resolve the dataset's current commit sha + the file'scontent hash in ONE resolver-bucket request, (2) short-circuit on an unchangedhash, else (3) `hf_hub_download` the file at that pinned sha (one resumable,hash-verified stream) and query it locally. Nothing here is used by thedeployed Space."""from __future__ import annotations1234567891011121314151617181920"""Pinned, local snapshot of `cfahlgren1/hub-stats` for the bulk scripts.Why this exists (see specs/hub-stats-snapshot-fetch.md): the HF parquet-converterendpoint (`/api/datasets/<repo>/parquet/<config>/<split>/<n>.parquet`) answers400 for several minutes after *any* commit to the upstream dataset β thedataset-viewer deletes and rebuilds the whole `refs/convert/parquet` branch.Upstream commits six files every day around 13:18β13:36 UTC, and the cronsregularly fired inside that window. The raw `main/models.parquet` isbyte-identical to the converted file and lives on a path the viewer nevertouches.The bulk scripts (1) resolve the dataset's current commit sha + the file'scontent hash in ONE resolver-bucket request, (2) short-circuit on an unchangedhash, else (3) `hf_hub_download` the file at that pinned sha (one resumable,hash-verified stream) and query it locally. The write-mode live`HubStatsClient` (draft enrichment during `sync`) resolves the same pinned shaand range-reads `hf_source(snap)` instead of downloading."""from __future__ import annotations
src/eval_entity_registry/services/hub_stats.py+59-56
src/eval_entity_registry/services/hub_stats_snapshot.py+12-11