saladday1 commited on
Commit
7505a51
·
verified ·
1 Parent(s): 1984e89

code: sync from git

Browse files
code/hfeco/org.py CHANGED
@@ -183,6 +183,77 @@ def _declared_lineage(r, comm, d1, today):
183
  return lin
184
 
185
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  def build(rels, found, deep_data, who):
187
  """(site, {category: page data}). `deep_data` maps a family key to its dashboard dict."""
188
  snaps = read_snapshots()
@@ -194,7 +265,11 @@ def build(rels, found, deep_data, who):
194
  columns=["repo_id", "release", "up", "depth", "relation", "created_at", "downloads_30d",
195
  "downloads_all_time", "likes", "nsfw"])
196
 
197
- lineages, repos = {}, defaultdict(list)
 
 
 
 
198
  for key, r in rels.items():
199
  if r["deep"]:
200
  fam, lk = r["deep"]
@@ -206,9 +281,12 @@ def build(rels, found, deep_data, who):
206
  "likes": sum(m.likes or 0 for m in off)}
207
  lineages[key] = lin
208
  repos[key] = [{**x, "lin": key} for x in src["repos"] if x["lin"] == lk]
 
 
209
  continue
210
  comm = comm_all[comm_all.release == key]
211
  lineages[key] = _declared_lineage(r, comm, d1, today)
 
212
  hidden = set(comm[comm.nsfw].repo_id)
213
  up_of = dict(zip(comm.repo_id, comm.up))
214
  for x in comm[~comm.nsfw].itertuples():
@@ -226,6 +304,11 @@ def build(rels, found, deep_data, who):
226
  def has_page(k):
227
  return lineages[k]["n_models"] >= PAGE_MIN
228
 
 
 
 
 
 
229
  by_cat = defaultdict(list)
230
  for key, r in sorted(rels.items(), key=lambda kv: kv[1]["date"], reverse=True):
231
  by_cat[r["cat"]].append(key)
 
183
  return lin
184
 
185
 
186
+ def history_ids(pub):
187
+ """Every repo the download history follows: the public official models, the latest org
188
+ snapshot, and the family repos of the deep releases."""
189
+ ids = {m.id for m in pub}
190
+ snaps = read_snapshots()
191
+ ids |= set(snaps[snaps.day == snaps.day.max()].repo_id)
192
+ for p in (store.LOCAL / "labels").glob("*/latest.parquet"):
193
+ lab = pd.read_parquet(p)
194
+ ids |= set(lab[lab.family.astype(bool) & (lab.kind == "model")].repo_id)
195
+ return ids
196
+
197
+
198
+ def download_history(groups, deep_fams):
199
+ """{release: [[day, official, community], ...]}: all-time downloads, about weekly.
200
+
201
+ `groups` maps a release to (release date, official ids, community ids, (official, community)
202
+ today). The past comes from cfahlgren1/hub-stats revisions (raw/hubstats.parquet, written by
203
+ scripts/backfill_hubstats.py), then from our own snapshots, then today's totals. Before
204
+ 2025-02-27 hub-stats has only trailing 30-day downloads, so earlier totals are walked back
205
+ from the first all-time one, each step taking off its share of those 30 days.
206
+ """
207
+ path = store.LOCAL / "raw" / "hubstats.parquet"
208
+ if not path.exists():
209
+ return {}
210
+ hs = pd.read_parquet(path)
211
+ own = [read_snapshots()]
212
+ for fam in deep_fams:
213
+ raw = store.read_raw(fam)
214
+ own.append(raw[raw.kind == "model"])
215
+ own = (pd.concat(own, ignore_index=True)[["day", "repo_id", "downloads_30d", "downloads_all_time"]]
216
+ .rename(columns={"downloads_30d": "d30", "downloads_all_time": "dla"}))
217
+ own = own[own.day > hs.day.max()].drop_duplicates(["day", "repo_id"])
218
+ keep, nxt = [], ""
219
+ for d in sorted(own.day.unique()):
220
+ if d >= nxt:
221
+ keep.append(d)
222
+ nxt = (pd.Timestamp(d) + pd.Timedelta(days=7)).strftime("%Y-%m-%d")
223
+ pts = pd.concat([hs, own[own.day.isin(keep)]], ignore_index=True)
224
+ days = sorted(pts.day.unique())
225
+
226
+ hs_days = set(hs.day)
227
+
228
+ def series(ids):
229
+ """day -> total; a hub-stats day without these repos is 0 (none existed yet), one of our
230
+ snapshot days without them is unknown (that snapshot does not follow them)."""
231
+ g = pts[pts.repo_id.isin(ids)].groupby("day").agg(
232
+ dla=("dla", lambda x: x.sum(min_count=1)), d30=("d30", "sum"), n=("repo_id", "size"))
233
+ g = g.reindex(days)
234
+ v, after = {}, None
235
+ for d in reversed(days):
236
+ row = g.loc[d]
237
+ if pd.isna(row.n):
238
+ if d in hs_days:
239
+ v[d] = 0.0
240
+ continue
241
+ if pd.notna(row.dla):
242
+ v[d] = float(row.dla)
243
+ else:
244
+ step = (pd.Timestamp(after) - pd.Timestamp(d)).days if after else 0
245
+ v[d] = max(0.0, v[after] - (g.loc[after].d30 or 0) * step / 30) if after else 0.0
246
+ after = d
247
+ return v
248
+
249
+ out = {}
250
+ for key, (start, off, comm, now) in groups.items():
251
+ a, b = series(off), series(comm)
252
+ rows = [[d, int(round(a[d])), int(round(b[d]))] for d in days if start < d < now[0] and d in a and d in b]
253
+ out[key] = [[start, 0, 0]] + rows + [[now[0], int(now[1]), int(now[2])]]
254
+ return out
255
+
256
+
257
  def build(rels, found, deep_data, who):
