ArthurZ HF Staff commited on
Commit
59913a3
Β·
verified Β·
1 Parent(s): ca9ec80

Upload folder using huggingface_hub

Browse files
scrape_analysis/analyze.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Analyze scraped tokenizer.json pre_tokenizers and classify each against the
4
+ PR's atom FSM shapes. Report which patterns are covered and which need hand-unroll.
5
+
6
+ PR atom FSM shapes (from fast_split/src/fsm.rs + TAG_CLASSIFY_SPEC.md):
7
+ A1. fsm_split<DELIM,BEHAVIOR> β€” Split delimiter (Removed/Isolated/Contiguous/MergedPrev/MergedNext)
8
+ covers: WhitespaceSplit, Punctuation, Digits, Metaspace, CharDelimiterSplit, Split-literal
9
+ A2. fsm_class_runs<DROP,ISOLATE,SPLIT> β€” class-change cut
10
+ covers: Whitespace, Bert
11
+ A3. fsm_cl100k β€” cl100k/o200k 7-rule scalar FSM
12
+ A4. fsm_deepseek β€” deepseek-v3 Sequence (digits{1,3} β†’ CJK β†’ big regex)
13
+ A5. fsm_byte_level β€” GPT-2/ByteLevel (TODO in PR)
14
+ A6. fsm_script_run β€” UnicodeScripts (TODO in PR)
15
+ OUT. Split(regex) β€” runtime regex, feature-gated escape hatch (NOT an atom)
16
+ """
17
+ import json, os, re, sys
18
+ from collections import Counter, defaultdict
19
+
20
+ IN = os.path.join(os.path.dirname(__file__), "scrape_hf.jsonl")
21
+
22
+ # ── Canonical regex patterns we recognize ──────────────────────────────────────
23
+ # cl100k_base / o200k_base (GPT-4 / GPT-4o) pretokenizer regex:
24
+ CL100K_REGEX = r"""'(?i:[sdmt]|ll|ve|re)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
25
+ O200K_REGEX = r"""[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\p{Lu}[\p{Lm}\p{Lo}\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
26
+ # GPT-2 / ByteLevel regex (use_regex=true):
27
+ GPT2_REGEX = r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"""
28
+ # Deepseek-v3 big-regex alt-3:
29
+ DS_BIGREGEX = r"""[!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~][A-Za-z]+|[^\r\n\p{L}\p{P}\p{S}]?[\p{L}\p{M}]+| ?[\p{P}\p{S}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
30
+ # Qwen / Llama3 / Mistral-style Split regex (the common "ByteLevel with regex" split):
31
+ # This is the GPT-2-like regex but with \p{N}{1,2} or \p{N}{1,3} variations:
32
+ LLAMA3_REGEX = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
33
+
34
+ def normalize_regex(r):
35
+ """Normalize a regex string for comparison (strip whitespace, collapse)."""
36
+ if r is None:
37
+ return None
38
+ r = r.strip()
39
+ # collapse internal whitespace
40
+ r = re.sub(r'\s+', '', r)
41
+ return r
42
+
43
+ # Pre-compute normalized known regexes
44
+ KNOWN = {
45
+ "cl100k": normalize_regex(CL100K_REGEX),
46
+ "o200k": normalize_regex(O200K_REGEX),
47
+ "gpt2": normalize_regex(GPT2_REGEX),
48
+ "deepseek_big": normalize_regex(DS_BIGREGEX),
49
+ "llama3": normalize_regex(LLAMA3_REGEX),
50
+ }
51
+
52
+ # ── Classification ─────────────────────────────────────────────────────────────
53
+
54
+ def classify_pre_tokenizer(pt, norm=None):
55
+ """
56
+ Classify a pre_tokenizer JSON object.
57
+ Returns (atom_shape, canonical_signature, details).
58
+ atom_shape is one of:
59
+ 'A1_split', 'A2_class_runs', 'A3_cl100k', 'A4_deepseek', 'A5_byte_level',
60
+ 'A6_script_run', 'A1_split_regex', 'SEQUENCE', 'null', 'UNKNOWN'
61
+ canonical_signature: a string that uniquely identifies the pre_tokenizer pattern.
62
+ """
63
+ if pt is None:
64
+ return ("null", "null", "no pre_tokenizer (SentencePiece or raw)")
65
+ t = pt.get("type")
66
+ sig_parts = []
67
+ if t == "Sequence":
68
+ subs = pt.get("pretokenizers", [])
69
+ sub_results = []
70
+ for s in subs:
71
+ sub_atom, sub_sig, sub_det = classify_pre_tokenizer(s)
72
+ sub_results.append((sub_atom, sub_sig, s.get("type")))
73
+ # Classify the whole sequence
74
+ sub_types = [s.get("type") for s in subs]
75
+ sub_atoms = [r[0] for r in sub_results]
76
+ sub_sigs = [r[1] for r in sub_results]
77
+ sig = "Seq[" + ",".join(sub_sigs) + "]"
78
+ # Heuristics for known sequences
79
+ # Deepseek: [Split(N{1,3}), Split(CJK), Split(bigregex), ByteLevel]
80
+ if len(subs) == 4 and sub_types == ["Split","Split","Split","ByteLevel"]:
81
+ r0 = subs[0].get("pattern",{}).get("Regex","")
82
+ r1 = subs[1].get("pattern",{}).get("Regex","")
83
+ r2 = subs[2].get("pattern",{}).get("Regex","")
84
+ if "N}" in r0 and ("4e00" in r1.lower() or "\\u4e00" in r1) and "p{P}" in r2:
85
+ return ("A4_deepseek", sig, "deepseek-v3 Sequence")
86
+ # Check if r2 is the deepseek big regex
87
+ nr2 = normalize_regex(r2)
88
+ if nr2 == KNOWN["deepseek_big"]:
89
+ return ("A4_deepseek", sig, "deepseek-v3 Sequence (big regex match)")
90
+ # Llama3/Qwen/Mistral: [Split(cl100k-like regex), ByteLevel]
91
+ if len(subs) == 2 and sub_types == ["Split","ByteLevel"]:
92
+ r0 = subs[0].get("pattern",{}).get("Regex","")
93
+ nr0 = normalize_regex(r0)
94
+ if nr0 == KNOWN["cl100k"] or nr0 == KNOWN["llama3"]:
95
+ return ("A5_byte_level", sig, "ByteLevel + cl100k-regex Split (llama3/qwen pattern)")
96
+ # generic regex + bytelevel
97
+ return ("A5_byte_level", sig, f"ByteLevel + Split(regex {r0[:40]}...)")
98
+ # XLM-R: [WhitespaceSplit, Metaspace]
99
+ if len(subs) == 2 and sub_types == ["WhitespaceSplit","Metaspace"]:
100
+ return ("A1_split", sig, "WhitespaceSplit + Metaspace (A1 Γ—2)")
101
+ # Sequence of all A1-compatible splits
102
+ if all(a in ("A1_split","A1_split_regex") for a in sub_atoms):
103
+ if all(a == "A1_split" for a in sub_atoms):
104
+ return ("A1_split", sig, "Sequence of A1-compatible splits")
105
+ return ("A1_split_regex", sig, "Sequence with regex Split(s)")
106
+ # Mixed
107
+ return ("SEQUENCE", sig, f"Seq types={sub_types} atoms={sub_atoms}")
108
+ elif t == "WhitespaceSplit":
109
+ return ("A1_split", "WhitespaceSplit", "fsm_split<WS, Removed>")
110
+ elif t == "Whitespace":
111
+ return ("A2_class_runs", "Whitespace", "fsm_class_runs<WS,0,WORD>")
112
+ elif t == "BertPreTokenizer":
113
+ return ("A2_class_runs", "BertPreTokenizer", "fsm_class_runs<WS,PUNCT,0>")
114
+ elif t == "Punctuation":
115
+ return ("A1_split", "Punctuation", "fsm_split<PUNCT, Isolated>")
116
+ elif t == "Digits":
117
+ beh = pt.get("behavior", "Contiguous")
118
+ return ("A1_split", f"Digits({beh})", f"fsm_split<NUMERIC, {beh}>")
119
+ elif t == "Metaspace":
120
+ return ("A1_split", "Metaspace", "fsm_split<Space→▁, MergedWithNext>")
121
+ elif t == "ByteLevel":
122
+ ur = pt.get("use_regex", False)
123
+ if ur:
124
+ return ("A5_byte_level", "ByteLevel(use_regex=true)", "fsm_byte_level (GPT-2 regex)")
125
+ else:
126
+ return ("A5_byte_level", "ByteLevel(use_regex=false)", "fsm_byte_level (no regex)")
127
+ elif t == "Split":
128
+ pat = pt.get("pattern", {})
129
+ beh = pt.get("behavior", "?")
130
+ inv = pt.get("invert", False)
131
+ pat_kind = list(pat.keys())[0] if pat else "none"
132
+ pat_val = list(pat.values())[0] if pat else ""
133
+ if pat_kind == "Regex":
134
+ nr = normalize_regex(pat_val)
135
+ if nr == KNOWN["cl100k"]:
136
+ return ("A3_cl100k", f"Split(cl100k:{beh})", "cl100k regex Split")
137
+ if nr == KNOWN["o200k"]:
138
+ return ("A3_cl100k", f"Split(o200k:{beh})", "o200k regex Split (A3 variant)")
139
+ if nr == KNOWN["gpt2"]:
140
+ return ("A5_byte_level", f"Split(gpt2:{beh})", "GPT-2 regex Split (A5)")
141
+ if nr == KNOWN["deepseek_big"]:
142
+ return ("A4_deepseek", f"Split(ds_big:{beh})", "deepseek big regex Split")
143
+ # Unknown regex
144
+ return ("A1_split_regex", f"Split(Regex:{beh}:{pat_val[:50]})", f"regex Split, behavior={beh}")
145
+ elif pat_kind == "String":
146
+ return ("A1_split", f"Split(String:{beh}:{pat_val})", "literal Split (CharDelimiterSplit family)")
147
+ elif pat_kind == "FairSeq":
148
+ return ("UNKNOWN", f"Split(FairSeq:{beh})", "FairSeq pattern β€” not an atom")
149
+ else:
150
+ return ("UNKNOWN", f"Split({pat_kind}:{beh})", f"unknown Split pattern type {pat_kind}")
151
+ elif t == "UnicodeScripts":
152
+ return ("A6_script_run", "UnicodeScripts", "fsm_script_run (TODO in PR)")
153
+ elif t == "CharDelimiterSplit":
154
+ ch = pt.get("delimiter", "?")
155
+ return ("A1_split", f"CharDelimiterSplit({ch})", "byte compare, no tag")
156
+ elif t == "FixedLength":
157
+ return ("UNKNOWN", "FixedLength", "positional β€” rides char_start bitplane, not an atom FSM")
158
+ elif t == "Symbols":
159
+ return ("UNKNOWN", "Symbols", "Symbols pretokenizer β€” not in atom design")
160
+ elif t == "Sequence":
161
+ return classify_pre_tokenizer(pt, norm) # handled above
162
+ else:
163
+ return ("UNKNOWN", f"{t}", f"unknown pretokenizer type: {t}")
164
+
165
+ # ── Main ───────────────────────────────────────────────────────────────────────
166
+
167
+ def main():
168
+ records = [json.loads(l) for l in open(IN)]
169
+ print(f"Loaded {len(records)} scraped records")
170
+
171
+ # Classify each
172
+ results = []
173
+ for r in records:
174
+ pt = r.get("pre_tokenizer")
175
+ norm = r.get("normalizer")
176
+ if r.get("error"):
177
+ continue
178
+ atom, sig, detail = classify_pre_tokenizer(pt, norm)
179
+ results.append({
180
+ "id": r["id"],
181
+ "downloads": r.get("downloads", 0),
182
+ "atom": atom,
183
+ "sig": sig,
184
+ "detail": detail,
185
+ "pre_tokenizer": pt,
186
+ "normalizer": norm,
187
+ })
188
+
189
+ print(f"Classified {len(results)} models (excluding errors)\n")
190
+
191
+ # Aggregate by canonical signature
192
+ sig_counts = Counter()
193
+ sig_examples = defaultdict(list)
194
+ sig_atom = {}
195
+ sig_downloads = defaultdict(int)
196
+ for r in results:
197
+ sig_counts[r["sig"]] += 1
198
+ sig_examples[r["sig"]].append(r["id"])
199
+ sig_atom[r["sig"]] = r["atom"]
200
+ sig_downloads[r["sig"]] += r["downloads"]
201
+
202
+ # Print the full ranked table
203
+ print("=" * 120)
204
+ print(f"{'CANONICAL PRE_TOKENIZER SIGNATURE':<55} {'ATOM':<18} {'COUNT':>6} {'βˆ‘DL':>12} EXAMPLES")
205
+ print("=" * 120)
206
+ for sig, cnt in sig_counts.most_common():
207
+ atom = sig_atom[sig]
208
+ dl = sig_downloads[sig]
209
+ exs = sig_examples[sig][:3]
210
+ ex_str = " | ".join(exs)
211
+ if len(ex_str) > 40:
212
+ ex_str = ex_str[:37] + "..."
213
+ print(f"{sig:<55} {atom:<18} {cnt:>6} {dl:>12,} {ex_str}")
214
+ print("=" * 120)
215
+ print(f"TOTAL distinct signatures: {len(sig_counts)}")
216
+ print(f"TOTAL models classified: {len(results)}")
217
+
218
+ # Atom coverage summary
219
+ print("\n" + "=" * 80)
220
+ print("ATOM COVERAGE SUMMARY")
221
+ print("=" * 80)
222
+ atom_counts = Counter(r["atom"] for r in results)
223
+ atom_dl = defaultdict(int)
224
+ for r in results:
225
+ atom_dl[r["atom"]] += r["downloads"]
226
+ for atom, cnt in atom_counts.most_common():
227
+ dl = atom_dl[atom]
228
+ print(f" {atom:<20} models={cnt:>5} βˆ‘downloads={dl:>13,}")
229
+
230
+ # Patterns NOT covered by atoms
231
+ print("\n" + "=" * 80)
232
+ print("PATTERNS NOT COVERED BY ATOMS (need hand-unroll or escape hatch)")
233
+ print("=" * 80)
234
+ uncovered = [r for r in results if r["atom"] in ("UNKNOWN", "A1_split_regex", "SEQUENCE")]
235
+ unc_sigs = Counter(r["sig"] for r in uncovered)
236
+ unc_atom = defaultdict(set)
237
+ for r in uncovered:
238
+ unc_atom[r["atom"]].add(r["sig"])
239
+ print(f"\nBy atom category:")
240
+ for atom in sorted(unc_atom.keys()):
241
+ sigs = unc_atom[atom]
242
+ total_models = sum(sig_counts[s] for s in sigs)
243
+ total_dl = sum(sig_downloads[s] for s in sigs)
244
+ print(f"\n [{atom}] {len(sigs)} distinct signatures, {total_models} models, βˆ‘{total_dl:,} downloads")
245
+ for sig in sorted(sigs, key=lambda s: sig_downloads[s], reverse=True)[:20]:
246
+ cnt = sig_counts[sig]
247
+ dl = sig_downloads[sig]
248
+ exs = sig_examples[sig][:2]
249
+ print(f" {sig:<60} {cnt:>4} models βˆ‘{dl:>10,} e.g. {exs[0]}")
250
+
251
+ # The key question: how many unique "important" patterns need hand-unroll?
252
+ print("\n" + "=" * 80)
253
+ print("UNIQUE PATTERNS NEEDING HAND-UNROLL")
254
+ print("=" * 80)
255
+ # "Important" = either appears in >1 model OR >10K downloads
256
+ important_uncovered = []
257
+ for sig, cnt in unc_sigs.items():
258
+ dl = sig_downloads[sig]
259
+ atom = sig_atom[sig]
260
+ if cnt > 1 or dl > 10000:
261
+ important_uncovered.append((sig, atom, cnt, dl, sig_examples[sig][:3]))
262
+ important_uncovered.sort(key=lambda x: x[3], reverse=True)
263
+ print(f"\n{len(important_uncovered)} distinct signatures with >1 model OR >10K downloads:")
264
+ for sig, atom, cnt, dl, exs in important_uncovered:
265
+ print(f" [{atom}] {sig[:65]:<65} {cnt:>3}x βˆ‘{dl:>10,} {exs[0]}")
266
+
267
+ # Save full results
268
+ out_path = os.path.join(os.path.dirname(__file__), "classification.json")
269
+ with open(out_path, "w") as f:
270
+ json.dump(results, f, indent=2, ensure_ascii=False, default=str)
271
+ print(f"\nFull classification saved to {out_path}")
272
+
273
+ if __name__ == "__main__":
274
+ main()
scrape_analysis/model_list.json ADDED
@@ -0,0 +1 @@
 
 
1
+ []
scrape_analysis/scrape_hf.jsonl ADDED
File without changes
scrape_analysis/scrape_hf.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Scrape HuggingFace Hub for transformers-compatible models, fetch tokenizer.json
4
+ for each (streaming only pre_tokenizer + normalizer, not the vocab), dump to JSONL.
5
+ Uses cached HF token for higher rate limits.
6
+ """
7
+ import json, os, sys, time, urllib.request, urllib.error, concurrent.futures, threading
8
+ from collections import Counter
9
+
10
+ BASE = "https://huggingface.co/api/models"
11
+ RESOLVE = "https://huggingface.co/{mid}/resolve/main/tokenizer.json"
12
+ OUT = os.path.join(os.path.dirname(__file__), "scrape_hf.jsonl")
13
+ MODELS_OUT = os.path.join(os.path.dirname(__file__), "model_list.json")
14
+
15
+ TARGET = 10000
16
+ MAX_WORKERS = 40
17
+ TIMEOUT = 15
18
+
19
+ # Load HF token from cache for auth
20
+ def get_hf_token():
21
+ tok_path = os.path.expanduser("~/.cache/huggingface/token")
22
+ try:
23
+ with open(tok_path) as f:
24
+ return f.read().strip()
25
+ except:
26
+ return None
27
+
28
+ HF_TOKEN = get_hf_token()
29
+
30
+ def api_headers():
31
+ h = {"User-Agent": "hf-scrape/1.0"}
32
+ if HF_TOKEN:
33
+ h["Authorization"] = f"Bearer {HF_TOKEN}"
34
+ return h
35
+
36
+ # ── streaming pre_tokenizer extractor ──────────────────────────────────────────
37
+
38
+ def find_key_value(buf, key):
39
+ needle = b'"' + key.encode() + b'"'
40
+ idx = buf.find(needle)
41
+ if idx == -1:
42
+ return "NOT_FOUND", -1
43
+ i = idx + len(needle)
44
+ while i < len(buf) and buf[i:i+1] in (b' ', b'\t', b'\n', b'\r', b':'):
45
+ i += 1
46
+ if i >= len(buf):
47
+ return "INCOMPLETE", idx
48
+ start = i
49
+ b0 = buf[i]
50
+ if b0 in (0x6E, 0x74, 0x66): # null/true/false
51
+ j = i
52
+ while j < len(buf) and buf[j] not in (b',', b'}', b']', 0x20, 0x09, 0x0A, 0x0D):
53
+ j += 1
54
+ if j < len(buf):
55
+ return buf[start:j].decode('utf-8', errors='replace'), j
56
+ return "INCOMPLETE", idx
57
+ if b0 == 0x22: # string
58
+ j = i + 1
59
+ esc = False
60
+ while j < len(buf):
61
+ if esc:
62
+ esc = False
63
+ elif buf[j] == 0x5C:
64
+ esc = True
65
+ elif buf[j] == 0x22:
66
+ return buf[start:j+1].decode('utf-8', errors='replace'), j+1
67
+ j += 1
68
+ return "INCOMPLETE", idx
69
+ if (0x30 <= b0 <= 0x39) or b0 == 0x2D: # number
70
+ j = i
71
+ while j < len(buf) and buf[j] not in (b',', b'}', b']', 0x20, 0x09, 0x0A, 0x0D):
72
+ j += 1
73
+ if j < len(buf):
74
+ return buf[start:j].decode('utf-8', errors='replace'), j
75
+ return "INCOMPLETE", idx
76
+ # object/array -- brace-match
77
+ depth = 0
78
+ in_str = False
79
+ esc = False
80
+ while i < len(buf):
81
+ b = buf[i]
82
+ if in_str:
83
+ if esc:
84
+ esc = False
85
+ elif b == 0x5C:
86
+ esc = True
87
+ elif b == 0x22:
88
+ in_str = False
89
+ else:
90
+ if b == 0x22:
91
+ in_str = True
92
+ elif b in (0x7B, 0x5B):
93
+ depth += 1
94
+ elif b in (0x7D, 0x5D):
95
+ depth -= 1
96
+ if depth == 0:
97
+ return buf[start:i+1].decode('utf-8', errors='replace'), i+1
98
+ i += 1
99
+ return "INCOMPLETE", idx
100
+
101
+ def stream_pre_tokenizer(url, timeout=TIMEOUT, max_bytes=3_000_000):
102
+ req = urllib.request.Request(url, headers={"User-Agent": "hf-scrape/1.0"})
103
+ out = {}
104
+ for attempt in range(3):
105
+ try:
106
+ resp = urllib.request.urlopen(req, timeout=timeout)
107
+ buf = b""
108
+ have = set()
109
+ wanted = {"pre_tokenizer", "normalizer"}
110
+ try:
111
+ while True:
112
+ chunk = resp.read(65536)
113
+ if not chunk:
114
+ break
115
+ buf += chunk
116
+ for key in wanted:
117
+ if key not in have:
118
+ val, _ = find_key_value(buf, key)
119
+ if val == "NOT_FOUND":
120
+ continue
121
+ if val == "INCOMPLETE":
122
+ continue
123
+ try:
124
+ out[key] = json.loads(val) if val != "null" else None
125
+ have.add(key)
126
+ except:
127
+ pass
128
+ if have == wanted:
129
+ break
130
+ if b'"model"' in buf and have:
131
+ for key in wanted:
132
+ if key not in have:
133
+ out[key] = None
134
+ have.add(key)
135
+ break
136
+ if len(buf) > max_bytes:
137
+ break
138
+ finally:
139
+ resp.close()
140
+ break
141
+ except urllib.error.HTTPError as e:
142
+ if e.code == 429 and attempt < 2:
143
+ time.sleep(3 * (attempt+1))
144
+ continue
145
+ out["error"] = f"HTTP {e.code}"
146
+ break
147
+ except Exception as e:
148
+ out["error"] = str(e)[:200]
149
+ break
150
+ return out
151
+
152
+ # ── model list scraping ────────────────────────────────────────────────────────
153
+
154
+ def fetch_model_list(target):
155
+ models = []
156
+ seen = set()
157
+ offset = 0
158
+ limit = 500 # larger pages with auth
159
+ url_base = f"{BASE}?library=transformers&sort=downloads&direction=-1&limit={limit}"
160
+ print(f"Fetching model list with AUTH (target={target})...", flush=True)
161
+ consecutive_fails = 0
162
+ while len(models) < target:
163
+ page_url = f"{url_base}&offset={offset}"
164
+ batch = []
165
+ got = False
166
+ for attempt in range(5):
167
+ try:
168
+ req = urllib.request.Request(page_url, headers=api_headers())
169
+ with urllib.request.urlopen(req, timeout=30) as resp:
170
+ batch = json.loads(resp.read())
171
+ got = True
172
+ break
173
+ except urllib.error.HTTPError as e:
174
+ if e.code == 429:
175
+ wait = min(60, 5 * (attempt+1))
176
+ print(f" 429 at offset={offset}, waiting {wait}s", flush=True)
177
+ time.sleep(wait)
178
+ continue
179
+ print(f" HTTP {e.code} at offset={offset}", flush=True)
180
+ break
181
+ except Exception as e:
182
+ if attempt < 4:
183
+ time.sleep(2 * (attempt+1))
184
+ continue
185
+ print(f" FAILED offset={offset}: {e}", flush=True)
186
+ break
187
+ if not got or not batch:
188
+ consecutive_fails += 1
189
+ if consecutive_fails >= 3:
190
+ print(f" 3 consecutive fails, stopping", flush=True)
191
+ break
192
+ offset += limit
193
+ continue
194
+ consecutive_fails = 0
195
+ for m in batch:
196
+ mid = m["id"] if isinstance(m, dict) else m
197
+ if mid in seen:
198
+ continue
199
+ seen.add(mid)
200
+ models.append({
201
+ "id": mid,
202
+ "downloads": m.get("downloads", 0) if isinstance(m, dict) else 0,
203
+ "likes": m.get("likes", 0) if isinstance(m, dict) else 0,
204
+ })
205
+ if len(models) >= target:
206
+ break
207
+ offset += limit
208
+ if len(models) >= target or offset % 5000 == 0:
209
+ print(f" fetched {len(models)} models (offset={offset})", flush=True)
210
+ time.sleep(0.05)
211
+ return models[:target]
212
+
213
+ # ── main ───────────────────────────────────────────────────────────────────────
214
+
215
+ def main():
216
+ t0 = time.time()
217
+ models = fetch_model_list(TARGET)
218
+ print(f"\nGot {len(models)} model IDs in {time.time()-t0:.1f}s", flush=True)
219
+ with open(MODELS_OUT, "w") as f:
220
+ json.dump(models, f)
221
+
222
+ total = len(models)
223
+ results = []
224
+ done = [0]
225
+ lock = threading.Lock()
226
+
227
+ def fetch_one(m):
228
+ url = RESOLVE.format(mid=m["id"])
229
+ out = stream_pre_tokenizer(url)
230
+ rec = {
231
+ "id": m["id"],
232
+ "downloads": m.get("downloads", 0),
233
+ "likes": m.get("likes", 0),
234
+ "pre_tokenizer": out.get("pre_tokenizer"),
235
+ "normalizer": out.get("normalizer"),
236
+ "error": out.get("error"),
237
+ }
238
+ with lock:
239
+ done[0] += 1
240
+ if done[0] % 500 == 0:
241
+ print(f" progress: {done[0]}/{total}", flush=True)
242
+ return rec
243
+
244
+ print(f"\nFetching tokenizer.json for {total} models with {MAX_WORKERS} workers...", flush=True)
245
+ with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as ex:
246
+ futures = {ex.submit(fetch_one, m): m for m in models}
247
+ for f in concurrent.futures.as_completed(futures):
248
+ try:
249
+ results.append(f.result())
250
+ except Exception as e:
251
+ m = futures[f]
252
+ results.append({"id": m["id"], "error": str(e)[:200]})
253
+
254
+ # Sort by downloads desc
255
+ results.sort(key=lambda r: r.get("downloads", 0), reverse=True)
256
+ with open(OUT, "w") as f:
257
+ for r in results:
258
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
259
+
260
+ elapsed = time.time() - t0
261
+ ok = sum(1 for r in results if r.get("pre_tokenizer") is not None)
262
+ null_pt = sum(1 for r in results if r.get("pre_tokenizer") is None and not r.get("error"))
263
+ err = sum(1 for r in results if r.get("error"))
264
+ err404 = sum(1 for r in results if r.get("error") == "HTTP 404")
265
+ err401 = sum(1 for r in results if r.get("error") == "HTTP 401")
266
+ print(f"\n=== DONE in {elapsed:.1f}s ===", flush=True)
267
+ print(f" models listed: {len(models)}", flush=True)
268
+ print(f" had tokenizer.json (no 404): {len(results) - err404}", flush=True)
269
+ print(f" 404 (no tokenizer.json): {err404}", flush=True)
270
+ print(f" 401 (gated): {err401}", flush=True)
271
+ print(f" pre_tokenizer != None: {ok}", flush=True)
272
+ print(f" pre_tokenizer == null: {null_pt}", flush=True)
273
+ print(f" output: {OUT}", flush=True)
274
+
275
+ if __name__ == "__main__":
276
+ main()