Spaces:
Running
Running
Deploy eval-entity-registry service
Browse files
src/eval_entity_registry/services/hub_stats.py
CHANGED
|
@@ -21,27 +21,15 @@ import threading
|
|
| 21 |
from datetime import datetime, date
|
| 22 |
from typing import Optional
|
| 23 |
|
| 24 |
-
# Where hub-stats bytes come from — NEVER the HF parquet-converter endpoint
|
| 25 |
-
# (the `/api/datasets/<repo>/parquet/<config>/<split>/<n>.parquet` URL), which
|
| 26 |
-
# answers 400 for several minutes after ANY commit to the upstream dataset
|
| 27 |
-
# (daily, ~13:18–13:36 UTC) while the dataset-viewer rebuilds
|
| 28 |
-
# `refs/convert/parquet`. Every reader pins a commit sha of `main/models.parquet`
|
| 29 |
-
# (same bytes) via `services/hub_stats_snapshot.py`: the bulk scripts download
|
| 30 |
-
# it; the live `HubStatsClient` below range-reads the pinned `hf://` path. See
|
| 31 |
-
# specs/hub-stats-snapshot-fetch.md.
|
| 32 |
-
|
| 33 |
# Offline read path: when HUB_STATS_LOCAL_PARQUET points at a local hub-stats
|
| 34 |
-
# parquet, every hub-stats query
|
| 35 |
-
#
|
| 36 |
-
#
|
| 37 |
-
# tests can set/unset it per-test without reimporting the module.
|
| 38 |
HUB_STATS_LOCAL_PARQUET_ENV = "HUB_STATS_LOCAL_PARQUET"
|
| 39 |
|
| 40 |
|
| 41 |
def local_parquet_path() -> Optional[str]:
|
| 42 |
-
"""
|
| 43 |
-
AND the file exists; else None. A set-but-missing path is ignored so a
|
| 44 |
-
stale env var never silently breaks the live path."""
|
| 45 |
local = os.environ.get(HUB_STATS_LOCAL_PARQUET_ENV)
|
| 46 |
if local and os.path.exists(local):
|
| 47 |
return local
|
|
@@ -397,34 +385,22 @@ def extract_base_models(base_models) -> list[dict]:
|
|
| 397 |
class HubStatsClient:
|
| 398 |
"""Single-id lookup against the hub-stats parquet via DuckDB.
|
| 399 |
|
| 400 |
-
Used
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
`
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
Materializes the parquet into a local DuckDB table on first use, then
|
| 413 |
-
serves all subsequent lookups against the local copy. Trade-off: one
|
| 414 |
-
bulk fetch instead of N per-id range-fetch queries (rate-limit-prone when
|
| 415 |
-
N is in the thousands; the Hub's `ratelimit-policy` header gives the
|
| 416 |
-
per-bucket limits). On bulk-fetch failure, falls back to per-id remote
|
| 417 |
-
queries against the same pinned source so the client degrades gracefully
|
| 418 |
-
rather than going silent. Per-id fallback retains the same in-process
|
| 419 |
-
cache.
|
| 420 |
-
|
| 421 |
-
Failure mode: any DuckDB / network error (incl. failing to resolve the
|
| 422 |
-
snapshot) returns None from `lookup()` and is logged. Callers must
|
| 423 |
-
handle None as "no enrichment data available" — never raise."""
|
| 424 |
|
| 425 |
def __init__(self, parquet_url: Optional[str] = None) -> None:
|
| 426 |
-
# Explicit source >
|
| 427 |
-
#
|
| 428 |
self.parquet_url: Optional[str] = parquet_url or local_parquet_path()
|
| 429 |
self._con = None
|
| 430 |
self._local_table_ready: bool = False
|
|
@@ -447,18 +423,12 @@ class HubStatsClient:
|
|
| 447 |
|
| 448 |
hf_token = os.environ.get("HF_TOKEN")
|
| 449 |
if self.parquet_url is None:
|
| 450 |
-
# One resolver-bucket HEAD; pins the sha for this client's lifetime.
|
| 451 |
self.parquet_url = hf_source(resolve_snapshot(token=hf_token))
|
| 452 |
con = duckdb.connect()
|
| 453 |
-
# Reading a LOCAL parquet needs no httpfs / HF auth — skip the network
|
| 454 |
-
# extension install so the offline path works with no connectivity.
|
| 455 |
if not is_remote_source(self.parquet_url):
|
| 456 |
-
self._con = con
|
| 457 |
return con
|
| 458 |
con.execute("INSTALL httpfs; LOAD httpfs;")
|
| 459 |
-
# Authenticate the `hf://` reads when HF_TOKEN is in the environment
|
| 460 |
-
# (typical on a sync host): DuckDB's HUGGINGFACE secret type sends the
|
| 461 |
-
# bearer to the resolve endpoint and not to the CDN redirect target.
|
| 462 |
if hf_token:
|
| 463 |
escaped = hf_token.replace("'", "''")
|
| 464 |
con.execute(f"CREATE SECRET hf_auth (TYPE HUGGINGFACE, TOKEN '{escaped}');")
|
|
|
|
| 21 |
from datetime import datetime, date
|
| 22 |
from typing import Optional
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
# Offline read path: when HUB_STATS_LOCAL_PARQUET points at a local hub-stats
|
| 25 |
+
# parquet, every hub-stats query reads that file instead of the pinned remote
|
| 26 |
+
# snapshot (services/hub_stats_snapshot.py). Read at call time so tests can
|
| 27 |
+
# set/unset it per test.
|
|
|
|
| 28 |
HUB_STATS_LOCAL_PARQUET_ENV = "HUB_STATS_LOCAL_PARQUET"
|
| 29 |
|
| 30 |
|
| 31 |
def local_parquet_path() -> Optional[str]:
|
| 32 |
+
"""`$HUB_STATS_LOCAL_PARQUET` when set and the file exists; else None."""
|
|
|
|
|
|
|
| 33 |
local = os.environ.get(HUB_STATS_LOCAL_PARQUET_ENV)
|
| 34 |
if local and os.path.exists(local):
|
| 35 |
return local
|
|
|
|
| 385 |
class HubStatsClient:
|
| 386 |
"""Single-id lookup against the hub-stats parquet via DuckDB.
|
| 387 |
|
| 388 |
+
Used by draft enrichment in write mode (a `sync` run); the read-only Space
|
| 389 |
+
confirms HF ids against the published `hub_stats_index` table instead.
|
| 390 |
+
|
| 391 |
+
Source: a pinned commit of `main/models.parquet` resolved on first use
|
| 392 |
+
(`hf://datasets/<repo>@<sha>/...`), or `$HUB_STATS_LOCAL_PARQUET`.
|
| 393 |
+
The parquet is materialized into a local DuckDB table on first use (one
|
| 394 |
+
bulk fetch instead of thousands of per-id range reads); if that fails,
|
| 395 |
+
lookups fall back to per-id remote queries against the same pinned source.
|
| 396 |
+
|
| 397 |
+
Any DuckDB or network error, including failing to resolve the snapshot,
|
| 398 |
+
makes `lookup()` return None and log. Callers treat None as "no
|
| 399 |
+
enrichment available"; it never raises."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 400 |
|
| 401 |
def __init__(self, parquet_url: Optional[str] = None) -> None:
|
| 402 |
+
# Explicit source > local file > pinned snapshot resolved lazily in
|
| 403 |
+
# _ensure_con. Construction never touches the network.
|
| 404 |
self.parquet_url: Optional[str] = parquet_url or local_parquet_path()
|
| 405 |
self._con = None
|
| 406 |
self._local_table_ready: bool = False
|
|
|
|
| 423 |
|
| 424 |
hf_token = os.environ.get("HF_TOKEN")
|
| 425 |
if self.parquet_url is None:
|
|
|
|
| 426 |
self.parquet_url = hf_source(resolve_snapshot(token=hf_token))
|
| 427 |
con = duckdb.connect()
|
|
|
|
|
|
|
| 428 |
if not is_remote_source(self.parquet_url):
|
| 429 |
+
self._con = con # local file: no httpfs, no auth
|
| 430 |
return con
|
| 431 |
con.execute("INSTALL httpfs; LOAD httpfs;")
|
|
|
|
|
|
|
|
|
|
| 432 |
if hf_token:
|
| 433 |
escaped = hf_token.replace("'", "''")
|
| 434 |
con.execute(f"CREATE SECRET hf_auth (TYPE HUGGINGFACE, TOKEN '{escaped}');")
|
src/eval_entity_registry/services/hub_stats_snapshot.py
CHANGED
|
@@ -1,20 +1,14 @@
|
|
| 1 |
-
"""Pinned
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
endpoint (`/api/datasets/<repo>/parquet/
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
The bulk scripts (1) resolve the dataset's current commit sha + the file's
|
| 13 |
-
content hash in ONE resolver-bucket request, (2) short-circuit on an unchanged
|
| 14 |
-
hash, else (3) `hf_hub_download` the file at that pinned sha (one resumable,
|
| 15 |
-
hash-verified stream) and query it locally. The write-mode live
|
| 16 |
-
`HubStatsClient` (draft enrichment during `sync`) resolves the same pinned sha
|
| 17 |
-
and range-reads `hf_source(snap)` instead of downloading.
|
| 18 |
"""
|
| 19 |
from __future__ import annotations
|
| 20 |
|
|
@@ -47,8 +41,7 @@ def resolve_snapshot(
|
|
| 47 |
token: Optional[str] = None,
|
| 48 |
) -> HubStatsSnapshot:
|
| 49 |
"""One HEAD on `resolve/main/<filename>` → commit sha, LFS sha256, size.
|
| 50 |
-
Raises RuntimeError if
|
| 51 |
-
want to see loudly, not paper over)."""
|
| 52 |
from huggingface_hub import get_hf_file_metadata, hf_hub_url
|
| 53 |
|
| 54 |
url = hf_hub_url(repo_id, filename, repo_type="dataset")
|
|
@@ -72,9 +65,8 @@ def download_snapshot(
|
|
| 72 |
token: Optional[str] = None,
|
| 73 |
cache_dir: Optional[str | os.PathLike] = None,
|
| 74 |
) -> HubStatsSnapshot:
|
| 75 |
-
"""`hf_hub_download` the file at the snapshot's pinned sha
|
| 76 |
-
|
| 77 |
-
size check as a cheap belt-and-braces guard."""
|
| 78 |
from huggingface_hub import hf_hub_download
|
| 79 |
|
| 80 |
path = Path(
|
|
@@ -96,10 +88,8 @@ def download_snapshot(
|
|
| 96 |
|
| 97 |
|
| 98 |
def hf_source(snap: HubStatsSnapshot) -> str:
|
| 99 |
-
"""DuckDB
|
| 100 |
-
|
| 101 |
-
`CREATE SECRET (TYPE HUGGINGFACE, TOKEN ...)` for authenticated reads. The
|
| 102 |
-
crons do not use this; they download."""
|
| 103 |
return f"hf://datasets/{snap.repo_id}@{snap.revision}/{snap.filename}"
|
| 104 |
|
| 105 |
|
|
|
|
| 1 |
+
"""Pinned snapshot of `cfahlgren1/hub-stats` `main/models.parquet`.
|
| 2 |
+
|
| 3 |
+
All hub-stats readers go through here instead of the HF parquet-converter
|
| 4 |
+
endpoint (`/api/datasets/<repo>/parquet/...`): the dataset-viewer rebuilds that
|
| 5 |
+
endpoint after every upstream commit and it answers 400 meanwhile, which hit
|
| 6 |
+
the daily crons. The raw file is byte-identical and never rebuilt.
|
| 7 |
+
|
| 8 |
+
`resolve_snapshot` pins a commit sha and the file's content hash in one
|
| 9 |
+
request; `download_snapshot` fetches that exact revision for local queries;
|
| 10 |
+
`hf_source` is the equivalent pinned `hf://` path for a caller that prefers
|
| 11 |
+
range reads.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
"""
|
| 13 |
from __future__ import annotations
|
| 14 |
|
|
|
|
| 41 |
token: Optional[str] = None,
|
| 42 |
) -> HubStatsSnapshot:
|
| 43 |
"""One HEAD on `resolve/main/<filename>` → commit sha, LFS sha256, size.
|
| 44 |
+
Raises RuntimeError if any of them is missing."""
|
|
|
|
| 45 |
from huggingface_hub import get_hf_file_metadata, hf_hub_url
|
| 46 |
|
| 47 |
url = hf_hub_url(repo_id, filename, repo_type="dataset")
|
|
|
|
| 65 |
token: Optional[str] = None,
|
| 66 |
cache_dir: Optional[str | os.PathLike] = None,
|
| 67 |
) -> HubStatsSnapshot:
|
| 68 |
+
"""`hf_hub_download` the file at the snapshot's pinned sha, then check its
|
| 69 |
+
size against the snapshot."""
|
|
|
|
| 70 |
from huggingface_hub import hf_hub_download
|
| 71 |
|
| 72 |
path = Path(
|
|
|
|
| 88 |
|
| 89 |
|
| 90 |
def hf_source(snap: HubStatsSnapshot) -> str:
|
| 91 |
+
"""Pinned DuckDB source `hf://datasets/<repo>@<sha>/<file>`. Authenticated
|
| 92 |
+
reads need `CREATE SECRET (TYPE HUGGINGFACE, TOKEN ...)`."""
|
|
|
|
|
|
|
| 93 |
return f"hf://datasets/{snap.repo_id}@{snap.revision}/{snap.filename}"
|
| 94 |
|
| 95 |
|