File size: 3,440 Bytes
e6969d0
 
 
 
 
2471af3
 
 
 
 
e6969d0
 
 
 
 
 
 
 
 
 
2471af3
 
 
 
 
 
 
 
 
 
 
 
 
e6969d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2471af3
e6969d0
 
2471af3
e6969d0
 
 
 
 
2471af3
e6969d0
2471af3
e6969d0
 
 
 
 
 
 
2471af3
e6969d0
2471af3
 
 
e6969d0
 
 
 
2471af3
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"""Past downloads of our repos, from the git history of cfahlgren1/hub-stats.

hub-stats commits a snapshot of every Hub model (models.parquet) about once a day, so its
history holds each repo's all-time downloads (`downloadsAllTime`, present from 2025-02-27) and
trailing 30-day downloads (`downloads`) day by day. `backfill` reads one revision every `every`
days and keeps only the given repos, one file per revision, laid out like our own snapshots:

    raw/hubstats/YYYY-MM-DD.parquet   repo_id, downloads_30d, downloads_all_time

It runs once (when the folder is empty); our own daily snapshots carry the series on.
"""
import time

import pandas as pd

from . import store
from .hub import api

SRC = "cfahlgren1/hub-stats"
URL = "https://huggingface.co/datasets/" + SRC + "/resolve/{sha}/models.parquet"
DIR = store.LOCAL / "raw" / "hubstats"


def files():
    return sorted(DIR.glob("*.parquet"))


def read():
    """day, repo_id, downloads_30d, downloads_all_time over every revision kept."""
    fs = files()
    if not fs:
        return None
    return pd.concat([pd.read_parquet(f).assign(day=f.stem) for f in fs], ignore_index=True)


def revisions(every=7, since="2025-01-01"):
    """(day, sha) of models.parquet commits: the day's last commit, one day per `every` days,
    and always the newest."""
    by_day = {}
    for c in sorted(api.list_repo_commits(SRC, repo_type="dataset"), key=lambda c: c.created_at):
        if "models.parquet" in c.title:
            by_day[str(c.created_at)[:10]] = c.commit_id
    days = sorted(d for d in by_day if d >= since)
    out, nxt = [], ""
    for d in days:
        if d >= nxt:
            out.append((d, by_day[d]))
            nxt = (pd.Timestamp(d) + pd.Timedelta(days=every)).strftime("%Y-%m-%d")
    if days and out[-1][0] != days[-1]:
        out.append((days[-1], by_day[days[-1]]))
    return out


def backfill(ids, every=7, since="2025-01-01", log=print):
    """Writes the missing revisions; returns the paths written."""
    import duckdb

    DIR.mkdir(parents=True, exist_ok=True)
    con = duckdb.connect()
    con.sql("SET http_timeout=120; SET http_retries=8; SET http_retry_wait_ms=2000")
    con.register("ours", pd.DataFrame({"id": sorted(ids)}))
    revs = revisions(every, since)
    log(f"hub-stats: {len(ids)} repos, {len(revs)} revisions")
    t0, written = time.time(), []
    for day, sha in revs:
        out = DIR / f"{day}.parquet"
        if out.exists():
            continue
        url = URL.format(sha=sha)
        for attempt in range(4):
            try:
                cols = {r[0] for r in con.sql(f"SELECT name FROM parquet_schema('{url}')").fetchall()}
                dla = "downloadsAllTime" if "downloadsAllTime" in cols else "NULL::BIGINT"
                df = con.sql(f"""SELECT id AS repo_id, downloads AS downloads_30d, {dla} AS downloads_all_time
                                 FROM read_parquet('{url}') WHERE id IN (SELECT id FROM ours)""").df()
                if len(df):
                    df.to_parquet(out, index=False)
                    written.append(out)
                break
            except Exception as e:  # network: retry the revision, then leave it out
                log(f"hub-stats {day} attempt {attempt + 1}: {type(e).__name__}: {str(e)[:120]}")
                time.sleep(10 * (attempt + 1))
    log(f"hub-stats: {len(written)} revisions written in {time.time() - t0:.0f}s")
    return written