saladday1 commited on
Commit
226b7bf
·
verified ·
1 Parent(s): 946b77d

code: sync from git

Browse files
code/.gitignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ data/
2
+ __pycache__/
3
+ *.pyc
4
+ web/node_modules/
5
+ web/dist/
6
+ web/public/data/
code/README.md CHANGED
@@ -15,11 +15,14 @@ hfeco/ 通用流水线,不含任何具体模型的知识
15
  discover.py 找候选仓库(Model tree 逐层往下、名字、标签、模型卡全文、Space)
16
  enrich.py 只读文件头和少量字节收集证据(不下载权重)
17
  classify.py 三档证据判定:属于哪个成员、什么关系、base_model 声明对不对
18
- metrics.py 每日下载(相邻快照相减)和看板数据
 
19
  store.py 存储布局
20
  scripts/daily.py 每日任务入口(本地和 HF Jobs 一样跑)
21
  scripts/build_reference.py 生成某个家族的官方参考数据
22
- space/ 看板页面
 
 
23
  octo-hf/ Octo-patch 新场景:给下游仓库提 base_model PR
24
  eval/ 分类准确率评估(独立标注 + 对比)
25
  ```
@@ -30,6 +33,7 @@ eval/ 分类准确率评估(独立标注 + 对比)
30
  raw/<family>/YYYY-MM-DD.parquet 每天一份,只追加不修改;每日下载在读取时由相邻两份相减得到
31
  labels/<family>/latest.parquet 当前分类结果,带规则版本号,可随时重算
32
  cache/<family>/enrich.jsonl 每个仓库的证据,按仓库 sha 缓存,没变的仓库不重复读
 
33
  ```
34
 
35
  ## 加一个模型家族
@@ -39,11 +43,18 @@ cache/<family>/enrich.jsonl 每个仓库的证据,按仓库 sha 缓存
39
  3. `python scripts/build_reference.py --family <key>` 生成官方参考数据。
40
  4. `python scripts/daily.py --family <key>` 试跑,用 `eval/` 的方法抽样核对准确率。
41
 
42
- 定时任务和看板会自动带上新家族(看板顶部出现家族切换)。
 
 
 
 
43
 
44
  ## 本地运行
45
 
46
  ```bash
47
  python scripts/daily.py --family h3 # 只在本地生成,不推送
48
  python scripts/daily.py --family h3 --push # 推送到数据集和 Space
 
 
 
49
  ```
 
15
  discover.py 找候选仓库(Model tree 逐层往下、名字、标签、模型卡全文、Space)
16
  enrich.py 只读文件头和少量字节收集证据(不下载权重)
17
  classify.py 三档证据判定:属于哪个成员、什么关系、base_model 声明对不对
18
+ metrics.py 每日下载(相邻快照相减)和看板数据(会公开,只放页面用到的字段)
19
+ authors.py 作者头像和名字(缓存,只查新作者)
20
  store.py 存储布局
21
  scripts/daily.py 每日任务入口(本地和 HF Jobs 一样跑)
22
  scripts/build_reference.py 生成某个家族的官方参考数据
23
+ scripts/push_code.py 把代码同步到数据集的 code/(每日任务从那里取代码)
24
+ scripts/deploy_space.py 构建 web/ 并上传到 Space(只在页面改动时需要)
25
+ web/ 看板页面源码(React + Tailwind + shadcn/ui + Recharts,生态全景用 d3-force)
26
  octo-hf/ Octo-patch 新场景:给下游仓库提 base_model PR
27
  eval/ 分类准确率评估(独立标注 + 对比)
28
  ```
 
33
  raw/<family>/YYYY-MM-DD.parquet 每天一份,只追加不修改;每日下载在读取时由相邻两份相减得到
34
  labels/<family>/latest.parquet 当前分类结果,带规则版本号,可随时重算
35
  cache/<family>/enrich.jsonl 每个仓库的证据,按仓库 sha 缓存,没变的仓库不重复读
36
+ cache/authors.json 作者头像和显示名
37
  ```
38
 
39
  ## 加一个模型家族
 
43
  3. `python scripts/build_reference.py --family <key>` 生成官方参考数据。
44
  4. `python scripts/daily.py --family <key>` 试跑,用 `eval/` 的方法抽样核对准确率。
45
 
46
+ 定时任务会自动带上新家族;看板目前只读第一个家族,加第二个时要在 `web/src/App.tsx` 加切换。
47
+
48
+ ## 公开前要注意
49
+
50
+ 看板 Space 以后会公开。页面数据只有页面用到的字段:没有分类依据、置信度、声明状态。成人内容(名字、HF 的成人标签、模型卡自述、同作者多个成人仓库、它们的复制和下游)照常计数,但不在页面上出现名字;`families/<key>.py` 的 `nsfw_author_exempt` 是例外名单。规则是尽力而为,公开前请人工过一遍"全部衍生模型"。
51
 
52
  ## 本地运行
53
 
54
  ```bash
55
  python scripts/daily.py --family h3 # 只在本地生成,不推送
56
  python scripts/daily.py --family h3 --push # 推送到数据集和 Space
57
+ python scripts/push_code.py # 代码改动后同步给每日任务
58
+ python scripts/deploy_space.py # 页面改动后重新构建上传
59
+ cd web && npm run dev # 本地看页面(数据放 web/public/data/,不会上传)
60
  ```