258
  """(site, {category: page data}). `deep_data` maps a family key to its dashboard dict."""
259
  snaps = read_snapshots()
 
265
  columns=["repo_id", "release", "up", "depth", "relation", "created_at", "downloads_30d",
266
  "downloads_all_time", "likes", "nsfw"])
267
 
268
+ lineages, repos, ids = {}, defaultdict(list), {}
269
+ labels = {}
270
+ for fam in {r["deep"][0] for r in rels.values() if r["deep"]}:
271
+ lab = pd.read_parquet(store.LOCAL / "labels" / fam / "latest.parquet")
272
+ labels[fam] = lab[lab.family.astype(bool) & (lab.kind == "model") & lab.relation.isin(metrics.REL_ORDER)]
273
  for key, r in rels.items():
274
  if r["deep"]:
275
  fam, lk = r["deep"]
 
281
  "likes": sum(m.likes or 0 for m in off)}
282
  lineages[key] = lin
283
  repos[key] = [{**x, "lin": key} for x in src["repos"] if x["lin"] == lk]
284
+ lab = labels[fam]
285
+ ids[key] = ({m.id for m in off}, set(lab[(lab.lineage == lk) & ~lab.repo_id.str.startswith(ORG + "/")].repo_id))
286
  continue
287
  comm = comm_all[comm_all.release == key]
288
  lineages[key] = _declared_lineage(r, comm, d1, today)
289
+ ids[key] = ({m.id for m in r["models"]}, set(comm.repo_id))
290
  hidden = set(comm[comm.nsfw].repo_id)
291
  up_of = dict(zip(comm.repo_id, comm.up))
292
  for x in comm[~comm.nsfw].itertuples():
 
304
  def has_page(k):
305
  return lineages[k]["n_models"] >= PAGE_MIN
306
 
307
+ hist = download_history({k: (rels[k]["date"], *ids[k], (today, lineages[k]["official"]["dlall"] or 0, lineages[k]["dlall"]))
308
+ for k in rels if has_page(k)}, labels)
309
+ for k, h in hist.items():
310
+ lineages[k]["history"] = h
311
+
312
  by_cat = defaultdict(list)
313
  for key, r in sorted(rels.items(), key=lambda kv: kv[1]["date"], reverse=True):
314
  by_cat[r["cat"]].append(key)
