File size: 23,091 Bytes
2eaa456
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2471af3
2eaa456
 
 
 
 
 
 
 
 
 
 
 
ff88a82
 
 
 
 
 
 
 
 
 
2eaa456
 
340dbd7
 
 
 
 
 
 
 
 
2eaa456
 
 
 
 
 
 
 
 
 
 
 
 
 
340dbd7
2eaa456
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
032bef2
 
 
 
2eaa456
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7505a51
 
 
 
 
 
 
 
 
 
 
 
4abf37c
 
2471af3
4abf37c
2471af3
 
4abf37c
2471af3
7505a51
 
 
 
 
 
 
4abf37c
7505a51
 
 
 
 
4abf37c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7505a51
4abf37c
 
 
 
 
7505a51
 
4abf37c
 
7505a51
 
 
 
4abf37c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2eaa456
2471af3
 
2eaa456
 
 
 
b357068
2eaa456
 
 
 
4abf37c
7505a51
 
 
 
2eaa456
 
 
 
 
 
 
 
 
 
ff88a82
 
7505a51
4abf37c
 
 
2eaa456
 
 
7505a51
4abf37c
2eaa456
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4abf37c
a52b517
4abf37c
 
 
 
 
 
 
 
 
 
 
 
a52b517
 
 
4abf37c
 
 
a52b517
4abf37c
a52b517
2471af3
a52b517
 
 
2471af3
a52b517
 
 
 
2471af3
7505a51
2eaa456
 
 
 
 
 
 
 
 
 
 
a52b517
 
2eaa456
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2471af3
2eaa456
 
032bef2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2eaa456
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
"""MiniMaxAI's public releases and the community built on them (the landing page and the
per-category pages).

Releases with a full scan (the H3 family) take their numbers from that family's dashboard
data, so every page shows the same count. For every other release we follow HF's base_model
tags downward (children, grandchildren, ...), the same links the Hub's Model tree uses.

Each run also stores raw/org/YYYY-MM-DD.parquet (official and community repos with their
all-time downloads) so daily downloads can be differenced later, as for the families.
"""
import datetime as dt
import re
import time
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor

import pandas as pd

from . import classify, hubstats, metrics, store
from .hub import api, retry

ORG = "MiniMaxAI"
CATEGORY_NAME = {"video": "Video", "language": "Language", "image": "Image", "music": "Music",
                 "audio": "Speech & Audio"}

# Official repos grouped into releases: (key, name, category, repo-name pattern, deep lineage).
# First match wins. Public repos that match nothing become their own release, with a category
# from their pipeline tag, so a new launch shows up without a code change.
RELEASES = [
    ("h3-image", "MiniMax-H3-Image", "image", r"MiniMax-H3-Image", ("h3", "H3-Image")),
    ("h3", "MiniMax-H3", "video", r"MiniMax-H3", ("h3", "H3")),
    ("music3", "MiniMax-Music3", "music", r"MiniMax-Music3(-.+)?", ("music", "Music3")),
    ("m3.1-flash", "MiniMax-M3.1-Flash", "language", r"MiniMax-M3\.1-Flash(-.+)?", ("m", "M3.1-Flash")),
    ("m3", "MiniMax-M3", "language", r"MiniMax-M3(-.+)?", ("m", "M3")),
    ("m2.7", "MiniMax-M2.7", "language", r"MiniMax-M2\.7(-.+)?", ("m", "M2.7")),
    ("m2.5", "MiniMax-M2.5", "language", r"MiniMax-M2\.5(-.+)?", ("m", "M2.5")),
    ("m2.1", "MiniMax-M2.1", "language", r"MiniMax-M2\.1(-.+)?", ("m", "M2.1")),
    ("m2", "MiniMax-M2", "language", r"MiniMax-M2(-.+)?", ("m", "M2")),
    ("m1", "MiniMax-M1", "language", r"MiniMax-M1-.+", ("m", "M1")),
    ("text-01", "MiniMax-Text-01", "language", r"MiniMax-Text-01(-.+)?", ("m", "Text-01")),
    ("vl-01", "MiniMax-VL-01", "language", r"MiniMax-VL-01(-.+)?", ("m", "VL-01")),
    ("synlogic", "SynLogic", "language", r"SynLogic-.+", None),
]
# Public, but not shown anywhere (page, totals, tables): H3-Image-PE (the user asked for only H3
# and H3-Image from the H3 family) and VTP (taken off the Image modality at the user's request,
# 2026-11-26). Full-match patterns on the repo name, so a later VTP size stays hidden too; a
# hidden repo must not simply be dropped from RELEASES, or it comes back as a release of its own.
HIDDEN = [r"MiniMax-H3-Image-PE", r"VTP-.+"]


