#!/usr/bin/env python3 """ Scrape HuggingFace Hub for transformers-compatible models, fetch tokenizer.json for each (streaming only pre_tokenizer + normalizer, not the vocab), dump to JSONL. Uses cached HF token for higher rate limits. """ import json, os, sys, time, urllib.request, urllib.error, concurrent.futures, threading from collections import Counter BASE = "https://huggingface.co/api/models" RESOLVE = "https://huggingface.co/{mid}/resolve/main/tokenizer.json" OUT = os.path.join(os.path.dirname(__file__), "scrape_hf.jsonl") MODELS_OUT = os.path.join(os.path.dirname(__file__), "model_list.json") TARGET = 10000 MAX_WORKERS = 40 TIMEOUT = 15 # Load HF token from cache for auth def get_hf_token(): tok_path = os.path.expanduser("~/.cache/huggingface/token") try: with open(tok_path) as f: return f.read().strip() except: return None HF_TOKEN = get_hf_token() def api_headers(): h = {"User-Agent": "hf-scrape/1.0"} if HF_TOKEN: h["Authorization"] = f"Bearer {HF_TOKEN}" return h # ── streaming pre_tokenizer extractor ────────────────────────────────────────── def find_key_value(buf, key): needle = b'"' + key.encode() + b'"' idx = buf.find(needle) if idx == -1: return "NOT_FOUND", -1 i = idx + len(needle) while i < len(buf) and buf[i:i+1] in (b' ', b'\t', b'\n', b'\r', b':'): i += 1 if i >= len(buf): return "INCOMPLETE", idx start = i b0 = buf[i] if b0 in (0x6E, 0x74, 0x66): # null/true/false j = i while j < len(buf) and buf[j] not in (b',', b'}', b']', 0x20, 0x09, 0x0A, 0x0D): j += 1 if j < len(buf): return buf[start:j].decode('utf-8', errors='replace'), j return "INCOMPLETE", idx if b0 == 0x22: # string j = i + 1 esc = False while j < len(buf): if esc: esc = False elif buf[j] == 0x5C: esc = True elif buf[j] == 0x22: return buf[start:j+1].decode('utf-8', errors='replace'), j+1 j += 1 return "INCOMPLETE", idx if (0x30 <= b0 <= 0x39) or b0 == 0x2D: # number j = i while j < len(buf) and buf[j] not in (b',', b'}', b']', 0x20, 0x09, 0x0A, 0x0D): j += 1 if j < len(buf): return buf[start:j].decode('utf-8', errors='replace'), j return "INCOMPLETE", idx # object/array -- brace-match depth = 0 in_str = False esc = False while i < len(buf): b = buf[i] if in_str: if esc: esc = False elif b == 0x5C: esc = True elif b == 0x22: in_str = False else: if b == 0x22: in_str = True elif b in (0x7B, 0x5B): depth += 1 elif b in (0x7D, 0x5D): depth -= 1 if depth == 0: return buf[start:i+1].decode('utf-8', errors='replace'), i+1 i += 1 return "INCOMPLETE", idx def stream_pre_tokenizer(url, timeout=TIMEOUT, max_bytes=3_000_000): req = urllib.request.Request(url, headers={"User-Agent": "hf-scrape/1.0"}) out = {} for attempt in range(3): try: resp = urllib.request.urlopen(req, timeout=timeout) buf = b"" have = set() wanted = {"pre_tokenizer", "normalizer"} try: while True: chunk = resp.read(65536) if not chunk: break buf += chunk for key in wanted: if key not in have: val, _ = find_key_value(buf, key) if val == "NOT_FOUND": continue if val == "INCOMPLETE": continue try: out[key] = json.loads(val) if val != "null" else None have.add(key) except: pass if have == wanted: break if b'"model"' in buf and have: for key in wanted: if key not in have: out[key] = None have.add(key) break if len(buf) > max_bytes: break finally: resp.close() break except urllib.error.HTTPError as e: if e.code == 429 and attempt < 2: time.sleep(3 * (attempt+1)) continue out["error"] = f"HTTP {e.code}" break except Exception as e: out["error"] = str(e)[:200] break return out # ── model list scraping ──────────────────────────────────────────────────────── def fetch_model_list(target): models = [] seen = set() offset = 0 limit = 500 # larger pages with auth url_base = f"{BASE}?library=transformers&sort=downloads&direction=-1&limit={limit}" print(f"Fetching model list with AUTH (target={target})...", flush=True) consecutive_fails = 0 while len(models) < target: page_url = f"{url_base}&offset={offset}" batch = [] got = False for attempt in range(5): try: req = urllib.request.Request(page_url, headers=api_headers()) with urllib.request.urlopen(req, timeout=30) as resp: batch = json.loads(resp.read()) got = True break except urllib.error.HTTPError as e: if e.code == 429: wait = min(60, 5 * (attempt+1)) print(f" 429 at offset={offset}, waiting {wait}s", flush=True) time.sleep(wait) continue print(f" HTTP {e.code} at offset={offset}", flush=True) break except Exception as e: if attempt < 4: time.sleep(2 * (attempt+1)) continue print(f" FAILED offset={offset}: {e}", flush=True) break if not got or not batch: consecutive_fails += 1 if consecutive_fails >= 3: print(f" 3 consecutive fails, stopping", flush=True) break offset += limit continue consecutive_fails = 0 for m in batch: mid = m["id"] if isinstance(m, dict) else m if mid in seen: continue seen.add(mid) models.append({ "id": mid, "downloads": m.get("downloads", 0) if isinstance(m, dict) else 0, "likes": m.get("likes", 0) if isinstance(m, dict) else 0, }) if len(models) >= target: break offset += limit if len(models) >= target or offset % 5000 == 0: print(f" fetched {len(models)} models (offset={offset})", flush=True) time.sleep(0.05) return models[:target] # ── main ─────────────────────────────────────────────────────────────────────── def main(): t0 = time.time() models = fetch_model_list(TARGET) print(f"\nGot {len(models)} model IDs in {time.time()-t0:.1f}s", flush=True) with open(MODELS_OUT, "w") as f: json.dump(models, f) total = len(models) results = [] done = [0] lock = threading.Lock() def fetch_one(m): url = RESOLVE.format(mid=m["id"]) out = stream_pre_tokenizer(url) rec = { "id": m["id"], "downloads": m.get("downloads", 0), "likes": m.get("likes", 0), "pre_tokenizer": out.get("pre_tokenizer"), "normalizer": out.get("normalizer"), "error": out.get("error"), } with lock: done[0] += 1 if done[0] % 500 == 0: print(f" progress: {done[0]}/{total}", flush=True) return rec print(f"\nFetching tokenizer.json for {total} models with {MAX_WORKERS} workers...", flush=True) with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as ex: futures = {ex.submit(fetch_one, m): m for m in models} for f in concurrent.futures.as_completed(futures): try: results.append(f.result()) except Exception as e: m = futures[f] results.append({"id": m["id"], "error": str(e)[:200]}) # Sort by downloads desc results.sort(key=lambda r: r.get("downloads", 0), reverse=True) with open(OUT, "w") as f: for r in results: f.write(json.dumps(r, ensure_ascii=False) + "\n") elapsed = time.time() - t0 ok = sum(1 for r in results if r.get("pre_tokenizer") is not None) null_pt = sum(1 for r in results if r.get("pre_tokenizer") is None and not r.get("error")) err = sum(1 for r in results if r.get("error")) err404 = sum(1 for r in results if r.get("error") == "HTTP 404") err401 = sum(1 for r in results if r.get("error") == "HTTP 401") print(f"\n=== DONE in {elapsed:.1f}s ===", flush=True) print(f" models listed: {len(models)}", flush=True) print(f" had tokenizer.json (no 404): {len(results) - err404}", flush=True) print(f" 404 (no tokenizer.json): {err404}", flush=True) print(f" 401 (gated): {err401}", flush=True) print(f" pre_tokenizer != None: {ok}", flush=True) print(f" pre_tokenizer == null: {null_pt}", flush=True) print(f" output: {OUT}", flush=True) if __name__ == "__main__": main()