File size: 9,647 Bytes
fb6b9a8 da5997b fb6b9a8 b357068 fb6b9a8 b357068 3e83256 da5997b fb6b9a8 3e83256 da5997b fb6b9a8 b357068 da5997b b357068 fb6b9a8 da5997b fb6b9a8 da5997b fb6b9a8 b357068 ff88a82 946b77d ff88a82 fb6b9a8 ff88a82 946b77d b357068 fb6b9a8 946b77d fb6b9a8 946b77d fb6b9a8 946b77d 226b7bf fb6b9a8 226b7bf fb6b9a8 226b7bf fb6b9a8 946b77d fb6b9a8 226b7bf fb6b9a8 226b7bf 946b77d 226b7bf 946b77d 226b7bf fb6b9a8 946b77d fb6b9a8 | 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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 | """Turn raw snapshots + labels into the dashboard's data.json."""
import datetime as dt
import json
import pandas as pd
REL_ORDER = ["adapter", "finetune", "quantized", "repackage", "merge", "mirror", "component"]
HF_ORDER = ["adapter", "finetune", "merge", "quantized"]
REFRESH_UTC_HOUR = 11 # HF's daily counter refresh lands somewhere around 08:40-13:30 UTC
def daily_downloads(raw):
"""Per repo and day: downloads per day since the previous snapshot.
The first time a repo is seen it has no previous value, so it contributes nothing
that day (its all-time total is not counted as one day's downloads).
HF refreshes its download counters in a daily batch (a few repos trickle in between), so a
snapshot taken before the next refresh nearly repeats the previous one. When the counters
moved by less than a fifth of a usual day (the repos' 30-day downloads / 30), the snapshot is
dropped: that day has no value rather than zero, and what did trickle in counts with the next
one. A difference is divided by the number of refreshes between the two snapshots (taken to
land at REFRESH_UTC_HOUR each day), at least one.
"""
cols = ["repo_id", "kind", "day", "fetched_at", "downloads_all_time"]
df = raw[raw.kind != "space"][cols + (["downloads_30d"] if "downloads_30d" in raw else [])].copy()
df["t"] = pd.to_datetime(df.fetched_at, utc=True, format="ISO8601")
df = df.sort_values(["kind", "repo_id", "t"])
delta = df.downloads_all_time - df.groupby(["kind", "repo_id"]).downloads_all_time.shift()
if "downloads_30d" in df:
usual = df.downloads_30d.fillna(0) / 30
else:
usual = df.downloads_all_time.notna().astype(float) # no 30-day figure: one per repo
snap = pd.DataFrame({"kind": df.kind, "day": df.day, "seen": delta.notna(),
"moved": delta.clip(lower=0).fillna(0), "usual": usual.where(delta.notna(), 0)})
snap = snap.groupby(["kind", "day"])[["seen", "moved", "usual"]].sum()
stale = set(snap[(snap.seen > 0) & (snap.moved < 0.2 * snap.usual)].index)
if stale:
df = df[[(k, d) not in stale for k, d in zip(df.kind, df.day)]]
g = df.groupby(["kind", "repo_id"])
df["prev"] = g.downloads_all_time.shift()
shift = pd.Timedelta(hours=REFRESH_UTC_HOUR)
refreshes = ((df.t - shift).dt.floor("D") - (g.t.shift() - shift).dt.floor("D")).dt.days.clip(lower=1)
delta = df.downloads_all_time - df.prev
df["negative"] = delta < 0
df["daily"] = (delta.clip(lower=0) / refreshes).where(df.prev.notna())
return df[["kind", "repo_id", "day", "daily", "negative"]]
def latest_daily(dd):
"""repo_id -> its most recent daily downloads (the last snapshot may have been dropped)."""
d = dd.dropna(subset=["daily"]).sort_values("day")
return d.groupby("repo_id").daily.last().to_dict()
def build(raw, labels, hf_tree_counts, fam, authors=None, history=None):
"""The dashboard's data file. The Space may become public, so this is a whitelist of
what the page renders: no evidence, confidence, declaration status or flags, and no
names of NSFW repos (they still count in the totals). Internal detail stays in the
labels parquet in the private dataset.
`history`: earlier snapshots of the same repos taken by another pass (the org-wide one
followed the language and music releases before they had a family), so daily downloads
carry on across the switch. On a day both have, the family's own snapshot wins."""
days = sorted(raw.day.unique())
today = days[-1]
lab = pd.DataFrame(labels)
cur = raw[raw.day == today].merge(lab, on=["kind", "repo_id"], how="left")
counters = raw
if history is not None and len(history):
cols = ["repo_id", "day", "fetched_at", "downloads_all_time", "downloads_30d"]
h = history[history.repo_id.isin(set(raw.repo_id)) & ~history.day.isin(set(days))][cols]
counters = pd.concat([h.assign(kind="model"), raw[["kind"] + cols]], ignore_index=True)
dd = daily_downloads(counters)
dd = dd[dd.kind == "model"]
last = latest_daily(dd)
famdf = cur[cur.family.fillna(False).astype(bool)]
out = {"today": today, "snapshot_days": days,
"family": {"key": fam.key, "title": fam.title,
"members": [{"lineage": m.lineage, "base": m.base} for m in fam.tracked]},
"rel_order": REL_ORDER, "lineages": {}, "repos": []}
for lin in [m.lineage for m in fam.tracked]:
base = fam.base_of(lin)
models = famdf[(famdf.lineage == lin) & (famdf.kind == "model") & famdf.relation.isin(REL_ORDER)
& (famdf.repo_id != base)]
off = cur[(cur.kind == "model") & (cur.repo_id == base)]
d = dd.merge(models[["repo_id", "relation"]], on="repo_id").dropna(subset=["daily"])
daily = d.groupby(["day", "relation"]).daily.sum().round().astype(int)
growth = models.assign(date=models.created_at.str[:10]).groupby(["date", "relation"]).size()
out["lineages"][lin] = {
"base": base,
"official": {"dl30": _i(off.downloads_30d), "dlall": _i(off.downloads_all_time),
"likes": _i(off.likes)},
"n_models": int(len(models)),
"n_authors": int(models.repo_id.str.split("/").str[0].nunique()),
"dl30": int(models.downloads_30d.fillna(0).sum()),
"dlall": int(models.downloads_all_time.fillna(0).sum()),
"by_relation": {rel: {"n": int((models.relation == rel).sum()),
"dl30": int(models[models.relation == rel].downloads_30d.fillna(0).sum()),
"dlall": int(models[models.relation == rel].downloads_all_time.fillna(0).sum())}
for rel in REL_ORDER},
"hf_tree": hf_tree_counts.get(base, {}),
"daily": [{"day": k[0], "rel": k[1], "n": int(v)} for k, v in daily.items()],
"growth": [{"date": k[0], "rel": k[1], "n": int(v)} for k, v in growth.items()],
}
# Most active authors, by models they made themselves (whole-repo copies don't count).
own = models[models.copy_of.isna() & ~models["flags"].apply(
lambda f: bool({"nsfw", "nsfw_author"} & set(f if isinstance(f, list) else [])))]
ta = (own.assign(a=own.repo_id.str.split("/").str[0])
.groupby("a").agg(n=("repo_id", "size"), dlall=("downloads_all_time", "sum"))
.sort_values(["n", "dlall"], ascending=False).head(12))
out["lineages"][lin]["top_authors"] = [{"a": k, "n": int(v.n), "dlall": int(v.dlall or 0)}
for k, v in ta.iterrows()]
up = tree_parents(models, base)
nsfw = set(models[models["flags"].apply(
lambda f: bool({"nsfw", "nsfw_author"} & set(f if isinstance(f, list) else [])))].repo_id)
for r in models[~models.repo_id.isin(nsfw)].itertuples():
p = up[r.repo_id]
while p in nsfw: # hidden repos keep their place in the totals, not in the tree
p = up[p]
v = last.get(r.repo_id)
out["repos"].append({"id": r.repo_id, "lin": lin, "rel": r.relation, "up": p,
"dl30": _i(r.downloads_30d), "dlall": _i(r.downloads_all_time),
"d1": None if v is None or pd.isna(v) else int(round(v)),
"likes": _i(r.likes), "created": (r.created_at or "")[:10]})
names = {r["id"].split("/")[0] for r in out["repos"]} | {m.base.split("/")[0] for m in fam.tracked}
out["authors"] = {n: (authors or {}).get(n, {"a": None, "n": n}) for n in sorted(names)}
return out
def tree_parents(models, base):
"""Parent of every derived model, for the tree.
1. a declared base_model that is itself a derived model of the same member
2. the official base, if the author declared it
3. the community repo this one is a byte-identical copy of
4. otherwise the official base (what the weights say it is built on)
"""
ids = set(models.repo_id)
up = {}
for r in models.itertuples():
decl = list(r.card_base_model or [])
fam_decl = [p for p in decl if p in ids and p != r.repo_id]
if fam_decl:
up[r.repo_id] = fam_decl[0]
elif base in decl:
up[r.repo_id] = base
elif isinstance(r.copy_of, str) and r.copy_of in ids and r.copy_of != r.repo_id:
up[r.repo_id] = r.copy_of
else:
up[r.repo_id] = base
for x in ids: # break cycles (A declares B, B declares A)
seen, p = {x}, up[x]
while p != base:
if p in seen:
up[x] = base
break
seen.add(p)
p = up[p]
return up
def hf_tree_counts(raw_today, fam):
"""What the Hub's Model tree shows: direct children per relation tag."""
out = {b: {k: 0 for k in HF_ORDER} for b in fam.bases}
for r in raw_today[raw_today.kind == "model"].itertuples():
for p in r.hf_parents:
rel, parent = p.split(":", 1)
if parent in out and rel in out[parent]:
out[parent][rel] += 1
return out
def _i(x):
try:
v = x.iloc[0] if hasattr(x, "iloc") else x
return None if pd.isna(v) else int(v)
except (IndexError, ValueError, TypeError):
return None
def dump(obj, path):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(obj, ensure_ascii=False, separators=(",", ":"), default=str))
|