card-pipeline / fetch_model_cards.py
davanstrien's picture
davanstrien HF Staff
Add model card fetch and compile scripts (Phase B)
7696f9a
Raw History Blame Contribute Delete
8.26 kB
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "httpx[http2]",
# "huggingface-hub>=1.7",
# "pydantic",
# "python-dotenv",
# "stamina",
# "structlog",
# "aiolimiter",
# "tqdm",
# ]
# ///
"""
Fetch model cards from HF Hub and store as JSONL batches in a Storage Bucket.
Each batch is written to:
hf://buckets/{BUCKET_ID}/models/{timestamp}_{uuid}.jsonl
Run locally:
uv run fetch_model_cards.py
Run as HF Job:
hf jobs uv run -s HF_TOKEN --flavor cpu-basic --timeout 30m fetch_model_cards.py
Schedule:
hf jobs scheduled uv run "17 */6 * * *" -s HF_TOKEN --flavor cpu-basic --timeout 30m \\
https://huggingface.co/datasets/librarian-bots/card-pipeline/resolve/main/fetch_model_cards.py
"""
import asyncio
import os
import random
import re
from datetime import datetime, timezone
from typing import Optional
from uuid import uuid4
import httpx
import stamina
import structlog
from aiolimiter import AsyncLimiter
from dotenv import load_dotenv
from huggingface_hub import HfApi, batch_bucket_files, hf_hub_url, login
from pydantic import BaseModel
from tqdm.auto import tqdm
load_dotenv(override=True)
# --- Configuration ---
HF_TOKEN = os.getenv("HF_TOKEN")
assert HF_TOKEN is not None, "HF_TOKEN environment variable is required"
BUCKET_ID = os.getenv("BUCKET_ID", "librarian-bots/card-store")
MAX_MODELS = int(os.getenv("MAX_MODELS", "5000"))
MAX_CONCURRENT = int(os.getenv("MAX_CONCURRENT", "100"))
BATCH_SIZE = int(os.getenv("BATCH_SIZE", "5000"))
DRY_RUN = os.getenv("DRY_RUN", "false").lower() == "true"
USER_AGENT = os.getenv("USER_AGENT")
MODEL_PREFIX = "models/"
# --- Logging ---
structlog.configure(
processors=[
structlog.stdlib.add_log_level,
structlog.processors.TimeStamper(fmt="iso"),
structlog.dev.ConsoleRenderer(),
],
wrapper_class=structlog.make_filtering_bound_logger(20),
context_class=dict,
logger_factory=structlog.PrintLoggerFactory(),
cache_logger_on_first_use=True,
)
logger = structlog.get_logger()
# --- Auth and rate limiting ---
login(token=HF_TOKEN)
hf_api = HfApi(token=HF_TOKEN, user_agent=USER_AGENT)
RATE_LIMIT = int(os.getenv("RATE_LIMIT", "5000"))
RATE_PERIOD = int(os.getenv("RATE_PERIOD", "60"))
semaphore = asyncio.Semaphore(MAX_CONCURRENT)
rate_limit = AsyncLimiter(RATE_LIMIT, RATE_PERIOD)
REGEX_YAML_BLOCK = re.compile(r"^-{3,}\s*\n.*?\n-{3,}\s*\n", re.DOTALL)
SORT_OPTIONS = ["last_modified", "trending_score", "created_at"]
# --- Helpers ---
def is_valid_card(card: str, repo_id: str) -> bool:
if not card:
return False
if card.strip() == "Invalid username or password.":
return False
if "Entry not found" in card:
return False
if "<h1>429</h1>" in card:
return False
card_content = card.replace("\r\n", "\n").strip()
if len(card_content) < 30:
return False
if match := REGEX_YAML_BLOCK.match(card_content):
remaining = card_content[match.end() :].strip()
if not remaining or len(remaining) < 50:
return False
return True
class ModelCardRecord(BaseModel):
"""Full schema for a model card stored in the bucket."""
modelId: str
author: Optional[str] = None
last_modified: Optional[datetime] = None
downloads: int = 0
likes: int = 0
library_name: Optional[str] = None
tags: Optional[list[str]] = None
pipeline_tag: Optional[str] = None
createdAt: Optional[datetime] = None
card: str = ""
fetched_at: Optional[datetime] = None
def parse_model(model) -> Optional[ModelCardRecord]:
try:
return ModelCardRecord(
modelId=model.id,
author=model.author,
last_modified=model.last_modified,
downloads=model.downloads or 0,
likes=model.likes or 0,
library_name=model.library_name,
tags=model.tags or [],
pipeline_tag=model.pipeline_tag,
createdAt=model.created_at,
)
except Exception as e:
logger.error("Failed to parse model", model=model.id, error=str(e))
return None
# --- Fetch ---
@stamina.retry(on=Exception, attempts=5, wait_initial=5, wait_max=120, wait_exp_base=2)
async def fetch_card(client: httpx.AsyncClient, model_id: str) -> Optional[str]:
async with semaphore:
async with rate_limit:
url = hf_hub_url(model_id, "README.md")
response = await client.get(url, follow_redirects=True)
if response.is_success:
card = response.text
if is_valid_card(card, model_id):
return card
return None
if response.status_code == 429:
raise Exception(f"Rate limit exceeded for {model_id}")
return None
async def _fetch_one(
client: httpx.AsyncClient, record: ModelCardRecord
) -> Optional[ModelCardRecord]:
try:
card = await fetch_card(client, record.modelId)
if card:
record.card = card
record.fetched_at = datetime.now(timezone.utc)
return record
except Exception as e:
logger.error("Failed to fetch card", model=record.modelId, error=str(e))
return None
async def fetch_and_upload_batch(
client: httpx.AsyncClient, batch: list[ModelCardRecord]
) -> tuple[int, int]:
"""Fetch cards for a batch concurrently, upload as JSONL to bucket."""
tasks = [_fetch_one(client, record) for record in batch]
fetched = await asyncio.gather(*tasks)
results = [r for r in fetched if r is not None]
if not results:
return 0, len(batch)
lines = [record.model_dump_json() for record in results]
jsonl_data = ("\n".join(lines) + "\n").encode("utf-8")
timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
path = f"{MODEL_PREFIX}{timestamp}_{uuid4().hex[:8]}.jsonl"
if DRY_RUN:
logger.info(
"[DRY RUN] Would upload JSONL to bucket",
path=path,
records=len(results),
bytes=len(jsonl_data),
)
else:
batch_bucket_files(BUCKET_ID, add=[(jsonl_data, path)], token=HF_TOKEN)
logger.info("Uploaded JSONL to bucket", path=path, records=len(results))
return len(results), len(batch) - len(results)
async def main():
logger.info(
"Starting model card fetch",
max_models=MAX_MODELS,
bucket=BUCKET_ID,
dry_run=DRY_RUN,
)
sort_by = random.choice(SORT_OPTIONS)
logger.info("Fetching model list", sort=sort_by)
models = hf_api.list_models(sort=sort_by, full=True, limit=MAX_MODELS)
models = (m for m in models if not m.private)
models = (m for m in models if not m.gated)
models = (m for m in models if "not-for-all-audiences" not in (m.tags or []))
models = list(tqdm(models, desc="Listing models"))
logger.info("Found models", count=len(models))
metas = [parse_model(m) for m in models]
metas = [m for m in metas if m is not None]
logger.info("Parsed metadata", count=len(metas))
total_success = 0
total_failed = 0
headers = {"authorization": f"Bearer {HF_TOKEN}"}
if USER_AGENT:
headers["user-agent"] = USER_AGENT
async with httpx.AsyncClient(
headers=headers,
timeout=60,
http2=True,
limits=httpx.Limits(
max_connections=MAX_CONCURRENT,
max_keepalive_connections=MAX_CONCURRENT,
),
) as client:
for i in range(0, len(metas), BATCH_SIZE):
batch = metas[i : i + BATCH_SIZE]
success, failed = await fetch_and_upload_batch(client, batch)
total_success += success
total_failed += failed
logger.info(
"Batch complete",
batch=i // BATCH_SIZE + 1,
success=success,
failed=failed,
progress=f"{min(i + BATCH_SIZE, len(metas))}/{len(metas)}",
)
logger.info(
"Finished",
total_success=total_success,
total_failed=total_failed,
success_rate=f"{total_success / max(total_success + total_failed, 1):.1%}",
)
if __name__ == "__main__":
asyncio.run(main())