def hidden(repo_id):
    return any(re.fullmatch(p, repo_id.split("/", 1)[1]) for p in HIDDEN)
PIPELINE_CATEGORY = {"text-to-video": "video", "image-to-video": "video", "video-text-to-text": "language",
                     "text-to-image": "image", "image-to-image": "image", "text-to-audio": "music",
                     "text-to-speech": "audio", "automatic-speech-recognition": "audio"}
# A release gets its own page once it has this many community models.
PAGE_MIN = 10

OFFICIAL_EXPAND = ["createdAt", "private", "downloads", "downloadsAllTime", "likes", "pipeline_tag"]
CHILD_EXPAND = ["createdAt", "private", "downloads", "downloadsAllTime", "likes", "tags"]


def public_models():
    """The org's public models. `private` must be exactly False: with an admin token the
    listing also returns private repos, and a missing field must not count as public."""
    ms = retry(lambda: list(api.list_models(author=ORG, expand=OFFICIAL_EXPAND)))
    return [m for m in ms if m.private is False and not hidden(m.id)]


def group(models, log=print):
    """Release spec per key, in the order of RELEASES, then the unmatched ones."""
    out, extra = {}, {}
    for m in models:
        name = m.id.split("/", 1)[1]
        hit = next((r for r in RELEASES if re.fullmatch(r[3], name)), None)
        if hit:
            key, title, cat, _, deep = hit
        else:
            key, title, cat, deep = name.lower(), name, PIPELINE_CATEGORY.get(m.pipeline_tag or "", "language"), None
            extra[key] = m.id
        r = out.setdefault(key, {"key": key, "name": title, "cat": cat, "deep": deep, "models": []})
        r["models"].append(m)
    for key, mid in extra.items():
        log(f"org: {mid} matches no release rule; shown as its own release ({out[key]['cat']})")
    for r in out.values():
        r["models"].sort(key=lambda m: -(getattr(m, "downloads_all_time", None) or 0))
        # The centre of a release is the repo named like it (MiniMax-M3, not its MXFP8 copy),
        # else the most downloaded one.
        named = [m for m in r["models"] if m.id.split("/", 1)[1] == r["name"]]
        r["base"] = (named or r["models"])[0].id
        r["date"] = min(str(m.created_at)[:10] for m in r["models"])
    return out


def _children(parent):
    return parent, retry(lambda: list(api.list_models(filter=f"base_model:{parent}", expand=CHILD_EXPAND, limit=10000)))


def _relation(tags, parent):
    for t in tags or []:
        parts = t.split(":", 2)
        if len(parts) == 3 and parts[0] == "base_model" and parts[2] == parent:
            return parts[1] if parts[1] in ("adapter", "finetune", "quantized", "merge") else "finetune"
    return "finetune"


def crawl(roots, skip=frozenset(), log=print, workers=8):
    """Community models declared on `roots` ({official id: release key}) and on their
    descendants. Each repo gets one parent: the first one found, level by level, in sorted
    order, so a repo naming two MiniMax models lands in the same release every day."""
    owner = dict(roots)
    found, frontier, depth, t0 = {}, sorted(roots), 0, time.time()
    while frontier:
        with ThreadPoolExecutor(workers) as ex:
            res = list(ex.map(_children, frontier))
        nxt = []
        for parent, kids in res:
            for m in sorted(kids, key=lambda m: m.id):
                if (m.id in owner or m.id in skip or m.id.startswith(ORG + "/") or m.private is not False):
                    continue
                owner[m.id] = owner[parent]
                found[m.id] = {"repo_id": m.id, "release": owner[parent], "up": parent, "depth": depth,
                               "relation": _relation(m.tags, parent),
                               "created_at": str(m.created_at)[:19] if m.created_at else None,
                               "downloads_30d": m.downloads,
                               "downloads_all_time": getattr(m, "downloads_all_time", None),
                               "likes": m.likes, "nsfw": bool(classify.NSFW.search(m.id.lower())
                                                              or "not-for-all-audiences" in (m.tags or []))}
                nxt.append(m.id)
        frontier, depth = sorted(nxt), depth + 1
    log(f"org: {len(found)} declared community models in {depth} levels ({time.time() - t0:.0f}s)")
    return found


