saladday1's picture
code: sync from git
af4699d verified
Raw History Blame Contribute Delete
6.04 kB
"""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, export, 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()
run = {}
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)
run[key] = (raw, today, cache_path, classify.classify_all(today, cache, fam))
# One repo counts in one family; families not run today take part with their latest labels.
others = {k: pd.read_parquet(p).to_dict("records") for k in families.FAMILIES if k not in run
for p in [store.LOCAL / "labels" / k / "latest.parquet"] if p.exists()}
moved = classify.resolve_overlaps({k: v[3] for k, v in run.items()}, others)
if moved:
log(f"claimed by more than one family, kept in the strongest: {moved}")
for key, (raw, today, cache_path, labels) in run.items():
fam = families.get(key)
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)
history = org.read_snapshots() if any((store.LOCAL / "raw" / "org").glob("*.parquet")) else None
data = metrics.build(raw, labels, metrics.hf_tree_counts(today, fam), fam, who, history=history)
data_path = store.LOCAL / "dashboard" / "family" / f"{fam.key}.json" # apart from the page files:
# a family key can also be a category key ("music"), and dashboard/<category>.json is a page
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"]}:
p = store.LOCAL / "dashboard" / "family" / f"{key}.json"
if not p.exists():
sys.exit(f"{p} is missing: the landing page needs every family's dashboard; run all families "
f"(no --family) or --skip-org")
deep[key] = json.loads(p.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.files(): # once: past downloads for the history charts; never blocks the day
try:
written = hubstats.backfill(org.history_ids(pub), log=log)
if args.push and written:
store.push(written, "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, shown = 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")
# the dataset's tables/, site/ and card, for people; never blocks the day
try:
export.publish(site, shown, public_ids, paths, push=args.push, log=log)
except Exception as e:
log(f"export skipped: {type(e).__name__}: {e}")