code/eval/compare.py DELETED
@@ -1,96 +0,0 @@
1
- """Compare classifier labels with independent hand labels.
2
-
3
- python eval/compare.py [--family h3]
4
-
5
- Inputs: data/labels/<family>/latest.parquet, eval/labels_part*.json (independent
6
- labels for a stratified sample) and eval/seed_awesome.json (hand-checked entries from
7
- the integrations list, lineage only).
8
- """
9
- import argparse
10
- import json
11
- import sys
12
- from collections import Counter
13
- from pathlib import Path
14
-
15
- import pandas as pd
16
-
17
- ROOT = Path(__file__).resolve().parent.parent
18
- sys.path.insert(0, str(ROOT))
19
- from hfeco import store # noqa: E402
20
-
21
- ap = argparse.ArgumentParser()
22
- ap.add_argument("--family", default="h3")
23
- ap.add_argument("--show", action="store_true", help="print every disagreement")
24
- ap.add_argument("--set", default="sample", choices=["sample", "holdout"],
25
- help="sample = the 100 repos used while tuning; holdout = 60 fresh repos labelled after the freeze")
26
- a = ap.parse_args()
27
-
28
- lab = pd.read_parquet(store.LOCAL / "labels" / a.family / "latest.parquet").set_index(["kind", "repo_id"])
29
- lab["evidence"] = lab.evidence.apply(json.loads)
30
- hand = []
31
- pattern = "labels_part*.json" if a.set == "sample" else "holdout_labels_part*.json"
32
- for p in sorted((ROOT / "eval").glob(pattern)):
33
- hand += json.load(open(p))
34
- sample = {x["repo_id"]: x for x in json.load(open(ROOT / "eval" / ("sample.json" if a.set == "sample" else "holdout.json")))}
35
-
36
- # Relations that count as the same answer for this check.
37
- SAME_REL = {"no-weights": "no-weights", None: None}
38
-
39
-
40
- def norm_rel(x):
41
- return None if x in (None, "null", "") else x
42
-
43
-
44
- rows = []
45
- for h in hand:
46
- rid = h["repo_id"]
47
- key = (sample.get(rid, {}).get("kind", "model"), rid)
48
- if key not in lab.index:
49
- rows.append({**h, "ours_lin": "(not found)", "ours_rel": None, "stratum": sample.get(rid, {}).get("stratum")})
50
- continue
51
- o = lab.loc[key]
52
- rows.append({"repo_id": rid, "stratum": sample.get(rid, {}).get("stratum"), "kind": key[0],
53
- "hand_lin": h["lineage"], "hand_rel": norm_rel(h.get("relation")), "hand_conf": h.get("confidence"),
54
- "ours_lin": o.lineage, "ours_rel": norm_rel(o.relation), "ours_conf": o.confidence,
55
- "reason": h.get("reason"), "evidence": o.evidence})
56
- df = pd.DataFrame(rows)
57
- df["lin_ok"] = df.hand_lin == df.ours_lin
58
- # "in family as H3" is what the dashboard counts; check it as its own yes/no question.
59
- df["is_h3_hand"] = df.hand_lin == "H3"
60
- df["is_h3_ours"] = df.ours_lin == "H3"
61
- fam_rel = df[df.hand_lin.isin(["H3", "H3-Image", "H3-Image-PE"]) & df.lin_ok]
62
- fam_rel = fam_rel.assign(rel_ok=fam_rel.hand_rel == fam_rel.ours_rel)
63
-
64
- print(f"{a.set}: {len(df)} repos")
65
- print(f" lineage agreement: {df.lin_ok.mean():.1%} ({df.lin_ok.sum()}/{len(df)})")
66
- tp = (df.is_h3_hand & df.is_h3_ours).sum()
67
- fp = (~df.is_h3_hand & df.is_h3_ours).sum()
68
- fn = (df.is_h3_hand & ~df.is_h3_ours).sum()
69
- print(f" counted as H3: precision {tp / max(1, tp + fp):.1%} ({tp}/{tp + fp}), recall {tp / max(1, tp + fn):.1%} ({tp}/{tp + fn})")
70
- print(f" relation agreement (where lineage agrees, family repos): {fam_rel.rel_ok.mean():.1%} "
71
- f"({fam_rel.rel_ok.sum()}/{len(fam_rel)})")
72
- print(" by our confidence:")
73
- for c, g in df.groupby("ours_conf"):
74
- print(f" {c}: {g.lin_ok.mean():.1%} lineage agreement ({g.lin_ok.sum()}/{len(g)})")
75
- print(" confusion (hand -> ours):", dict(Counter(zip(df.hand_lin, df.ours_lin)).most_common()))
76
-
77
- seed = json.load(open(ROOT / "eval" / "seed_awesome.json"))
78
- seed["MiniMaxAI/MiniMax-H3-Image-PE"] = "H3-Image-PE"
79
- s = [(rid, lin, lab.loc[("model", rid)].lineage if ("model", rid) in lab.index else "(not found)")
80
- for rid, lin in seed.items()]
81
- ok = sum(1 for _, a_, b in s if a_ == b)
82
- print(f"\nseed list (hand-checked integrations entries): {ok}/{len(s)} lineage agreement")
83
-
84
- if a.show:
85
- print("\n--- disagreements (independent sample) ---")
86
- for r in df[~df.lin_ok].itertuples():
87
- print(f"{r.repo_id} [{r.stratum}] hand={r.hand_lin}/{r.hand_rel} ours={r.ours_lin}/{r.ours_rel} ({r.ours_conf})")
88
- print(f" hand: {r.reason}")
89
- print(f" ours: {r.evidence}")
90
- print("\n--- relation disagreements ---")
91
- for r in fam_rel[~fam_rel.rel_ok].itertuples():
92
- print(f"{r.repo_id} {r.hand_lin}: hand={r.hand_rel} ours={r.ours_rel} | hand: {r.reason}")
93
- print("\n--- seed disagreements ---")
94
- for rid, a_, b in s:
95
- if a_ != b:
96
- print(rid, "seed", a_, "ours", b)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
code/hfeco/authors.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Author avatars and display names for the dashboard, cached across runs.
2
+
3
+ cache/authors.json maps an HF user or org name to {"a": avatar url, "n": display name}.
4
+ Only names not in the cache are fetched, so a daily run makes a handful of calls.
5
+ """
6
+ import json
7
+ from concurrent.futures import ThreadPoolExecutor
8
+
9
+ from . import store
10
+ from .hub import api, retry
11
+
12
+
13
+ def path():
14
+ return store.LOCAL / "cache" / "authors.json"
15
+
16
+
17
+ AVATAR_HOSTS = ("https://cdn-avatars.huggingface.co/", "https://huggingface.co/")
18
+
19
+
20
+ def _one(name):
21
+ """(name, entry), or (name, None) when the lookup failed for a reason worth retrying."""
22
+ missing = 0
23
+ # The same name is either a user or an org; the wrong endpoint answers 404.
24
+ for fn in (api.get_user_overview, api.get_organization_overview):
25
+ try:
26
+ o = retry(fn, name)
27
+ except Exception as e:
28
+ if getattr(getattr(e, "response", None), "status_code", None) == 404:
29
+ missing += 1
30
+ continue
31
+ return name, None
32
+ a = o.avatar_url or None
33
+ if a and a.startswith("/"):
34
+ a = "https://huggingface.co" + a
35
+ if a and not a.startswith(AVATAR_HOSTS): # shown on a public page: only HF-hosted images
36
+ a = None
37
+ return name, {"a": a, "n": o.fullname or name}
38
+ return name, ({"a": None, "n": name} if missing == 2 else None)
39
+
40
+
41
+ def update(names, log=print, workers=8):
42
+ p = path()
43
+ cache = json.loads(p.read_text()) if p.exists() else {}
44
+ todo = sorted(set(names) - set(cache))
45
+ with ThreadPoolExecutor(workers) as ex:
46
+ for name, v in ex.map(_one, todo):
47
+ if v is not None:
48
+ cache[name] = v
49
+ p.parent.mkdir(parents=True, exist_ok=True)
50
+ p.write_text(json.dumps(cache, ensure_ascii=False))
51
+ log(f"authors: {len(todo)} fetched, {len(cache)} cached")
52
+ return cache, p
code/hfeco/classify.py CHANGED
@@ -16,7 +16,7 @@ import re
16
 
17
  import numpy as np
18
 
19
- VERSION = "2026-11-17.8"
20
  DERIVED = {"adapter", "finetune", "merge", "quantized", "repackage", "mirror", "component"}
21
  HF_RELATIONS = {"adapter", "finetune", "merge", "quantized"}
22
  SAME = 1e-3 # probe distance below this = same weights (bf16 -> fp16 copies land at ~0)
@@ -30,8 +30,21 @@ REPACK_NAME = re.compile(r"comfy|diffusers|single[-_ ]?file|repack|split|bf16|fp
30
  TUNED_NAME = re.compile(r"finetun|fine-tun|\bft\b|turbo|lightning|distill|\d+[-_ ]?steps?|\bacc\b|fast|"
31
  r"lcm|dmd|pdmd|singularity|eros|nsfw|uncensor|heretic|abliterat", re.I)
32
  DISTILL_NAME = re.compile(r"turbo|lightning|distill|\d+[-_ ]?steps?|\bacc\b|lcm|dmd|pdmd|fast", re.I)
33
- NSFW = re.compile(r"nsfw|porn|hentai|nude|nudity|\bsex|dildo|cumshot|\bcum\b|pussy|deepthroat|blowjob|"
34
- r"erotic|(?:\b|(?<=\d)|(?<=ten)|(?<=_))eros(?![a-z])|xxx|uncensor", re.I) # "10Eros", "TenEros"
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  # Training/merge tools describe merges in prose; quantizers have a bare "merge" field for a compute step.
36
  META_MERGE = re.compile(r"lora[ _-]?merg|merged|graft|merge[ _](of|from|method|ratio|weights)|linear merge|"
37
  r"consensus merge|baked", re.I)
@@ -110,7 +123,7 @@ def classify_model(r, ev, g, cutoff, fam):
110
  name = rid.split("/")[1]
111
  readme = (ev or {}).get("readme") or ""
112
  text = " ".join([name, " ".join(r["tags"]), readme])
113
- flags = ["nsfw"] if ("not-for-all-audiences" in r["tags"] or NSFW.search(rid)) else []
114
  lob = fam.lineage_of_base()
115
 
116
  if rid in lob:
@@ -451,6 +464,7 @@ def classify_all(raw_today, cache, fam):
451
  lab.update(declared_status(r, lab, g, fam))
452
  mlabels[r["repo_id"]] = lab
453
  out.append({"kind": "model", "repo_id": r["repo_id"], **lab})
 
454
  for r in rows:
455
  if r["kind"] == "space":
456
  out.append({"kind": "space", "repo_id": r["repo_id"], **classify_space(r, mlabels, fam)})
@@ -462,6 +476,42 @@ def classify_all(raw_today, cache, fam):
462
  return out
463
 
464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465
  def declared_status(r, lab, g, fam):
466
  decl = declared_member(r["repo_id"], g, fam)
467
  hf_rel = r["hf_parents"][0].split(":")[0] if r["hf_parents"] else None
 
16
 
17
  import numpy as np
18
 
19
+ VERSION = "2026-11-17.9"
20
  DERIVED = {"adapter", "finetune", "merge", "quantized", "repackage", "mirror", "component"}
21
  HF_RELATIONS = {"adapter", "finetune", "merge", "quantized"}
22
  SAME = 1e-3 # probe distance below this = same weights (bf16 -> fp16 copies land at ~0)
 
30
  TUNED_NAME = re.compile(r"finetun|fine-tun|\bft\b|turbo|lightning|distill|\d+[-_ ]?steps?|\bacc\b|fast|"
31
  r"lcm|dmd|pdmd|singularity|eros|nsfw|uncensor|heretic|abliterat", re.I)
32
  DISTILL_NAME = re.compile(r"turbo|lightning|distill|\d+[-_ ]?steps?|\bacc\b|lcm|dmd|pdmd|fast", re.I)
33
+ # Adult content is counted like anything else but never named on the (public) dashboard, so
34
+ # these lean towards hiding. Names: explicit words, also inside compounds ("epiccum", "Tit_Fuck").
35
+ NSFW = re.compile(r"nsfw|porn|hentai|nude|nudity|naked|sex|dildo|cum(?![a-z])|cumshot|blowj|blow[-_ ]?job|"
36
+ r"deep[-_ ]?throat|pussy|vagina|penis|dick(?![a-z])|cock(?![a-z])|tits?(?![a-z])|titty|"
37
+ r"titties|tiddies|boob|breast|nipple|anal(?![a-z])|orgasm|squirt|creampie|bukkake|milf|"
38
+ r"futa|bdsm|bondage|fetish|lewd|ecchi|ahegao|fuck|erotic|xxx|uncensor|strip(?:tease|per)|"
39
+ r"onlyfans|topless|undress|lingerie|bikini|r18|moan|pleasure|writh|cowgirl|doggy|missionary|"
40
+ r"panties|underwear|masturbat|handjob|footjob|grop(?:e|ing)|jiggl|booty|twerk|thicc|seduc|"
41
+ r"sensual|horny|slut|whore|bimbo|busty|cleavage|upskirt|voyeur|"
42
+ r"(?:(?<=\d)|(?<=ten))eros|(?:\b|(?<=_))eros(?![a-z])", re.I) # "10ErosMax", "TenEros"
43
+ # Cards only count when they describe the model itself as adult: derivatives copy the official
44
+ # license ("unlawful, pornographic, or ...") and many cards say "does not contain NSFW content".
45
+ NSFW_CARD = re.compile(r"\bnsfw[- ](?:lora|model|version|finetune|fine-tune|merge|capable|focused|checkpoint)s?\b|"
46
+ r"trained on .{0,30}\bporn|\bhentai\b|\bnudity\b|explicit sexual|not-for-all-audiences",
47
+ re.I)
48
  # Training/merge tools describe merges in prose; quantizers have a bare "merge" field for a compute step.
49
  META_MERGE = re.compile(r"lora[ _-]?merg|merged|graft|merge[ _](of|from|method|ratio|weights)|linear merge|"
50
  r"consensus merge|baked", re.I)
 
123
  name = rid.split("/")[1]
124
  readme = (ev or {}).get("readme") or ""
125
  text = " ".join([name, " ".join(r["tags"]), readme])
126
+ flags = ["nsfw"] if ("not-for-all-audiences" in r["tags"] or NSFW.search(rid) or NSFW_CARD.search(readme)) else []
127
  lob = fam.lineage_of_base()
128
 
129
  if rid in lob:
 
464
  lab.update(declared_status(r, lab, g, fam))
465
  mlabels[r["repo_id"]] = lab
466
  out.append({"kind": "model", "repo_id": r["repo_id"], **lab})
467
+ _nsfw_spread(mlabels, g, fam)
468
  for r in rows:
469
  if r["kind"] == "space":
470
  out.append({"kind": "space", "repo_id": r["repo_id"], **classify_space(r, mlabels, fam)})
 
476
  return out
477
 
478
 
479
+ def _nsfw_spread(mlabels, g, fam):
480
+ """Adult flags beyond a repo's own name/tags/card. These only decide what the public page
481
+ names; every repo is still counted.
482
+
483
+ - Whole-repo copies and declared children of an adult repo (a GGUF of an adult finetune
484
+ rarely says so in its name).
485
+ - Every repo of an author with several adult repos ("nsfw_author"), except publishers in
486
+ fam.nsfw_author_exempt whose adult repos are a small part of their work.
487
+ """
488
+ hidden = lambda rid: bool({"nsfw", "nsfw_author"} & set(mlabels.get(rid, {}).get("flags", [])))
489
+
490
+ def spread():
491
+ for _ in range(4):
492
+ for rid, lab in mlabels.items():
493
+ if hidden(rid):
494
+ continue
495
+ ups = ([lab["copy_of"]] if lab.get("copy_of") else []) + [p for _, p in g.get(rid, [])]
496
+ if any(hidden(u) for u in ups):
497
+ lab["flags"].append("nsfw")
498
+
499
+ spread()
500
+ by_author = {}
501
+ for rid, lab in mlabels.items():
502
+ if lab["family"]:
503
+ by_author.setdefault(rid.split("/")[0], []).append(lab)
504
+ for author, labs in by_author.items():
505
+ n = sum("nsfw" in x["flags"] for x in labs)
506
+ if author in fam.nsfw_author_exempt:
507
+ continue
508
+ if n >= 3 or (n >= 2 and n / len(labs) >= 0.25) or (n and n / len(labs) >= 0.5):
509
+ for x in labs:
510
+ if "nsfw" not in x["flags"]:
511
+ x["flags"].append("nsfw_author")
512
+ spread()
513
+
514
+
515
  def declared_status(r, lab, g, fam):
516
  decl = declared_member(r["repo_id"], g, fam)
517
  hf_rel = r["hf_parents"][0].split(":")[0] if r["hf_parents"] else None
code/hfeco/families/h3.py CHANGED
@@ -75,6 +75,7 @@ FAMILY = Family(
75
  (VIDEO_TEXT, "H3", 2, "模型卡讲的是视频生成", True),
76
  ],
77
  native_quant={"H3-Image-PE": re.compile(r"nvfp4|fp4|modelopt", re.I)}, # the official PE ships as NVFP4
 
78
  text_member="H3-Image-PE",
79
  text_member_hint=PE_TEXT,
80
  text_member_name=re.compile(r"h3[-_ ]?image[-_ ]?pe|image[-_]pe\b", re.I),
 
75
  (VIDEO_TEXT, "H3", 2, "模型卡讲的是视频生成", True),
76
  ],
77
  native_quant={"H3-Image-PE": re.compile(r"nvfp4|fp4|modelopt", re.I)}, # the official PE ships as NVFP4
78
+ nsfw_author_exempt={"RunningHubAI", "Abiray"},
79
  text_member="H3-Image-PE",
80
  text_member_hint=PE_TEXT,
81
  text_member_name=re.compile(r"h3[-_ ]?image[-_ ]?pe|image[-_]pe\b", re.I),
code/hfeco/family.py CHANGED
@@ -58,6 +58,9 @@ class Family:
58
  text_component: Optional[re.Pattern] = None # e.g. the family's own text encoder
59
  component_names: Optional[re.Pattern] = None
60
  native_quant: dict = field(default_factory=dict) # lineage -> regex of the member's own quant format
 
 
 
61
 
62
  _ref: dict = None
63
 
 
58
  text_component: Optional[re.Pattern] = None # e.g. the family's own text encoder
59
  component_names: Optional[re.Pattern] = None
60
  native_quant: dict = field(default_factory=dict) # lineage -> regex of the member's own quant format
61
+ # Publishers with many ordinary repos: their few adult repos are hidden one by one, the rest stay
62
+ # on the page (otherwise an author with several adult repos is hidden entirely).
63
+ nsfw_author_exempt: set = field(default_factory=set)
64
 
65
  _ref: dict = None
66
 
code/hfeco/metrics.py CHANGED
@@ -28,7 +28,7 @@ def daily_downloads(raw):
28
  return df[["kind", "repo_id", "day", "daily", "negative"]]
29
 
30
 
31
- def build(raw, labels, hf_tree_counts, fam):
32
  """The dashboard's data file. The Space may become public, so this is a whitelist of