def snapshot(rels, found, day=None):
    """raw/org/<day>.parquet: one row per official and community repo."""
    now = dt.datetime.now(dt.timezone.utc)
    day = day or now.date().isoformat()
    rows = [{"repo_id": m.id, "kind": "model", "release": r["key"], "official": True, "up": None, "depth": None,
             "relation": None, "created_at": str(m.created_at)[:19], "downloads_30d": m.downloads,
             "downloads_all_time": getattr(m, "downloads_all_time", None), "likes": m.likes, "nsfw": False}
            for r in rels.values() for m in r["models"]]
    rows += [{**v, "kind": "model", "official": False} for v in found.values()]
    df = pd.DataFrame(rows).assign(fetched_at=now.isoformat())
    p = store.LOCAL / "raw" / "org" / f"{day}.parquet"
    p.parent.mkdir(parents=True, exist_ok=True)
    df.to_parquet(p, index=False)
    return p


def read_snapshots():
    files = sorted((store.LOCAL / "raw" / "org").glob("*.parquet"))
    return pd.concat([pd.read_parquet(f).assign(day=f.stem) for f in files], ignore_index=True)


def _declared_lineage(r, comm, d1, today):
    """The family dashboard's lineage record, for a release followed through base_model tags."""
    rel_order = metrics.REL_ORDER
    off = r["models"]
    lin = {
        "base": r["base"],
        "official": {"dl30": sum(m.downloads or 0 for m in off),
                     "dlall": sum(getattr(m, "downloads_all_time", None) or 0 for m in off),
                     "likes": sum(m.likes or 0 for m in off)},
        "n_models": int(len(comm)),
        "n_authors": int(comm.repo_id.str.split("/").str[0].nunique()) if len(comm) else 0,
        "dl30": int(comm.downloads_30d.fillna(0).sum()),
        "dlall": int(comm.downloads_all_time.fillna(0).sum()),
        "by_relation": {k: {"n": int((comm.relation == k).sum()),
                            "dl30": int(comm[comm.relation == k].downloads_30d.fillna(0).sum()),
                            "dlall": int(comm[comm.relation == k].downloads_all_time.fillna(0).sum())}
                        for k in rel_order},
        "hf_tree": {k: int(((comm.depth == 0) & (comm.relation == k)).sum())
                    for k in metrics.HF_ORDER},
    }
    if len(comm):
        g = comm.assign(date=comm.created_at.str[:10]).groupby(["date", "relation"]).size()
        lin["growth"] = [{"date": k[0], "rel": k[1], "n": int(v)} for k, v in g.items()]
        dd = d1[d1.repo_id.isin(set(comm.repo_id))].dropna(subset=["daily"])
        dd = dd.merge(comm[["repo_id", "relation"]], on="repo_id").groupby(["day", "relation"]).daily.sum()
        lin["daily"] = [{"day": k[0], "rel": k[1], "n": int(round(v))} for k, v in dd.items()]
        own = comm[~comm.nsfw]
        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))
        lin["top_authors"] = [{"a": k, "n": int(v.n), "dlall": int(v.dlall or 0)} for k, v in ta.iterrows()]
    else:
        lin.update(growth=[], daily=[], top_authors=[])
    return lin


def history_ids(pub):
    """Every repo the download history follows: the public official models, the latest org
    snapshot, and the family repos of the deep releases."""
    ids = {m.id for m in pub}
    snaps = read_snapshots()
    ids |= set(snaps[snaps.day == snaps.day.max()].repo_id)
    for p in (store.LOCAL / "labels").glob("*/latest.parquet"):
        lab = pd.read_parquet(p)
        ids |= set(lab[lab.family.astype(bool) & (lab.kind == "model")].repo_id)
    return ids


