File size: 15,889 Bytes
2eaa456
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
032bef2
 
 
 
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
"""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, 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(-.+)?", None),
    ("m3.1-flash", "MiniMax-M3.1-Flash", "language", r"MiniMax-M3\.1-Flash(-.+)?", None),
    ("m3", "MiniMax-M3", "language", r"MiniMax-M3(-.+)?", None),
    ("m2.7", "MiniMax-M2.7", "language", r"MiniMax-M2\.7(-.+)?", None),
    ("m2.5", "MiniMax-M2.5", "language", r"MiniMax-M2\.5(-.+)?", None),
    ("m2.1", "MiniMax-M2.1", "language", r"MiniMax-M2\.1(-.+)?", None),
    ("m2", "MiniMax-M2", "language", r"MiniMax-M2(-.+)?", None),
    ("m1", "MiniMax-M1", "language", r"MiniMax-M1-.+", None),
    ("text-01", "MiniMax-Text-01", "language", r"MiniMax-Text-01(-.+)?", None),
    ("vl-01", "MiniMax-VL-01", "language", r"MiniMax-VL-01(-.+)?", None),
    ("synlogic", "SynLogic", "language", r"SynLogic-.+", None),
    ("vtp", "VTP", "image", r"VTP-.+", None),
]
# Public, but not shown (the user asked for only H3 and H3-Image from the H3 family).
HIDDEN = {"MiniMaxAI/MiniMax-H3-Image-PE"}
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 m.id not in HIDDEN]


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 build(rels, found, deep_data, who):
    """(site, {category: page data}). `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 = d1[d1.day == today].set_index("repo_id").daily.to_dict()
    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 = {}, defaultdict(list)
    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} for x in src["repos"] if x["lin"] == lk]
            continue
        comm = comm_all[comm_all.release == key]
        lineages[key] = _declared_lineage(r, comm, d1, today)
        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

    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": []}
    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


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)}")