File size: 4,779 Bytes
fb6b9a8
2eaa456
 
fb6b9a8
2eaa456
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7505a51
fb6b9a8
 
cab6640
fb6b9a8
 
 
 
2eaa456
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226b7bf
 
 
fb6b9a8
 
 
 
226b7bf
fb6b9a8
2eaa456
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7505a51
 
 
 
 
 
 
2eaa456
 
 
 
 
 
 
 
 
032bef2
2eaa456
 
fb6b9a8
2eaa456
 
 
 
 
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
"""Daily job: snapshot -> probe new/changed repos -> classify -> dashboard data -> push.
Then the org-wide pass for the landing page: every public MiniMaxAI release, the community
models declared on it, and one data file per category page.

    python scripts/daily.py [--family h3 ...] [--push] [--skip-snapshot] [--skip-org]

Runs the same way locally and on HF Jobs. With --push it first mirrors the dataset repo,
stores each family's raw snapshot before anything else (the one step that cannot be
redone later), then pushes labels, the probe cache and the dashboard data.
HF_TOKEN must be able to write the dataset repo and the Space repo.
"""
import argparse
import json
import sys
import time
from pathlib import Path

import pandas as pd

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from hfeco import authors, classify, discover, families, hubstats, metrics, org, pipeline, store  # noqa: E402
from hfeco.hub import api  # noqa: E402

SPACE_REPO = "MiniMaxAI/ecosystem"
ap = argparse.ArgumentParser()
ap.add_argument("--family", nargs="*", default=list(families.FAMILIES))
ap.add_argument("--push", action="store_true")
ap.add_argument("--skip-snapshot", action="store_true")
ap.add_argument("--skip-org", action="store_true")
args = ap.parse_args()
t0 = time.time()


def log(m):
    print(f"[{time.time() - t0:6.0f}s] {m}", flush=True)


if args.push:
    log("pull dataset")
    store.pull()

for key in args.family:
    fam = families.get(key)
    log(f"== {fam.title}")
    if not args.skip_snapshot:
        raw_path = store.write_raw(discover.discover(fam, log=log), fam.key)
        if args.push:
            store.push([raw_path], f"{fam.key}: snapshot {raw_path.stem}")
    raw = store.read_raw(fam.key)
    today = raw[raw.day == raw.day.max()]
    cache, cache_path = pipeline.enrich_all(today, fam, log=log)
    labels = classify.classify_all(today, cache, fam)

    lab_path = store.LOCAL / "labels" / fam.key / "latest.parquet"
    lab_path.parent.mkdir(parents=True, exist_ok=True)
    ldf = pd.DataFrame(labels)
    for c in ("evidence", "flags"):
        ldf[c] = ldf[c].apply(lambda v: json.dumps(v, ensure_ascii=False))
    ldf.to_parquet(lab_path, index=False)

    fam_ids = [x["repo_id"] for x in labels if x.get("family") and x["kind"] == "model"]
    who, who_path = authors.update({i.split("/")[0] for i in fam_ids} | {b.split("/")[0] for b in fam.bases}, log=log)
    data = metrics.build(raw, labels, metrics.hf_tree_counts(today, fam), fam, who)
    data_path = store.LOCAL / "dashboard" / f"{fam.key}.json"
    metrics.dump(data, data_path)
    log(f"{fam.key}: {len(labels)} labels, {len(data['repos'])} repos on the dashboard")
    if args.push:
        store.push([lab_path, cache_path, who_path], f"{fam.key}: labels {data['today']}")

if args.skip_org:
    sys.exit(0)

# ---- org-wide pass: the landing page and one data file per category -------------------------
log("== MiniMaxAI")
pub = org.public_models()
rels = org.group(pub, log=log)
deep = {}
for key in {r["deep"][0] for r in rels.values() if r["deep"]}:
    deep[key] = json.loads((store.LOCAL / "dashboard" / f"{key}.json").read_text())
in_families = {x["id"] for d in deep.values() for x in d["repos"]}
roots = {m.id: k for k, r in rels.items() if not r["deep"] for m in r["models"]}
found = org.crawl(roots, skip=in_families, log=log)
snap_path = org.snapshot(rels, found)
if args.push:
    store.push([snap_path], f"org: snapshot {snap_path.stem}")
if not hubstats.PATH.exists():  # once: past downloads for the history charts; never blocks the day
    try:
        hubstats.backfill(org.history_ids(pub), log=log)
        if args.push:
            store.push([hubstats.PATH], "hub-stats downloads history")
    except Exception as e:
        log(f"hub-stats history skipped: {type(e).__name__}: {e}")
who, who_path = authors.update({i.split("/")[0] for i in found} | {org.ORG}, log=log)
site, pages = org.build(rels, found, deep, who)
public_ids = {m.id for m in pub}
out = [("site", site)] + list(pages.items())
paths = []
for name, obj in out:
    org.check_public(obj, public_ids)
    paths.append(store.LOCAL / "dashboard" / f"{name}.json")
    metrics.dump(obj, paths[-1])
org.check_owned_public([obj for _, obj in out])
log(f"org: {len(rels)} releases, {sum(r['n'] for r in site['releases'])} community models, "
    f"pages: {', '.join(pages)}")
if args.push:
    from huggingface_hub import CommitOperationAdd
    store.push([who_path], f"org: authors {site['today']}")
    api.create_commit(SPACE_REPO, [CommitOperationAdd(path_in_repo=f"data/{p.name}", path_or_fileobj=str(p))
                                   for p in paths],
                      commit_message=f"data {site['today']}", repo_type="space")
    log("pushed")