def download_points(deep_fams):
    """Every followed repo's all-time (dla) and 30-day (d30) downloads, about a week apart: the
    cfahlgren1/hub-stats history (raw/hubstats/, see hfeco/hubstats.py), then our own
    snapshots a week apart. None until the history exists."""
    hs = hubstats.read()
    if hs is None:
        return None
    hs = hs.rename(columns={"downloads_30d": "d30", "downloads_all_time": "dla"})
    own = [read_snapshots()]
    for fam in deep_fams:
        raw = store.read_raw(fam)
        own.append(raw[raw.kind == "model"])
    own = (pd.concat(own, ignore_index=True)[["day", "repo_id", "downloads_30d", "downloads_all_time"]]
           .rename(columns={"downloads_30d": "d30", "downloads_all_time": "dla"}))
    own = own[own.day > hs.day.max()].drop_duplicates(["day", "repo_id"])
    keep, nxt = [], (pd.Timestamp(hs.day.max()) + pd.Timedelta(days=7)).strftime("%Y-%m-%d")
    for d in sorted(own.day.unique()):
        if d >= nxt:
            keep.append(d)
            nxt = (pd.Timestamp(d) + pd.Timedelta(days=7)).strftime("%Y-%m-%d")
    pts = pd.concat([hs, own[own.day.isin(keep)]], ignore_index=True)
    return pts, sorted(pts.day.unique()), set(hs.day)


def cumulative(P, ids):
    """day -> all-time downloads of `ids`. A hub-stats day without them is 0 (none existed yet);
    one of our snapshot days without them is left out (that snapshot does not follow them).
    Before 2025-02-27 hub-stats has only 30-day downloads, so earlier totals are walked back from
    the first all-time one, each step taking off its share of those 30 days."""
    pts, days, hs_days = P
    g = pts[pts.repo_id.isin(ids)].groupby("day").agg(
        dla=("dla", lambda x: x.sum(min_count=1)), d30=("d30", "sum"), n=("repo_id", "size"))
    g = g.reindex(days)
    v, after = {}, None
    for d in reversed(days):
        row = g.loc[d]
        if pd.isna(row.n):
            if d in hs_days:
                v[d] = 0.0
            continue
        if pd.notna(row.dla):
            v[d] = float(row.dla)
        else:
            step = (pd.Timestamp(after) - pd.Timestamp(d)).days if after else 0
            v[d] = max(0.0, v[after] - (g.loc[after].d30 or 0) * step / 30) if after else 0.0
        after = d
    return v


def download_history(groups, P):
    """{release: [[day, official, community], ...]}: all-time downloads, about weekly, ending
    with today's totals. `groups`: release -> (date, official ids, community ids, (today,
    official, community))."""
    out = {}
    for key, (start, off, comm, now) in groups.items():
        a, b = cumulative(P, off), cumulative(P, comm)
        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]
        out[key] = [[start, 0, 0]] + rows + [[now[0], int(now[1]), int(now[2])]]
    return out


def download_rates(groups, P):
    """{key: {day: downloads per day}} over each step between points (about a week), from the
    group's start. `groups`: key -> (start, ids)."""
    out = {}
    for key, (start, ids) in groups.items():
        v = cumulative(P, ids)
        prev_d, prev_v, rates = start, 0.0, {}
        for d in P[1]:
            if d <= start or d not in v:
                continue
            span = (pd.Timestamp(d) - pd.Timestamp(prev_d)).days
            rates[d] = max(0.0, v[d] - prev_v) / span
            prev_d, prev_v = d, v[d]
        out[key] = rates
    return out