33
  what the page renders: no evidence, confidence, declaration status or flags, and no
34
  names of NSFW repos (they still count in the totals). Internal detail stays in the
@@ -51,13 +51,15 @@ def build(raw, labels, hf_tree_counts, fam):
51
  models = famdf[(famdf.lineage == lin) & (famdf.kind == "model") & famdf.relation.isin(REL_ORDER)
52
  & (famdf.repo_id != base)]
53
  off = cur[(cur.kind == "model") & (cur.repo_id == base)]
54
- d = dd.merge(models[["repo_id"]], on="repo_id").dropna(subset=["daily"])
55
- daily = d.groupby("day").daily.sum().round().astype(int)
56
- growth = models.created_at.str[:10].value_counts().sort_index()
57
  out["lineages"][lin] = {
58
  "base": base,
59
- "official": {"dl30": _i(off.downloads_30d), "dlall": _i(off.downloads_all_time)},
 
60
  "n_models": int(len(models)),
 
61
  "dl30": int(models.downloads_30d.fillna(0).sum()),
62
  "dlall": int(models.downloads_all_time.fillna(0).sum()),
63
  "by_relation": {rel: {"n": int((models.relation == rel).sum()),
@@ -65,11 +67,20 @@ def build(raw, labels, hf_tree_counts, fam):
65
  "dlall": int(models[models.relation == rel].downloads_all_time.fillna(0).sum())}
66
  for rel in REL_ORDER},
67
  "hf_tree": hf_tree_counts.get(base, {}),
68
- "daily": [{"day": k, "n": int(v)} for k, v in daily.items()],
69
- "growth": [{"date": k, "n": int(v)} for k, v in growth.items()],
70
  }
 
 
 
 
 
 
 
 
