saladday1 commited on
Commit
4abf37c
·
verified ·
1 Parent(s): 13b0535

code: sync from git

Browse files
Files changed (1) hide show
  1. code/hfeco/org.py +101 -43
code/hfeco/org.py CHANGED
@@ -195,18 +195,13 @@ def history_ids(pub):
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:
@@ -215,45 +210,85 @@ def download_history(groups, deep_fams):
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,7 +300,7 @@ def build(rels, found, deep_data, who):
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")
@@ -282,11 +317,14 @@ def build(rels, found, deep_data, who):
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,10 +342,28 @@ def build(rels, found, deep_data, who):
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):
@@ -320,6 +376,8 @@ def build(rels, found, deep_data, who):
320
 
321
  everyone = {x["id"].split("/")[0] for rs in repos.values() for x in rs}
322
  site = {"today": today, "org": author_entry(ORG), "builders": len(everyone), "categories": [], "releases": []}
 
 
323
  for key, r in sorted(rels.items(), key=lambda kv: kv[1]["date"]):
324
  L = lineages[key]
325
  g = Counter()
 
195
  return ids
196
 
197
 
198
+ def download_points(deep_fams):
199
+ """Every followed repo's all-time (dla) and 30-day (d30) downloads, about a week apart: the
200
+ cfahlgren1/hub-stats history (raw/hubstats.parquet, see hfeco/hubstats.py), then our own
201
+ snapshots a week apart. None until the history exists."""
 
 
 
 
 
202
  path = store.LOCAL / "raw" / "hubstats.parquet"
203
  if not path.exists():
204
+ return None
205
  hs = pd.read_parquet(path)
206
  own = [read_snapshots()]
207
  for fam in deep_fams:
 
210
  own = (pd.concat(own, ignore_index=True)[["day", "repo_id", "downloads_30d", "downloads_all_time"]]
211
  .rename(columns={"downloads_30d": "d30", "downloads_all_time": "dla"}))
212
  own = own[own.day > hs.day.max()].drop_duplicates(["day", "repo_id"])
213
+ keep, nxt = [], (pd.Timestamp(hs.day.max()) + pd.Timedelta(days=7)).strftime("%Y-%m-%d")
214
  for d in sorted(own.day.unique()):
215
  if d >= nxt:
216
  keep.append(d)
217
  nxt = (pd.Timestamp(d) + pd.Timedelta(days=7)).strftime("%Y-%m-%d")
218
  pts = pd.concat([hs, own[own.day.isin(keep)]], ignore_index=True)
219
+ return pts, sorted(pts.day.unique()), set(hs.day)
220
+
221
+
222
+ def cumulative(P, ids):
223
+ """day -> all-time downloads of `ids`. A hub-stats day without them is 0 (none existed yet);
224
+ one of our snapshot days without them is left out (that snapshot does not follow them).
225
+ Before 2025-02-27 hub-stats has only 30-day downloads, so earlier totals are walked back from
226
+ the first all-time one, each step taking off its share of those 30 days."""
227
+ pts, days, hs_days = P
228
+ g = pts[pts.repo_id.isin(ids)].groupby("day").agg(
229
+ dla=("dla", lambda x: x.sum(min_count=1)), d30=("d30", "sum"), n=("repo_id", "size"))
230
+ g = g.reindex(days)
231
+ v, after = {}, None
232
+ for d in reversed(days):
233
+ row = g.loc[d]
234
+ if pd.isna(row.n):
235
+ if d in hs_days:
236
+ v[d] = 0.0
237
+ continue
238
+ if pd.notna(row.dla):
239
+ v[d] = float(row.dla)
240
+ else:
241
+ step = (pd.Timestamp(after) - pd.Timestamp(d)).days if after else 0
242
+ v[d] = max(0.0, v[after] - (g.loc[after].d30 or 0) * step / 30) if after else 0.0
243
+ after = d
244
+ return v
245
 
246
+
247
+ def download_history(groups, P):
248
+ """{release: [[day, official, community], ...]}: all-time downloads, about weekly, ending
249
+ with today's totals. `groups`: release -> (date, official ids, community ids, (today,
250
+ official, community))."""
251
  out = {}
252
  for key, (start, off, comm, now) in groups.items():
253
+ a, b = cumulative(P, off), cumulative(P, comm)
254
+ rows = [[d, int(round(a[d])), int(round(b[d]))] for d in P[1] if start < d < now[0] and d in a and d in b]
255
  out[key] = [[start, 0, 0]] + rows + [[now[0], int(now[1]), int(now[2])]]
256
  return out
257
 
258
 