def build(rels, found, deep_data, who):
    """(site, {category: page data}, {release: shown community repos}). `deep_data` maps a
    family key to its dashboard dict."""
    snaps = read_snapshots()
    days = sorted(snaps.day.unique())
    today = days[-1]
    d1 = metrics.daily_downloads(snaps.assign(kind="model"))
    last = metrics.latest_daily(d1)
    comm_all = pd.DataFrame(list(found.values())) if found else pd.DataFrame(
        columns=["repo_id", "release", "up", "depth", "relation", "created_at", "downloads_30d",
                 "downloads_all_time", "likes", "nsfw"])

    lineages, repos, ids, rel_of = {}, defaultdict(list), {}, {}
    labels = {}
    for fam in {r["deep"][0] for r in rels.values() if r["deep"]}:
        lab = pd.read_parquet(store.LOCAL / "labels" / fam / "latest.parquet")
        labels[fam] = lab[lab.family.astype(bool) & (lab.kind == "model") & lab.relation.isin(metrics.REL_ORDER)]
    for key, r in rels.items():
        if r["deep"]:
            fam, lk = r["deep"]
            src = deep_data[fam]
            lin = dict(src["lineages"][lk])
            off = r["models"]
            lin["official"] = {"dl30": sum(m.downloads or 0 for m in off),
                               "dlall": sum(getattr(m, "downloads_all_time", None) or 0 for m in off),
                               "likes": sum(m.likes or 0 for m in off)}
            lineages[key] = lin
            repos[key] = [{**x, "lin": key, "up": r["base"] if x["up"].startswith(ORG + "/") else x["up"]}
                          for x in src["repos"] if x["lin"] == lk]           # one centre per release
            lab = labels[fam]
            mine = lab[(lab.lineage == lk) & ~lab.repo_id.str.startswith(ORG + "/")]
            ids[key] = ({m.id for m in off}, set(mine.repo_id))
            rel_of[key] = dict(zip(mine.repo_id, mine.relation))
            continue
        comm = comm_all[comm_all.release == key]
        lineages[key] = _declared_lineage(r, comm, d1, today)
        ids[key] = ({m.id for m in r["models"]}, set(comm.repo_id))
        rel_of[key] = dict(zip(comm.repo_id, comm.relation))
        hidden = set(comm[comm.nsfw].repo_id)
        up_of = dict(zip(comm.repo_id, comm.up))
        for x in comm[~comm.nsfw].itertuples():
            p = x.up
            while p in hidden:            # hidden repos stay in the totals, not in the bubbles
                p = up_of[p]
            if p.startswith(ORG + "/"):
                p = r["base"]             # one centre per release
            v = last.get(x.repo_id)
            repos[key].append({"id": x.repo_id, "lin": key, "rel": x.relation, "up": p,
                               "dl30": metrics._i(x.downloads_30d), "dlall": metrics._i(x.downloads_all_time),
                               "d1": None if v is None or pd.isna(v) else int(round(v)),
                               "likes": metrics._i(x.likes), "created": (x.created_at or "")[:10]})

    def has_page(k):
        return lineages[k]["n_models"] >= PAGE_MIN

    P = download_points(labels)
    dl_total = None
    if P:
        pages_k = [k for k in rels if has_page(k)]
        hist = download_history({k: (rels[k]["date"], *ids[k], (today, lineages[k]["official"]["dlall"] or 0, lineages[k]["dlall"]))
                                 for k in pages_k}, P)
        for k, h in hist.items():
            lineages[k]["history"] = h
        # a release page's daily downloads by kind of community model, about weekly
        for k in pages_k:
            rates = download_rates({rel: (rels[k]["date"], {i for i, x in rel_of[k].items() if x == rel})
                                    for rel in metrics.REL_ORDER if rel in set(rel_of[k].values())}, P)
            lineages[k]["daily"] = [{"day": d, "rel": rel, "n": int(round(n))}
                                    for rel, rr in rates.items() for d, n in sorted(rr.items())]
        # the landing page: all-time downloads of MiniMax models and everything built on them, by
        # modality, about weekly, ending with today's totals; never going down
        cat_ids, cat_start, now_total = defaultdict(set), {}, Counter()
        for k, r in rels.items():
            cat_ids[r["cat"]] |= ids[k][0] | ids[k][1]
            cat_start[r["cat"]] = min(cat_start.get(r["cat"], r["date"]), r["date"])
            now_total[r["cat"]] += (lineages[k]["official"]["dlall"] or 0) + lineages[k]["dlall"]
        first = min(cat_start.values())
        cum = {c: cumulative(P, cat_ids[c]) for c in cat_ids}
        steps = sorted({d for v in cum.values() for d in v if first < d < today})
        totals = {}
        for c, v in cum.items():
            run, vals = 0.0, []
            for d in steps:
                if d >= cat_start[c] and d in v:
                    run = max(run, v[d])
                vals.append(int(round(run)))
            totals[c] = vals + [int(max(run, now_total[c]))]
        dl_total = {"days": steps + [today], "cats": totals}

    by_cat = defaultdict(list)
    for key, r in sorted(rels.items(), key=lambda kv: kv[1]["date"], reverse=True):
        by_cat[r["cat"]].append(key)
    size = {c: sum(lineages[k]["n_models"] for k in ks) for c, ks in by_cat.items()}
    cats = sorted(by_cat, key=lambda c: (c != "video", -size[c]))

    def author_entry(n):
        return who.get(n, {"a": None, "n": n})

    everyone = {x["id"].split("/")[0] for rs in repos.values() for x in rs}
    site = {"today": today, "org": author_entry(ORG), "builders": len(everyone), "categories": [], "releases": []}
    if dl_total:
        site["dl_total"] = dl_total
    for key, r in sorted(rels.items(), key=lambda kv: kv[1]["date"]):
        L = lineages[key]
        g = Counter()
        for x in L["growth"]:
            g[x["date"]] += x["n"]
        site["releases"].append({
            "key": key, "name": r["name"], "cat": r["cat"], "date": r["date"], "base": r["base"],
            "page": has_page(key),
            "models": [{"id": m.id, "created": str(m.created_at)[:10], "dl30": m.downloads,
                        "dlall": getattr(m, "downloads_all_time", None), "likes": m.likes} for m in r["models"]],
            "official": L["official"], "n": L["n_models"], "dl30": L["dl30"], "dlall": L["dlall"],
            "authors": L["n_authors"], "growth": sorted([d, n] for d, n in g.items()),
        })
    pages = {}
    for c in cats:
        ks = by_cat[c]
        top = Counter()
        for k in ks:
            for t in lineages[k].get("top_authors", []):
                top[t["a"]] += t["n"]
        builders = set()
        for k in ks:
            builders |= {x["id"].split("/")[0] for x in repos[k]}
        site["categories"].append({
            "key": c, "name": CATEGORY_NAME.get(c, c.title()), "releases": ks,
            "builders": len(builders),
            "top_authors": [{"id": a, **author_entry(a)} for a, _ in top.most_common(8)],
        })
        members = [k for k in ks if has_page(k)]
        if not members:
            continue
        page_repos = [x for k in members for x in repos[k]]
        names = {x["id"].split("/")[0] for x in page_repos} | {ORG}
        pages[c] = {
            "today": today, "snapshot_days": days,
            "family": {"key": c, "title": CATEGORY_NAME.get(c, c.title()),
                       "members": [{"lineage": k, "base": rels[k]["base"]} for k in members]},
            "rel_order": metrics.REL_ORDER,
            "lineages": {k: lineages[k] for k in members},
            "repos": page_repos,
            "authors": {n: author_entry(n) for n in sorted(names)},
        }
    return site, pages, dict(repos)


