"""Collect per-repo evidence for classification without downloading weights. Everything here is read through small requests: the file list (with LFS sha256), safetensors / GGUF headers via HTTP Range, a few hundred values of one tensor, model_index.json and the README. Results are cached by repo sha. """ import json import re import struct import numpy as np import requests from huggingface_hub import get_token, hf_hub_url from . import hub def is_weight(name): """A weight file, also one split into byte parts for the upload limit (x.gguf.part1of3).""" return re.sub(r"\.part\d+of\d+$", "", name.lower()).endswith(WEIGHT_EXT) WEIGHT_EXT = (".safetensors", ".gguf", ".bin", ".pt", ".pth", ".ckpt", ".onnx", ".npz", ".sft", ".tflite", ".mlmodel", ".engine", ".pte") MEDIA_VIDEO = (".mp4", ".webm", ".mov", ".gif", ".mkv") MEDIA_IMAGE = (".png", ".jpg", ".jpeg", ".webp") README_MAX = 12_000 _S = requests.Session() def _auth(): t = get_token() return {"Authorization": f"Bearer {t}"} if t else {} def _range(repo, fname, start, end, kind="model", revision=None): url = hf_hub_url(repo, fname, repo_type=None if kind == "model" else kind, revision=revision) r = hub.retry(_S.get, url, headers={**_auth(), "Range": f"bytes={start}-{end}"}, timeout=60) r.raise_for_status() return r.content def st_header(repo, fname, revision=None): n = struct.unpack(" 50_000_000: raise ValueError("header too large") h = json.loads(_range(repo, fname, 8, 8 + n - 1, revision=revision)) return n, h _DT = {"BF16": ("bf16", 2), "F16": (np.float16, 2), "F32": (np.float32, 4)} def st_values(repo, fname, n_header, info, count=256, revision=None): dt = info["dtype"] if dt not in _DT: return None kind, size = _DT[dt] start = 8 + n_header + info["data_offsets"][0] raw = _range(repo, fname, start, start + count * size - 1, revision=revision) if kind == "bf16": u = np.frombuffer(raw, dtype=np.uint16).astype(np.uint32) << 16 return u.view(np.float32) return np.frombuffer(raw, dtype=kind).astype(np.float32) def gguf_header(repo, fname, limit=8_000_000): """Parse GGUF metadata + tensor names from the first `limit` bytes (best effort).""" buf = _range(repo, fname, 0, limit - 1) if buf[:4] != b"GGUF": return None p = 4 ver, = struct.unpack_from("