code/scripts/backfill_hubstats.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Write raw/hubstats.parquet (past downloads from cfahlgren1/hub-stats) by hand.
2
+
3
+ python scripts/backfill_hubstats.py [--every 7] [--since 2025-01-01] [--push]
4
+
5
+ The daily job does this by itself when the file is missing from the dataset (see
6
+ hfeco/hubstats.py); this is for rebuilding it locally, e.g. with a different step.
7
+ """
8
+ import argparse
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ ROOT = Path(__file__).resolve().parent.parent
13
+ sys.path.insert(0, str(ROOT))
14
+ from hfeco import hubstats, org, store # noqa: E402
15
+
16
+
17
+ def main():
18
+ ap = argparse.ArgumentParser()
19
+ ap.add_argument("--every", type=int, default=7)
20
+ ap.add_argument("--since", default="2025-01-01")
21
+ ap.add_argument("--push", action="store_true", help="upload raw/hubstats.parquet to the dataset")
22
+ a = ap.parse_args()
23
+ path = hubstats.backfill(org.history_ids(org.public_models()), a.every, a.since)
24
+ if a.push:
25
+ store.push([path], "hub-stats downloads history")
26
+ print("pushed")
27
+
28
+
29
+ if __name__ == "__main__":
30
+ main()
code/scripts/daily.py CHANGED
@@ -19,7 +19,7 @@ import pandas as pd
19
 
20
  ROOT = Path(__file__).resolve().parent.parent
21
  sys.path.insert(0, str(ROOT))
22
- from hfeco import authors, classify, discover, families, metrics, org, pipeline, store # noqa: E402
23
  from hfeco.hub import api # noqa: E402
24
 
25
  SPACE_REPO = "MiniMaxAI/ecosystem"
@@ -84,6 +84,13 @@ found = org.crawl(roots, skip=in_families, log=log)
84
  snap_path = org.snapshot(rels, found)
85
  if args.push:
86
  store.push([snap_path], f"org: snapshot {snap_path.stem}")
 
 
 
 
 
 
 
87
  who, who_path = authors.update({i.split("/")[0] for i in found} | {org.ORG}, log=log)
88
  site, pages = org.build(rels, found, deep, who)
89
  public_ids = {m.id for m in pub}
 
19
 
20
  ROOT = Path(__file__).resolve().parent.parent
21
  sys.path.insert(0, str(ROOT))
22
+ from hfeco import authors, classify, discover, families, hubstats, metrics, org, pipeline, store # noqa: E402
23
  from hfeco.hub import api # noqa: E402
24
 
25
  SPACE_REPO = "MiniMaxAI/ecosystem"
 
84
  snap_path = org.snapshot(rels, found)
85
  if args.push:
86
  store.push([snap_path], f"org: snapshot {snap_path.stem}")
87
+ if not hubstats.PATH.exists(): # once: past downloads for the history charts; never blocks the day
88
+ try:
89
+ hubstats.backfill(org.history_ids(pub), log=log)
90
+ if args.push:
91
+ store.push([hubstats.PATH], "hub-stats downloads history")
92
+ except Exception as e:
93
+ log(f"hub-stats history skipped: {type(e).__name__}: {e}")
94
  who, who_path = authors.update({i.split("/")[0] for i in found} | {org.ORG}, log=log)
95
  site, pages = org.build(rels, found, deep, who)
96
  public_ids = {m.id for m in pub}
code/scripts/job.sh CHANGED
@@ -2,7 +2,7 @@
2
  # Entry point for the scheduled HF Job (image python:3.12, secret HF_TOKEN).
3
  # Pulls the code from the dataset repo and runs the daily pipeline with --push.
4
  set -euo pipefail
5
- pip install -q "huggingface_hub>=1.17,<3" pandas pyarrow numpy requests httpx pyyaml
6
  hf download MiniMaxAI/oss-ecosystem-data --repo-type dataset --include "code/*" --local-dir /w
7
  cd /w/code
8
  HFECO_LOCAL=/w/data python scripts/daily.py "${@:---push}"
 
2
  # Entry point for the scheduled HF Job (image python:3.12, secret HF_TOKEN).
3
  # Pulls the code from the dataset repo and runs the daily pipeline with --push.
4
  set -euo pipefail
5
+ pip install -q "huggingface_hub>=1.17,<3" pandas pyarrow numpy requests httpx pyyaml duckdb
6
  hf download MiniMaxAI/oss-ecosystem-data --repo-type dataset --include "code/*" --local-dir /w
7
  cd /w/code
8
  HFECO_LOCAL=/w/data python scripts/daily.py "${@:---push}"