71
  up = tree_parents(models, base)
72
- nsfw = set(models[models["flags"].apply(lambda f: "nsfw" in (f if isinstance(f, list) else []))].repo_id)
 
73
  for r in models[~models.repo_id.isin(nsfw)].itertuples():
74
  p = up[r.repo_id]
75
  while p in nsfw: # hidden repos keep their place in the totals, not in the tree
@@ -77,7 +88,10 @@ def build(raw, labels, hf_tree_counts, fam):
77
  v = last.get(r.repo_id)
78
  out["repos"].append({"id": r.repo_id, "lin": lin, "rel": r.relation, "up": p,
79
  "dl30": _i(r.downloads_30d), "dlall": _i(r.downloads_all_time),
80
- "d1": None if v is None or pd.isna(v) else int(round(v))})
 
 
 
81
  return out
82
 
83
 
 
28
  return df[["kind", "repo_id", "day", "daily", "negative"]]
29
 
30
 
31
+ def build(raw, labels, hf_tree_counts, fam, authors=None):
32
  """The dashboard's data file. The Space may become public, so this is a whitelist of
33
  what the page renders: no evidence, confidence, declaration status or flags, and no
34
  names of NSFW repos (they still count in the totals). Internal detail stays in the
 
51
  models = famdf[(famdf.lineage == lin) & (famdf.kind == "model") & famdf.relation.isin(REL_ORDER)
52
  & (famdf.repo_id != base)]
53
  off = cur[(cur.kind == "model") & (cur.repo_id == base)]
54
+ d = dd.merge(models[["repo_id", "relation"]], on="repo_id").dropna(subset=["daily"])
55
+ daily = d.groupby(["day", "relation"]).daily.sum().round().astype(int)
56
+ growth = models.assign(date=models.created_at.str[:10]).groupby(["date", "relation"]).size()
57
  out["lineages"][lin] = {
58
  "base": base,
59
+ "official": {"dl30": _i(off.downloads_30d), "dlall": _i(off.downloads_all_time),
60
+ "likes": _i(off.likes)},
61
  "n_models": int(len(models)),
62
+ "n_authors": int(models.repo_id.str.split("/").str[0].nunique()),
63
  "dl30": int(models.downloads_30d.fillna(0).sum()),
64
  "dlall": int(models.downloads_all_time.fillna(0).sum()),
65
  "by_relation": {rel: {"n": int((models.relation == rel).sum()),
 
67
  "dlall": int(models[models.relation == rel].downloads_all_time.fillna(0).sum())}
68
  for rel in REL_ORDER},
69
  "hf_tree": hf_tree_counts.get(base, {}),
70
+ "daily": [{"day": k[0], "rel": k[1], "n": int(v)} for k, v in daily.items()],
71
+ "growth": [{"date": k[0], "rel": k[1], "n": int(v)} for k, v in growth.items()],
72
  }
73
+ # Most active authors, by models they made themselves (whole-repo copies don't count).
74
+ own = models[models.copy_of.isna() & ~models["flags"].apply(
75
+ lambda f: bool({"nsfw", "nsfw_author"} & set(f if isinstance(f, list) else [])))]
76
+ ta = (own.assign(a=own.repo_id.str.split("/").str[0])
77
+ .groupby("a").agg(n=("repo_id", "size"), dlall=("downloads_all_time", "sum"))
78
+ .sort_values(["n", "dlall"], ascending=False).head(12))
79
+ out["lineages"][lin]["top_authors"] = [{"a": k, "n": int(v.n), "dlall": int(v.dlall or 0)}
80
+ for k, v in ta.iterrows()]
81
  up = tree_parents(models, base)
82
+ nsfw = set(models[models["flags"].apply(
83
+ lambda f: bool({"nsfw", "nsfw_author"} & set(f if isinstance(f, list) else [])))].repo_id)
84
  for r in models[~models.repo_id.isin(nsfw)].itertuples():
85
  p = up[r.repo_id]
86
  while p in nsfw: # hidden repos keep their place in the totals, not in the tree
 
88
  v = last.get(r.repo_id)
89
  out["repos"].append({"id": r.repo_id, "lin": lin, "rel": r.relation, "up": p,
90
  "dl30": _i(r.downloads_30d), "dlall": _i(r.downloads_all_time),
91
+ "d1": None if v is None or pd.isna(v) else int(round(v)),
92
+ "likes": _i(r.likes), "created": (r.created_at or "")[:10]})
93
+ names = {r["id"].split("/")[0] for r in out["repos"]} | {m.base.split("/")[0] for m in fam.tracked}
94
+ out["authors"] = {n: (authors or {}).get(n, {"a": None, "n": n}) for n in sorted(names)}
95
  return out
96
 
97
 
code/scripts/daily.py CHANGED
@@ -17,7 +17,7 @@ import pandas as pd
17
 
18
  ROOT = Path(__file__).resolve().parent.parent
19
  sys.path.insert(0, str(ROOT))
20
- from hfeco import classify, discover, families, metrics, pipeline, store # noqa: E402
21
  from hfeco.hub import api # noqa: E402
22
 
23
  SPACE_REPO = "MiniMaxAI/oss-ecosystem"
@@ -56,12 +56,14 @@ for key in args.family:
56
  ldf[c] = ldf[c].apply(lambda v: json.dumps(v, ensure_ascii=False))
57
  ldf.to_parquet(lab_path, index=False)
58
 
59
- data = metrics.build(raw, labels, metrics.hf_tree_counts(today, fam), fam)
 
 
60
  data_path = store.LOCAL / "dashboard" / f"{fam.key}.json"
61
  metrics.dump(data, data_path)
62
  log(f"{fam.key}: {len(labels)} labels, {len(data['repos'])} repos on the dashboard")
63
  if args.push:
64
- store.push([lab_path, cache_path], f"{fam.key}: labels {data['today']}")
65
  api.upload_file(path_or_fileobj=str(data_path), path_in_repo=f"data/{fam.key}.json",
66
  repo_id=SPACE_REPO, repo_type="space", commit_message=f"{fam.key}: data {data['today']}")
67
 
 
17
 
18
  ROOT = Path(__file__).resolve().parent.parent
19
  sys.path.insert(0, str(ROOT))
20
+ from hfeco import authors, classify, discover, families, metrics, pipeline, store # noqa: E402
21
  from hfeco.hub import api # noqa: E402
22
 
23
  SPACE_REPO = "MiniMaxAI/oss-ecosystem"
 
56
  ldf[c] = ldf[c].apply(lambda v: json.dumps(v, ensure_ascii=False))
57
  ldf.to_parquet(lab_path, index=False)
58
 
59
+ fam_ids = [x["repo_id"] for x in labels if x.get("family") and x["kind"] == "model"]
60
+ who, who_path = authors.update({i.split("/")[0] for i in fam_ids} | {b.split("/")[0] for b in fam.bases}, log=log)
61
+ data = metrics.build(raw, labels, metrics.hf_tree_counts(today, fam), fam, who)
62
  data_path = store.LOCAL / "dashboard" / f"{fam.key}.json"
63
  metrics.dump(data, data_path)
64
  log(f"{fam.key}: {len(labels)} labels, {len(data['repos'])} repos on the dashboard")
65
  if args.push:
66
+ store.push([lab_path, cache_path, who_path], f"{fam.key}: labels {data['today']}")
67
  api.upload_file(path_or_fileobj=str(data_path), path_in_repo=f"data/{fam.key}.json",
68
  repo_id=SPACE_REPO, repo_type="space", commit_message=f"{fam.key}: data {data['today']}")
69
 
code/scripts/deploy_space.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the dashboard page (web/) and upload it to the Space, leaving data/ alone.
2
+
3
+ python scripts/deploy_space.py
4
+
5
+ The page is static: it reads data/index.json and data/<family>.json, which the daily job
6
+ replaces. This only needs re-running when the page itself changes.
7
+ """
8
+ import subprocess
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ ROOT = Path(__file__).resolve().parent.parent
13
+ sys.path.insert(0, str(ROOT))
14
+ from huggingface_hub import CommitOperationAdd, CommitOperationDelete # noqa: E402
15
+
16
+ from hfeco.hub import api # noqa: E402
17
+
18
+ SPACE = "MiniMaxAI/oss-ecosystem"
19
+ KEEP = ("data/", "README.md", ".gitattributes")
20
+
21
+ subprocess.run(["npm", "run", "build"], cwd=ROOT / "web", check=True)
22
+ dist = ROOT / "web" / "dist"
23
+ files = [p for p in dist.rglob("*") if p.is_file() and not p.relative_to(dist).as_posix().startswith("data/")]
24
+ local = {p.relative_to(dist).as_posix() for p in files}
25
+ remote = set(api.list_repo_files(SPACE, repo_type="space"))
26
+ ops = [CommitOperationAdd(path_in_repo=p.relative_to(dist).as_posix(), path_or_fileobj=str(p)) for p in files]
27
+ ops += [CommitOperationDelete(path_in_repo=f) for f in sorted(remote - local) if not f.startswith(KEEP)]
28
+ api.create_commit(SPACE, ops, repo_type="space", commit_message="dashboard page")
29
+ print(f"uploaded {len(local)} files, removed {len(ops) - len(local)}")
code/scripts/push_code.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Upload the pipeline code to the dataset repo's code/ folder (the daily HF Job runs from there).
2
+
3
+ python scripts/push_code.py
4
+
5
+ Uploads every git-tracked file outside web/ and eval/, so a new module can't be forgotten.
6
+ """
7
+ import subprocess
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ ROOT = Path(__file__).resolve().parent.parent
12
+ sys.path.insert(0, str(ROOT))
13
+ from huggingface_hub import CommitOperationAdd, CommitOperationDelete # noqa: E402
14
+
15
+ from hfeco.hub import api # noqa: E402
16
+ from hfeco.store import DATASET_REPO # noqa: E402
17
+
18
+ files = subprocess.run(["git", "ls-files"], cwd=ROOT, capture_output=True, text=True, check=True).stdout.split()
19
+ files = [f for f in files if not f.startswith(("web/", "eval/", "space/"))]
20
+ remote = {f[len("code/"):] for f in api.list_repo_files(DATASET_REPO, repo_type="dataset") if f.startswith("code/")}
21
+ ops = [CommitOperationAdd(path_in_repo=f"code/{f}", path_or_fileobj=str(ROOT / f)) for f in files]
22
+ ops += [CommitOperationDelete(path_in_repo=f"code/{f}") for f in sorted(remote - set(files))]
23
+ api.create_commit(DATASET_REPO, ops, repo_type="dataset", commit_message="code: sync from git")
24
+ print(f"code/: {len(files)} files uploaded, {len(remote - set(files))} removed")
code/space/README.md DELETED
@@ -1,10 +0,0 @@
1
- ---
2
- title: MiniMax-H3 开源生态
3
- emoji: 📈
4
- colorFrom: blue
5
- colorTo: gray
6
- sdk: static
7
- pinned: false
8
- ---
9
-
10
- MiniMax-H3 家族(H3、H3-Image、H3-Image-PE)在 Hugging Face 上的下游仓库统计。数据每天由 HF Jobs 定时任务更新,原始快照在私有数据集 `MiniMaxAI/h3-ecosystem-data`。
 
 
 
 
 
 
 
 
 
 
 
code/space/index.html DELETED
@@ -1,357 +0,0 @@
1
- <!doctype html>
2
- <html lang="zh-CN">
3
- <head>
4
- <meta charset="utf-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1">
6
- <title>MiniMax 开源生态</title>
7
- <script src="https://cdn.jsdelivr.net/npm/echarts@5.5.1/dist/echarts.min.js"></script>
8
- <style>
9
- :root {
10
- color-scheme: light;
11
- --page: #f9f9f7; --surface: #fcfcfb; --ink: #0b0b0b; --ink2: #52514e; --muted: #898781;
12
- --grid: #e1e0d9; --axis: #c3c2b7; --ring: rgba(11,11,11,0.10); --wash: #f0efec;
13
- --s1: #2a78d6; --s2: #eb6834; --s3: #1baf7a; --s4: #eda100; --s5: #e87ba4; --s6: #008300; --s7: #6250d6;
14
- --accent: #2a78d6; --bar: #6b6a65;
15
- }
16
- @media (prefers-color-scheme: dark) {
17
- :root:not([data-theme="light"]) {
18
- color-scheme: dark;
19
- --page: #0d0d0d; --surface: #1a1a19; --ink: #f0efec; --ink2: #c3c2b7; --muted: #898781;
20
- --grid: #2c2c2a; --axis: #45453f; --ring: rgba(255,255,255,0.10); --wash: #262624;
21
- --s1: #3987e5; --s2: #d95926; --s3: #199e70; --s4: #c98500; --s5: #d55181; --s6: #0ca30c; --s7: #9085e9;
22
- --accent: #3987e5; --bar: #a3a29b;
23
- }
24
- }
25
- :root[data-theme="dark"] {
26
- color-scheme: dark;
27
- --page: #0d0d0d; --surface: #1a1a19; --ink: #f0efec; --ink2: #c3c2b7; --muted: #898781;
28
- --grid: #2c2c2a; --axis: #45453f; --ring: rgba(255,255,255,0.10); --wash: #262624;
29
- --s1: #3987e5; --s2: #d95926; --s3: #199e70; --s4: #c98500; --s5: #d55181; --s6: #0ca30c; --s7: #9085e9;
30
- --accent: #3987e5; --bar: #a3a29b;
31
- }
32
- * { box-sizing: border-box; }
33
- body { margin: 0; background: var(--page); color: var(--ink);
34
- font: 16px/1.55 system-ui, -apple-system, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; }
35
- .wrap { max-width: 1240px; margin: 0 auto; padding: 32px 16px 72px; }
36
- header { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 24px; }
37
- h1 { font-size: 30px; margin: 0; font-weight: 650; letter-spacing: -0.01em; }
38
- .seg { display: inline-flex; flex-wrap: wrap; background: var(--surface); border: 1px solid var(--ring); border-radius: 10px; padding: 3px; }
39
- .seg button { border: 0; background: transparent; color: var(--ink2); font: inherit; font-size: 16px; padding: 8px 16px; border-radius: 7px; cursor: pointer; }
40
- .seg button[aria-pressed="true"] { background: var(--wash); color: var(--ink); font-weight: 600; }
41
- .seg button:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
42
- #famSel { font: inherit; color: var(--ink); background: var(--page); border: 1px solid var(--axis); border-radius: 8px; padding: 7px 10px; }
43
- .tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 12px; margin-bottom: 16px; }
44
- .tile { background: var(--surface); border: 1px solid var(--ring); border-radius: 12px; padding: 18px 20px; min-width: 0; }
45
- .tile .label { color: var(--ink2); font-size: 16px; }
46
- .tile .value { font-size: 40px; font-weight: 650; line-height: 1.2; margin-top: 4px; }
47
- .card { background: var(--surface); border: 1px solid var(--ring); border-radius: 12px; padding: 20px 22px; margin-bottom: 16px; min-width: 0; }
48
- .card h2 { font-size: 20px; margin: 0 0 14px; font-weight: 620; }
49
- .row2 { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
50
- .row2.one { grid-template-columns: 1fr; }
51
- .row2 > * { min-width: 0; }
52
- @media (max-width: 900px) { .row2 { grid-template-columns: 1fr; } }
53
- @media (max-width: 600px) { .tile .value { font-size: 32px; } .card { padding: 16px 14px; } h1 { font-size: 24px; } }
54
- .chart { width: 100%; height: 320px; }
55
- .legend { display: flex; flex-wrap: wrap; gap: 6px 20px; margin: 0 0 12px; font-size: 15px; color: var(--ink2); }
56
- .legend i { display: inline-block; width: 12px; height: 12px; border-radius: 50%; margin-right: 7px; vertical-align: -1px; }
57
- .treewrap { overflow-x: auto; }
58
- .tree { display: block; font: 15px system-ui, -apple-system, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; }
59
- .tree .link { fill: none; stroke: var(--axis); stroke-width: 1.5; }
60
- .tree text { fill: var(--ink); dominant-baseline: central; }
61
- .tree .num { fill: var(--ink2); }
62
- .tree .root { font-size: 16px; font-weight: 650; }
63
- .tree a:hover .nm { fill: var(--accent); text-decoration: underline; }
64
- .tree .fold { cursor: pointer; }
65
- .tree .fold text { fill: var(--accent); }
66
- .tree .fold:hover text { text-decoration: underline; }
67
- .tree .fold circle { fill: var(--surface); stroke: var(--muted); stroke-width: 1.5; }
68
- .tree .fold:focus-visible { outline: 2px solid var(--accent); }
69
- table { width: 100%; border-collapse: collapse; font-size: 15px; }
70
- th, td { text-align: left; padding: 9px 12px; border-bottom: 1px solid var(--grid); }
71
- th { color: var(--ink2); font-weight: 560; white-space: nowrap; }
72
- th.sortable { cursor: pointer; user-select: none; }
73
- th.sortable:hover { color: var(--ink); }
74
- td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
75
- tr.sum td { font-weight: 620; }
76
- tr.sum + tr td { padding-top: 14px; }
77
- .tablewrap { overflow-x: auto; }
78
- a { color: var(--accent); text-decoration: none; }
79
- a:hover { text-decoration: underline; }
80
- td.repo { word-break: break-all; }
81
- #q { font: inherit; font-size: 15px; color: var(--ink); background: var(--page); border: 1px solid var(--axis); border-radius: 8px; padding: 8px 12px; width: 100%; max-width: 420px; margin-bottom: 12px; }
82
- .more { margin-top: 12px; font: inherit; font-size: 15px; background: var(--wash); color: var(--ink); border: 0; border-radius: 8px; padding: 8px 16px; cursor: pointer; }
83
- </style>
84
- </head>
85
- <body>
86
- <div class="wrap">
87
- <header>
88
- <h1 id="title">MiniMax 开源生态</h1>
89
- <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center">
90
- <select id="famSel" aria-label="选择模型家族" hidden></select>
91
- <div class="seg" role="group" aria-label="选择模型" id="lineageSeg"></div>
92
- </div>
93
- </header>
94
-
95
- <div class="tiles" id="tiles"></div>
96
-
97
- <section class="card">
98
- <h2>Model tree(数字为累计下载)</h2>
99
- <div class="legend" id="treeLegend"></div>
100
- <div class="treewrap"><svg class="tree" id="tree" role="group" aria-label="衍生关系树"></svg></div>
101
- </section>
102
-
103
- <section class="card">
104
- <h2>按关系类型</h2>
105
- <div class="tablewrap"><table id="relTable"></table></div>
106
- </section>
107
-
108
- <div class="row2" id="chartRow">
109
- <section class="card">
110
- <h2>每周新增衍生模型</h2>
111
- <div id="growthChart" class="chart"></div>
112
- </section>
113
- <section class="card" id="dailyCard" hidden>
114
- <h2>衍生模型每日下载</h2>
115
- <div id="dailyChart" class="chart"></div>
116
- </section>
117
- </div>
118
-
119
- <section class="card">
120
- <h2>全部衍生模型</h2>
121
- <input type="search" id="q" placeholder="搜索模型名" aria-label="搜索模型名">
122
- <div class="tablewrap"><table id="repoTable"></table></div>
123
- <button class="more" id="moreBtn" hidden>再显示 100 条</button>
124
- </section>
125
- </div>
126
-
127
- <script>
128
- const REL_NAME = {adapter: "适配器(LoRA 等)", finetune: "微调", quantized: "量化", repackage: "重打包", merge: "融合", mirror: "官方权重转存", component: "配套组件"};
129
- const HF_RELS = ["adapter", "finetune", "quantized", "merge"]; // the four kinds HF's Model tree has
130
- const css = n => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
131
- const fmt = n => n == null ? "–" : n >= 1e6 ? (n / 1e6).toFixed(n >= 1e7 ? 1 : 2).replace(/\.?0+$/, "") + "M" : n >= 1e4 ? (n / 1e3).toFixed(1).replace(/\.0$/, "") + "K" : n.toLocaleString("en-US");
132
- const full = n => n == null ? "–" : n.toLocaleString("en-US");
133
- const esc = s => String(s).replace(/[&<>"]/g, c => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;"}[c]));
134
- const FONT = 'system-ui, -apple-system, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif';
135
- let D, lineage, charts = {}, shown = 100, sortKey = "dlall", sortDir = -1, inited = false;
136
- let open = {}, trees = {};
137
-
138
- const relColor = rel => rel === "official" ? "var(--ink)" : `var(--s${D.rel_order.indexOf(rel) + 1})`;
139
- const L = () => D.lineages[lineage];
140
-
141
- fetch("data/index.json").then(r => r.json()).then(idx => {
142
- const sel = document.getElementById("famSel");
143
- sel.innerHTML = idx.families.map(f => `<option value="${f.key}">${esc(f.title)}</option>`).join("");
144
- sel.hidden = idx.families.length < 2;
145
- const want = location.hash.slice(1);
146
- sel.value = idx.families.some(f => f.key === want) ? want : idx.families[0].key;
147
- sel.onchange = () => { location.hash = sel.value; loadFamily(sel.value); };
148
- loadFamily(sel.value);
149
- });
150
-
151
- function loadFamily(key) {
152
- fetch(`data/${key}.json`).then(r => r.json()).then(d => {
153
- D = d; shown = 100; open = {}; trees = {};
154
- lineage = d.family.members[0].lineage;
155
- document.title = `${d.family.title}开源生态`;
156
- document.getElementById("title").textContent = `${d.family.title}开源生态`;
157
- const seg = document.getElementById("lineageSeg");
158
- seg.innerHTML = "";
159
- for (const m of d.family.members) {
160
- const b = document.createElement("button");
161
- b.textContent = m.base.split("/")[1]; b.dataset.k = m.lineage; b.setAttribute("aria-pressed", m.lineage === lineage);
162
- b.onclick = () => { lineage = m.lineage; shown = 100; open = {}; seg.querySelectorAll("button").forEach(x => x.setAttribute("aria-pressed", x.dataset.k === lineage)); render(); };
163
- seg.appendChild(b);
164
- }
165
- if (!inited) {
166
- inited = true;
167
- document.getElementById("q").addEventListener("input", () => { shown = 100; renderRepos(); });
168
- document.getElementById("moreBtn").onclick = () => { shown += 100; renderRepos(); };
169
- matchMedia("(prefers-color-scheme: dark)").addEventListener("change", renderCharts);
170
- new MutationObserver(renderCharts).observe(document.documentElement, {attributes: true, attributeFilter: ["data-theme"]});
171
- addEventListener("resize", () => Object.values(charts).forEach(c => c.resize()));
172
- }
173
- render();
174
- });
175
- }
176
-
177
- function render() { renderTiles(); renderTree(); renderRel(); renderCharts(); renderRepos(); }
178
- function renderCharts() { renderGrowth(); renderDaily(); }
179
-
180
- function renderTiles() {
181
- const l = L();
182
- const tiles = [["衍生模型", full(l.n_models)], ["衍生模型近 30 天下载", fmt(l.dl30)], ["衍生模型累计下载", fmt(l.dlall)]];
183
- document.getElementById("tiles").innerHTML = tiles.map(([k, v]) => `<div class="tile"><div class="label">${k}</div><div class="value">${v}</div></div>`).join("");
184
- }
185
-
186
- /* ---------- Model tree ---------- */
187
-
188
- function tree() {
189
- if (trees[lineage]) return trees[lineage];
190
- const l = L(), node = new Map();
191
- node.set(l.base, {id: l.base, rel: "official", dlall: l.official.dlall || 0, kids: []});
192
- const rows = D.repos.filter(r => r.lin === lineage);
193
- for (const r of rows) node.set(r.id, {id: r.id, rel: r.rel, dlall: r.dlall || 0, kids: []});
194
- for (const r of rows) (node.get(r.up) || node.get(l.base)).kids.push(node.get(r.id));
195
- const sub = n => n.sub ??= n.dlall + n.kids.reduce((a, k) => a + sub(k), 0);
196
- sub(node.get(l.base));
197
- for (const n of node.values()) n.kids.sort((a, b) => b.sub - a.sub || a.id.localeCompare(b.id));
198
- return trees[lineage] = node.get(l.base);
199
- }
200
-
201
- // How many children a node shows: the root its top 12, others their top 4 that have downloads.
202
- function nShown(n, depth) {
203
- if (open[n.id] != null) return open[n.id];
204
- return Math.min(depth === 0 ? 12 : 4, n.kids.filter(c => c.sub > 0).length);
205
- }
206
-
207
- const ROW = 38, RMAX = 13, PAD_LABEL = 10, NUM_DX = 10;
208
- const indent = () => innerWidth < 600 ? 28 : 46;
209
- let measureCtx;
210
- function textW(s, font) {
211
- measureCtx ||= document.createElement("canvas").getContext("2d");
212
- measureCtx.font = font;
213
- return measureCtx.measureText(s).width;
214
- }
215
-
216
- function renderTree() {
217
- const root = tree(), items = [];
218
- let row = 0;
219
- const maxDl = Math.max(1, root.dlall, ...root.kids.map(k => k.dlall), ...D.repos.filter(r => r.lin === lineage).map(r => r.dlall || 0));
220
- const rad = dl => 3.5 + (RMAX - 3.5) * Math.sqrt((dl || 0) / maxDl);
221
- // One row per node, children below their parent and indented one step: full names fit at
222
- // any depth and on a phone, and every link is a short elbow from parent to child.
223
- function walk(n, d) {
224
- const k = nShown(n, d), rest = n.kids.slice(k);
225
- const it = {n, d, kids: [], y: row++};
226
- items.push(it);
227
- for (const c of n.kids.slice(0, k)) it.kids.push(walk(c, d + 1));
228
- if (rest.length) {
229
- const f = {fold: true, n, d: d + 1, label: `其余 ${full(rest.length)} 个 · ${fmt(rest.reduce((a, c) => a + c.sub, 0))}`, kids: [], y: row++};
230
- items.push(f); it.kids.push(f);
231
- }
232
- return it;
233
- }
234
- walk(root, 0);
235
-
236
- const f15 = `15px ${FONT}`, fRoot = `650 16px ${FONT}`;
237
- for (const it of items) {
238
- if (it.fold) { it.w = textW(it.label, f15); continue; }
239
- it.num = fmt(it.n.dlall);
240
- it.w = textW(it.n.id, it.d === 0 ? fRoot : f15) + NUM_DX + textW(it.num, f15);
241
- }
242
- const INDENT = indent(), cx = d => 4 + RMAX + d * INDENT, lx = d => cx(d) + RMAX + PAD_LABEL;
243
- const Y = y => 6 + y * ROW + ROW / 2;
244
- const r = it => it.fold ? 5 : rad(it.n.dlall);
245
-
246
- let links = "", nodes = "";
247
- for (const it of items) {
248
- if (!it.kids.length) continue;
249
- const x = cx(it.d), last = it.kids.at(-1);
250
- links += `M${x},${Y(it.y) + r(it) + 2}V${Y(last.y)}`;
251
- for (const k of it.kids) links += `M${x},${Y(k.y)}H${cx(k.d) - r(k) - 3}`;
252
- }
253
- for (const it of items) {
254
- const y = Y(it.y), d = it.d;
255
- if (it.fold) {
256
- nodes += `<g class="fold" tabindex="0" role="button" data-id="${esc(it.n.id)}"><circle cx="${cx(d)}" cy="${y}" r="5"/><text x="${lx(d)}" y="${y}">${esc(it.label)}</text></g>`;
257
- continue;
258
- }
259
- const n = it.n;
260
- nodes += `<circle cx="${cx(d)}" cy="${y}" r="${rad(n.dlall).toFixed(1)}" style="fill:${relColor(n.rel)}"/>`
261
- + `<a href="https://huggingface.co/${esc(n.id)}" target="_blank" rel="noopener"><text x="${lx(d)}" y="${y}"${d === 0 ? ' class="root"' : ""}>`
262
- + `<tspan class="nm">${esc(n.id)}</tspan><tspan class="num" dx="${NUM_DX}">${it.num}</tspan></text></a>`;
263
- }
264
- const svg = document.getElementById("tree");
265
- const W = Math.ceil(Math.max(...items.map(i => lx(i.d) + i.w)) + 12), H = Math.ceil(Y(row - 1) + ROW / 2 + 6);
266
- svg.setAttribute("width", W); svg.setAttribute("height", H); svg.setAttribute("viewBox", `0 0 ${W} ${H}`);
267
- svg.innerHTML = `<path class="link" d="${links}"/>${nodes}`;
268
- svg.querySelectorAll(".fold").forEach(g => {
269
- const go = () => {
270
- const it = items.find(i => !i.fold && i.n.id === g.dataset.id);
271
- open[it.n.id] = nShown(it.n, it.d) + (it.d === 0 ? 20 : 10);
272
- renderTree();
273
- };
274
- g.onclick = go;
275
- g.onkeydown = e => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); go(); } };
276
- });
277
- const present = new Set(D.repos.filter(r => r.lin === lineage).map(r => r.rel));
278
- document.getElementById("treeLegend").innerHTML = D.rel_order.filter(r => present.has(r))
279
- .map(r => `<span><i style="background:${relColor(r)}"></i>${REL_NAME[r]}</span>`).join("");
280
- }
281
-
282
- /* ---------- tables ---------- */
283
-
284
- function renderRel() {
285
- const l = L(), b = l.by_relation, hf = l.hf_tree;
286
- const row = (name, n, h, d30, da, cls = "") => `<tr${cls ? ` class="${cls}"` : ""}><td>${name}</td><td class="num">${full(n)}</td><td class="num">${h == null ? "—" : full(h)}</td><td class="num">${full(d30)}</td><td class="num">${full(da)}</td></tr>`;
287
- const sum = (rels, k) => rels.reduce((a, r) => a + b[r][k], 0);
288
- const extra = D.rel_order.filter(r => !HF_RELS.includes(r));
289
- let h = `<thead><tr><th>关系</th><th class="num">识别到</th><th class="num">HF Model tree 显示</th><th class="num">近 30 天下载</th><th class="num">累计下载</th></tr></thead><tbody>`;
290
- for (const r of HF_RELS) h += row(REL_NAME[r], b[r].n, hf[r] || 0, b[r].dl30, b[r].dlall);
291
- h += row("小计", sum(HF_RELS, "n"), HF_RELS.reduce((a, r) => a + (hf[r] || 0), 0), sum(HF_RELS, "dl30"), sum(HF_RELS, "dlall"), "sum");
292
- for (const r of extra) h += row(REL_NAME[r], b[r].n, null, b[r].dl30, b[r].dlall);
293
- h += row("合计", l.n_models, null, l.dl30, l.dlall, "sum");
294
- document.getElementById("relTable").innerHTML = h + "</tbody>";
295
- }
296
-
297
- function renderRepos() {
298
- const q = document.getElementById("q").value.trim().toLowerCase();
299
- const rows = D.repos.filter(r => r.lin === lineage && (!q || r.id.toLowerCase().includes(q))).sort((a, b) => {
300
- const x = a[sortKey], y = b[sortKey];
301
- return (x == null) - (y == null) || (x < y ? -1 : x > y ? 1 : 0) * sortDir;
302
- });
303
- const cols = [["id", "模型"], ["rel", "关系"], ["dl30", "近 30 天下载", 1], ["dlall", "累计下载", 1], ...(D.snapshot_days.length > 1 ? [["d1", "最近一天", 1]] : [])];
304
- let h = "<thead><tr>" + cols.map(([k, n, num]) => `<th class="sortable${num ? " num" : ""}" data-k="${k}">${n}${sortKey === k ? (sortDir < 0 ? " ↓" : " ↑") : ""}</th>`).join("") + "</tr></thead><tbody>";
305
- for (const r of rows.slice(0, shown)) {
306
- h += `<tr><td class="repo"><a href="https://huggingface.co/${esc(r.id)}" target="_blank" rel="noopener">${esc(r.id)}</a></td><td style="white-space:nowrap">${REL_NAME[r.rel]}</td>`
307
- + `<td class="num">${full(r.dl30)}</td><td class="num">${full(r.dlall)}</td>${cols.length > 4 ? `<td class="num">${full(r.d1)}</td>` : ""}</tr>`;
308
- }
309
- const t = document.getElementById("repoTable");
310
- t.innerHTML = h + "</tbody>";
311
- t.querySelectorAll("th.sortable").forEach(th => th.onclick = () => { const k = th.dataset.k; sortDir = sortKey === k ? -sortDir : -1; sortKey = k; renderRepos(); });
312
- document.getElementById("moreBtn").hidden = rows.length <= shown;
313
- }
314
-
315
- /* ---------- charts ---------- */
316
-
317
- function chart(id) {
318
- if (charts[id]) { charts[id].dispose(); delete charts[id]; }
319
- return charts[id] = echarts.init(document.getElementById(id), null, {renderer: "svg"});
320
- }
321
-
322
- function bars(id, xs, ys, tip) {
323
- chart(id).setOption({
324
- animation: false, textStyle: {fontFamily: FONT},
325
- grid: {left: 8, right: 16, top: 14, bottom: 4, containLabel: true},
326
- tooltip: {trigger: "axis", axisPointer: {type: "shadow", shadowStyle: {color: css("--wash")}},
327
- backgroundColor: css("--surface"), borderColor: css("--ring"), textStyle: {color: css("--ink"), fontSize: 15},
328
- formatter: p => tip(p[0].dataIndex)},
329
- xAxis: {type: "category", data: xs, axisLine: {lineStyle: {color: css("--axis")}}, axisTick: {show: false}, axisLabel: {color: css("--ink2"), fontSize: 14}},
330
- yAxis: {type: "value", splitLine: {lineStyle: {color: css("--grid")}}, axisLabel: {color: css("--ink2"), fontSize: 14, formatter: v => fmt(v)}},
331
- series: [{type: "bar", data: ys, barMaxWidth: 22, itemStyle: {color: css("--bar"), borderRadius: [4, 4, 0, 0]}, emphasis: {disabled: true}}],
332
- });
333
- }
334
-
335
- function renderGrowth() {
336
- const wk = s => { const d = new Date(s + "T00:00:00Z"); d.setUTCDate(d.getUTCDate() - (d.getUTCDay() + 6) % 7); return d.toISOString().slice(0, 10); };
337
- const weeks = {};
338
- for (const g of L().growth) weeks[wk(g.date)] = (weeks[wk(g.date)] || 0) + g.n;
339
- const keys = Object.keys(weeks).sort(), xs = [];
340
- // Only finished weeks: the current one would show as a drop.
341
- const end = new Date(wk(D.today) + "T00:00:00Z");
342
- if (keys.length) for (let d = new Date(keys[0] + "T00:00:00Z"); d < end; d.setUTCDate(d.getUTCDate() + 7)) xs.push(d.toISOString().slice(0, 10));
343
- const ys = xs.map(w => weeks[w] || 0);
344
- bars("growthChart", xs.map(x => x.slice(5)), ys, i => `${xs[i]} 起一周:新增 ${full(ys[i])} 个`);
345
- }
346
-
347
- function renderDaily() {
348
- const daily = L().daily, card = document.getElementById("dailyCard");
349
- card.hidden = daily.length === 0;
350
- document.getElementById("chartRow").classList.toggle("one", card.hidden);
351
- if (card.hidden) { if (charts.dailyChart) { charts.dailyChart.dispose(); delete charts.dailyChart; } return; }
352
- bars("dailyChart", daily.map(r => r.day.slice(5)), daily.map(r => r.n), i => `${daily[i].day}:${full(daily[i].n)} 次下载`);
353
- if (charts.growthChart) charts.growthChart.resize();
354
- }
355
- </script>
356
- </body>
357
- </html>