def check_owned_public(objs):
    """Repos owned by the token's user or orgs are the only private ones a listing can return;
    every such id in data bound for the Space must be public."""
    me = api.whoami()
    owners = {me["name"]} | {o["name"] for o in me.get("orgs", [])}
    ids = set()

    def walk(o):
        if isinstance(o, dict):
            for v in o.values():
                walk(v)
        elif isinstance(o, list):
            for v in o:
                walk(v)
        elif isinstance(o, str) and o.count("/") == 1 and o.split("/")[0] in owners and " " not in o:
            ids.add(o)
    for o in objs:
        walk(o)
    bad = [i for i in sorted(ids) if retry(lambda: api.model_info(i, expand=["private"])).private is not False]
    if bad:
        raise ValueError(f"private repos in page data: {bad}")


def check_public(obj, public_ids):
    """Every MiniMaxAI/... id in data bound for the Space must be a public, shown repo."""
    bad = set()

    def walk(o):
        if isinstance(o, dict):
            for v in o.values():
                walk(v)
        elif isinstance(o, list):
            for v in o:
                walk(v)
        elif isinstance(o, str) and o.startswith(ORG + "/") and o not in public_ids:
            bad.add(o)
    walk(obj)
    if bad:
        raise ValueError(f"non-public {ORG} repos in page data: {sorted(bad)}")