"""Octo-patch scenario "hf-basemodel": add or fix base_model metadata on Hugging Face. Three commands, mirroring Octo-patch's scan / patch / follow modes: candidates read the classifier's labels and print the rows that would go into the Repo table (one per repo, reason code hf-base-model-add / -fix / -relation) patch open a PR that only edits the model card's YAML header (dry run by default; --submit to actually open it) follow report the state of PRs this account opened (open / merged / closed + new comments) The PR is a pure metadata change, so no clone, build or test is needed: the script reads the current card header, computes the new header, shows the diff, and on --submit calls huggingface_hub.metadata_update(create_pr=True). Main is never touched. """ import argparse import json import sys from pathlib import Path import pandas as pd import yaml from huggingface_hub import HfApi, hf_hub_download, metadata_update from huggingface_hub.utils import EntryNotFoundError ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT)) from hfeco import families, store # noqa: E402 api = HfApi() REASON = {"missing": "hf-base-model-add", "wrong_base": "hf-base-model-fix", "wrong_relation": "hf-base-model-relation"} # Plain English for the PR body, keyed by a fragment of the classifier's evidence text. WHY = [ ("逐字节相同", "the weight files are byte-identical to the official {base} files"), ("音频分支", "the weights contain the audio branch (audio_patch_proj / audio_out) that only {base} has"), ("PDD", "the weights contain the PDD heads that only {base} has"), ("数值与官方", "a slice of the transformer weights is identical to the official {base} checkpoint"), ("数值最接近", "a slice of the transformer weights is closest to {base}, so it was trained from it"), ("训练信息写明", "the safetensors training metadata names {base} as the base"), ("model_index.json", "model_index.json uses the {base} pipeline"), ("文本大模型", "it is the {base} prompt-expansion model"), ] def candidates(fam, min_downloads, limit, include_relation=False): lab = pd.read_parquet(store.LOCAL / "labels" / fam.key / "latest.parquet") raw_all = store.read_raw(fam.key) raw_all = raw_all[raw_all.day == raw_all.day.max()] raw = raw_all[["repo_id", "downloads_all_time", "downloads_30d", "gated"]] df = lab.merge(raw, on="repo_id") df["flags"] = df["flags"].apply(json.loads) df["evidence"] = df.evidence.apply(json.loads) keep = df[(df.kind == "model") & df.lineage.isin([m.lineage for m in fam.tracked]) & df.declared_status.isin(list(REASON)) & (df.confidence == "high") & ~df["flags"].apply(lambda f: "nsfw" in f or "copy" in f) & (df.downloads_all_time.fillna(0) >= min_downloads) & (df.gated == "False")] if not include_relation: keep = keep[keep.declared_status != "wrong_relation"] # A repo that already declares a community parent is fixed at the root of its chain, not here: # adding the official base next to the parent would read as a merge on the Hub. upstream = _member_upstreams(fam) keep = keep[keep.repo_id.apply(lambda rid: not _declares_other_parent(rid, raw_all, fam, upstream))] keep = keep.sort_values("downloads_30d", ascending=False).head(limit) rows = [] for r in keep.itertuples(): rows.append({"repo_url": f"https://huggingface.co/{r.repo_id}", "repo_id": r.repo_id, "reason": REASON[r.declared_status], "status": "candidate", "proposed_base_model": r.proposed_base_model, "proposed_relation": r.proposed_relation, "lineage": r.lineage, "relation": r.relation, "downloads_30d": int(r.downloads_30d or 0), "evidence": r.evidence}) return rows def _member_upstreams(fam): """Repos the official members themselves declare as base (e.g. Qwen for the PE).""" out = set() for m in fam.members: try: card = api.model_info(m.base).card_data except Exception: continue up = (card.to_dict() if card else {}).get("base_model") out |= {up} if isinstance(up, str) else set(up or []) return out def _declares_other_parent(rid, raw_all, fam, upstream): row = raw_all[(raw_all.repo_id == rid) & (raw_all.kind == "model")] if row.empty: return False declared = set(row.iloc[0].card_base_model) | {p.split(":", 1)[1] for p in row.iloc[0].hf_parents} return bool(declared - set(fam.bases) - upstream) def current_meta(repo): try: text = Path(hf_hub_download(repo, "README.md", force_download=True)).read_text() except EntryNotFoundError: return {}, "" if text.startswith("---"): end = text.find("\n---", 3) return (yaml.safe_load(text[3:end]) or {}), text return {}, text def plan(repo, base, relation, fam): """New base_model / base_model_relation values, keeping unrelated parents.""" meta, _ = current_meta(repo) old = meta.get("base_model") old_list = [old] if isinstance(old, str) else list(old or []) family_bases = set(fam.bases) # Drop parents that point at the wrong family member or at the text model's own # upstream (e.g. Qwen for a PE re-upload); keep community parents such as LoRAs. keep = [b for b in old_list if b not in family_bases and not _is_upstream_of_member(b, fam)] new_list = [base] + keep new = {"base_model": new_list[0] if len(new_list) == 1 else new_list} if relation: new["base_model_relation"] = relation changed = {k: v for k, v in new.items() if meta.get(k) != v} return meta, changed def _is_upstream_of_member(b, fam): for m in fam.members: try: card = api.model_info(m.base).card_data except Exception: continue up = (card.to_dict() if card else {}).get("base_model") if b == up or (isinstance(up, list) and b in up): return True return False def body(row): base = row["proposed_base_model"] why = [] for frag, en in WHY: if any(frag in e for e in row["evidence"]): why.append(en.format(base=base)) rel = f" and `base_model_relation: {row['proposed_relation']}`" if row["proposed_relation"] else "" lines = [f"This PR sets `base_model: {base}`{rel} in the model card metadata, so this repo shows up in " f"the model tree of [{base}](https://huggingface.co/{base}) and people can find it from there.", ""] if why: lines += ["Why we think it is based on " + base.split("/")[1] + ": " + "; ".join(why[:2]) + ".", ""] lines += ["Only the YAML header changes; the card text is untouched. Feel free to close this if it is not right."] return "\n".join(lines) def patch(row, fam, submit): meta, changed = plan(row["repo_id"], row["proposed_base_model"], row["proposed_relation"], fam) print(f"== {row['repo_id']} ({row['reason']})") print(" now:", {k: meta.get(k) for k in ("base_model", "base_model_relation")}) print(" new:", changed or "(nothing to change)") if not changed: return None title = "Add base_model metadata" if row["reason"] == "hf-base-model-add" else "Fix base_model metadata" if not submit: print(" title:", title) print(" body:\n " + body(row).replace("\n", "\n ")) return None commit = metadata_update(row["repo_id"], changed, overwrite=True, create_pr=True, commit_message=title, commit_description=body(row)) pr = next(d for d in api.get_repo_discussions(row["repo_id"], author=api.whoami()["name"], discussion_type="pull_request") if d.title == title) url = f"https://huggingface.co/{row['repo_id']}/discussions/{pr.num}" print(" opened:", url, commit) return url def follow(repo): me = api.whoami()["name"] for d in api.get_repo_discussions(repo, author=me, discussion_type="pull_request"): det = api.get_discussion_details(repo, d.num) others = [e for e in det.events if e.type == "comment" and e.author != me] print(json.dumps({"repo_id": repo, "pr": d.num, "status": d.status, # open | merged | closed | draft "url": f"https://huggingface.co/{repo}/discussions/{d.num}", "comments_from_others": [{"author": e.author, "text": e.content[:500]} for e in others]}, ensure_ascii=False)) if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("cmd", choices=["candidates", "patch", "follow"]) ap.add_argument("--family", default="h3") ap.add_argument("--min-downloads", type=int, default=100) ap.add_argument("--limit", type=int, default=20) ap.add_argument("--repo", help="patch/follow one repo (patch takes --base/--relation for a manual row)") ap.add_argument("--base") ap.add_argument("--relation") ap.add_argument("--submit", action="store_true", help="actually open the PR (default: dry run)") ap.add_argument("--include-relation", action="store_true", help="also propose base_model_relation fixes (off by default: authors chose them on purpose)") a = ap.parse_args() fam = families.get(a.family) if a.cmd == "candidates": print(json.dumps(candidates(fam, a.min_downloads, a.limit, a.include_relation), ensure_ascii=False, indent=1)) elif a.cmd == "patch": if a.repo and a.base: # a hand-written row, e.g. for testing on a sandbox repo rows = [{"repo_id": a.repo, "reason": "hf-base-model-fix", "proposed_base_model": a.base, "proposed_relation": a.relation, "evidence": []}] else: rows = candidates(fam, a.min_downloads, 10_000, a.include_relation) rows = [r for r in rows if not a.repo or r["repo_id"] == a.repo] for r in rows[:a.limit]: patch(r, fam, a.submit) else: follow(a.repo)