259
+ def download_rates(groups, P):
260
+ """{key: {day: downloads per day}} over each step between points (about a week), from the
261
+ group's start. `groups`: key -> (start, ids)."""
262
+ out = {}
263
+ for key, (start, ids) in groups.items():
264
+ v = cumulative(P, ids)
265
+ prev_d, prev_v, rates = start, 0.0, {}
266
+ for d in P[1]:
267
+ if d <= start or d not in v:
268
+ continue
269
+ span = (pd.Timestamp(d) - pd.Timestamp(prev_d)).days
270
+ rates[d] = max(0.0, v[d] - prev_v) / span
271
+ prev_d, prev_v = d, v[d]
272
+ out[key] = rates
273
+ return out
274
+
275
+
276
+ def aligned(rates, start):
277
+ """{"days": [...], "cats": {key: [per day, ...]}} on the days any key has, from `start`. A key
278
+ without a value that day takes the step that covers it (0 before it starts, its last after)."""
279
+ days = sorted({d for r in rates.values() for d in r if d > start})
280
+ out = {}
281
+ for k, r in rates.items():
282
+ ks = sorted(r)
283
+ vals, j = [], 0
284
+ for d in days:
285
+ while j < len(ks) and ks[j] < d:
286
+ j += 1
287
+ vals.append(int(round(r[ks[j]] if j < len(ks) else (r[ks[-1]] if ks else 0))))
288
+ out[k] = vals
289
+ return {"days": days, "cats": out}
290
+
291
+
292
  def build(rels, found, deep_data, who):
293
  """(site, {category: page data}). `deep_data` maps a family key to its dashboard dict."""
294
  snaps = read_snapshots()
 
300
  columns=["repo_id", "release", "up", "depth", "relation", "created_at", "downloads_30d",
301
  "downloads_all_time", "likes", "nsfw"])
302
 
303
+ lineages, repos, ids, rel_of = {}, defaultdict(list), {}, {}
304
  labels = {}
305
  for fam in {r["deep"][0] for r in rels.values() if r["deep"]}:
306
  lab = pd.read_parquet(store.LOCAL / "labels" / fam / "latest.parquet")
 
317
  lineages[key] = lin
318
  repos[key] = [{**x, "lin": key} for x in src["repos"] if x["lin"] == lk]
319
  lab = labels[fam]
320
+ mine = lab[(lab.lineage == lk) & ~lab.repo_id.str.startswith(ORG + "/")]
321
+ ids[key] = ({m.id for m in off}, set(mine.repo_id))
322
+ rel_of[key] = dict(zip(mine.repo_id, mine.relation))
323
  continue
324
  comm = comm_all[comm_all.release == key]
325
  lineages[key] = _declared_lineage(r, comm, d1, today)
326
  ids[key] = ({m.id for m in r["models"]}, set(comm.repo_id))
327
+ rel_of[key] = dict(zip(comm.repo_id, comm.relation))
328
  hidden = set(comm[comm.nsfw].repo_id)
329
  up_of = dict(zip(comm.repo_id, comm.up))
330
  for x in comm[~comm.nsfw].itertuples():
 
342
  def has_page(k):
343
  return lineages[k]["n_models"] >= PAGE_MIN
344
 
345
+ P = download_points(labels)
346
+ dl_daily = None
347
+ if P:
348
+ pages_k = [k for k in rels if has_page(k)]
349
+ hist = download_history({k: (rels[k]["date"], *ids[k], (today, lineages[k]["official"]["dlall"] or 0, lineages[k]["dlall"]))
350
+ for k in pages_k}, P)
351
+ for k, h in hist.items():
352
+ lineages[k]["history"] = h
353
+ # a release page's daily downloads by kind of community model, about weekly
354
+ for k in pages_k:
355
+ rates = download_rates({rel: (rels[k]["date"], {i for i, x in rel_of[k].items() if x == rel})
356
+ for rel in metrics.REL_ORDER if rel in set(rel_of[k].values())}, P)
357
+ lineages[k]["daily"] = [{"day": d, "rel": rel, "n": int(round(n))}
358
+ for rel, rr in rates.items() for d, n in sorted(rr.items())]
359
+ # the landing page: MiniMax models and their communities, per day, by modality
360
+ cat_ids = defaultdict(set)
361
+ cat_start = {}
362
+ for k, r in rels.items():
363
+ cat_ids[r["cat"]] |= ids[k][0] | ids[k][1]
364
+ cat_start[r["cat"]] = min(cat_start.get(r["cat"], r["date"]), r["date"])
365
+ first = min(cat_start.values())
366
+ dl_daily = aligned(download_rates({c: (cat_start[c], cat_ids[c]) for c in cat_ids}, P), first)
367
 
368
  by_cat = defaultdict(list)
369
  for key, r in sorted(rels.items(), key=lambda kv: kv[1]["date"], reverse=True):
 
376
 
377
  everyone = {x["id"].split("/")[0] for rs in repos.values() for x in rs}
378
  site = {"today": today, "org": author_entry(ORG), "builders": len(everyone), "categories": [], "releases": []}
379
+ if dl_daily:
380
+ site["dl_daily"] = dl_daily
381
  for key, r in sorted(rels.items(), key=lambda kv: kv[1]["date"]):
382
  L = lineages[key]
383
  g = Counter()