File size: 10,310 Bytes
59913a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#!/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()