File size: 5,658 Bytes
a709b7a | 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 | """Verify scripts/catalogue.yaml against the live Hub and write app/data/catalogue.json.
A model passes only if its own licence AND every base_model up the chain is OSI. A dataset passes on
OSI or open-data licences and must not be gated. GGUF builds (for Ollama) are found and gated too.
"""
from __future__ import annotations
import json, sys, time
from pathlib import Path
import yaml
from huggingface_hub import HfApi
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "app"))
from draiml.licences import is_open_dataset, is_open_model, licence_of # noqa: E402
api = HfApi()
_cache: dict[str, object] = {}
def info(mid):
if mid not in _cache:
try:
_cache[mid] = api.model_info(mid, expand=["cardData", "tags", "pipeline_tag", "downloads", "likes",
"gated", "inferenceProviderMapping", "safetensors"])
except Exception as e: # noqa: BLE001
_cache[mid] = e
return _cache[mid]
def bases(m) -> list[str]:
cd = m.card_data.to_dict() if m.card_data else {}
b = cd.get("base_model") or []
if isinstance(b, str):
b = [b]
if not b:
b = [t.split(":", 2)[-1] for t in (m.tags or []) if t.startswith("base_model:") and t.count(":") == 2
and not t.startswith(("base_model:quantized:", "base_model:finetune:", "base_model:adapter:", "base_model:merge:"))]
return [x for x in b if isinstance(x, str)]
def chain_ok(mid, depth=0, seen=None) -> tuple[bool, str]:
seen = seen or set()
if mid in seen or depth > 6:
return True, ""
seen.add(mid)
m = info(mid)
if isinstance(m, Exception):
return (depth > 0), f"{mid}: {type(m).__name__}" # an unreachable base is not proof of closure
ok, lic = is_open_model(m)
if not ok:
return False, f"{mid} is {lic!r}"
for b in bases(m):
ok, why = chain_ok(b, depth + 1, seen)
if not ok:
return False, why
return True, ""
def gguf_for(mid) -> str | None:
name = mid.split("/", 1)[1]
for m in api.list_models(search=f"{name}", sort="downloads", limit=30, expand=["cardData", "tags"]):
if "gguf" not in (m.tags or []) or "abliterated" in m.id.lower() or "uncensored" in m.id.lower():
continue
if not m.id.lower().split("/", 1)[1].startswith(name.lower()) and name.lower() not in m.id.lower():
continue
if is_open_model(m)[0]:
return m.id
return None
def main():
src = yaml.safe_load((ROOT / "scripts" / "catalogue.yaml").read_text())
out = {"version": "2.0.0", "built": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "models": [], "datasets": []}
for e in src["models"]:
m = info(e["id"])
if isinstance(m, Exception):
print(f"DROP model {e['id']}: {m}")
continue
ok, why = chain_ok(e["id"])
if not ok:
print(f"DROP model {e['id']}: licence gate — {why}")
continue
if m.gated:
print(f"DROP model {e['id']}: gated")
continue
providers = sorted({p.provider for p in (m.inference_provider_mapping or []) if getattr(p, "status", "live") == "live"})
params = None
if m.safetensors and getattr(m.safetensors, "total", None):
params = round(m.safetensors.total / 1e9, 1)
entry = {**e, "licence": licence_of(m), "pipeline": m.pipeline_tag, "downloads": m.downloads,
"likes": m.likes, "params_b": params, "bases": bases(m), "providers": providers}
if e["role"] in ("specialist", "vision"):
entry["gguf"] = gguf_for(e["id"])
out["models"].append(entry)
print(f"ok model {e['id']} [{entry['licence']}] gguf={entry.get('gguf')}")
for e in src["datasets"]:
try:
d = api.dataset_info(e["id"])
except Exception as ex: # noqa: BLE001
print(f"DROP dataset {e['id']}: {ex}")
continue
ok, lic = is_open_dataset(d)
if not ok or d.gated:
print(f"DROP dataset {e['id']}: licence {lic!r} gated={d.gated}")
continue
cd = d.card_data.to_dict() if d.card_data else {}
out["datasets"].append({**e, "licence": lic, "downloads": d.downloads, "likes": d.likes,
"size": (cd.get("size_categories") or [None])[0], "pretty": cd.get("pretty_name")})
print(f"ok dataset {e['id']} [{lic}]")
# every model the HF router serves right now, through the same gate (the app re-checks live)
import json as _j, urllib.request as _u
router = _j.load(_u.urlopen("https://router.huggingface.co/v1/models", timeout=60))["data"]
out["router_open"], out["router_closed"] = {}, {}
for m in router:
ok, why = chain_ok(m["id"])
provs = [p["provider"] for p in m.get("providers", []) if p.get("status") == "live"]
if ok:
out["router_open"][m["id"]] = {"licence": licence_of(info(m["id"])) if not isinstance(info(m["id"]), Exception) else None,
"providers": provs,
"vision": "image" in (m.get("architecture") or {}).get("input_modalities", [])}
else:
out["router_closed"][m["id"]] = why
print(f"router: {len(out['router_open'])} open, {len(out['router_closed'])} rejected")
p = ROOT / "app" / "data" / "catalogue.json"
p.write_text(json.dumps(out, indent=1))
print(f"wrote {p} — {len(out['models'])} models, {len(out['datasets'])} datasets")
if __name__ == "__main__":
main()
|