"""Thin, retrying wrappers around the Hugging Face Hub API.""" import random import sys import time import httpx import requests from huggingface_hub import HfApi, get_token from huggingface_hub.utils import HfHubHTTPError api = HfApi() MODEL_EXPAND = ["downloads", "downloadsAllTime", "likes", "createdAt", "lastModified", "pipeline_tag", "library_name", "tags", "cardData", "gated", "sha"] DATASET_EXPAND = ["downloads", "downloadsAllTime", "likes", "createdAt", "lastModified", "tags", "cardData", "gated", "sha"] SPACE_EXPAND = ["likes", "createdAt", "lastModified", "sdk", "tags", "cardData", "models", "datasets", "sha", "runtime"] def retry(fn, *a, tries=6, **kw): for i in range(tries): try: return fn(*a, **kw) except (HfHubHTTPError, requests.RequestException, httpx.HTTPError) as e: code = getattr(getattr(e, "response", None), "status_code", None) if code in (401, 403, 404, 410): raise if i == tries - 1: raise time.sleep((2 ** i) * (6 if code == 429 else 1) + random.random()) def listing(kind, **kw): """Fully materialised listing (models/datasets/spaces) with retries.""" fn = {"model": api.list_models, "dataset": api.list_datasets, "space": api.list_spaces}[kind] expand = {"model": MODEL_EXPAND, "dataset": DATASET_EXPAND, "space": SPACE_EXPAND}[kind] return retry(lambda: list(fn(expand=expand, **kw))) def info(kind, repo_id, **kw): fn = {"model": api.model_info, "dataset": api.dataset_info, "space": api.space_info}[kind] if "expand" not in kw and "files_metadata" not in kw: kw["expand"] = {"model": MODEL_EXPAND, "dataset": DATASET_EXPAND, "space": SPACE_EXPAND}[kind] return retry(fn, repo_id, **kw) def full_text(q, kind, page=100, cap=5000): """All hits of the Hub's README full-text search; returns repo ids.""" out, skip = [], 0 h = {"Authorization": f"Bearer {get_token()}"} if get_token() else {} while skip < cap: def get(): r = requests.get("https://huggingface.co/api/search/full-text", params={"q": q, "type": kind, "limit": page, "skip": skip}, headers=h, timeout=60) r.raise_for_status() # inside retry, so a 5xx/429 from the search backend is retried return r try: r = retry(get) except requests.HTTPError as e: # Deep pages of the search backend can time out for good; keep what the earlier # pages found rather than failing the day's run. if e.response is None or e.response.status_code < 500: raise print(f"full-text {kind} {q!r}: stopped at skip={skip} ({e.response.status_code})", file=sys.stderr) break hits = r.json().get("hits", []) if not hits: break out += [x["name"] for x in hits if x.get("type") == kind and not x.get("isPrivate")] skip += page return sorted(set(out))