OpenTransformer commited on
Commit
bd63fe9
·
verified ·
1 Parent(s): 00c4875

Upload source/crawl_v4.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. source/crawl_v4.py +375 -0
source/crawl_v4.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Fresh Web Crawler V4 - Actually crawls the internet ourselves.
3
+ Uses seed URLs from multiple sources, follows links BFS, extracts text with trafilatura.
4
+ Uploads large chunks (~1GB compressed) to OpenTransformer/web-crawl-2026."""
5
+ import os, sys, json, gzip, time, hashlib, random, re, traceback
6
+ from collections import deque
7
+ from urllib.parse import urlparse, urljoin
8
+ import requests
9
+ from bs4 import BeautifulSoup
10
+ import trafilatura
11
+ from huggingface_hub import HfApi, login
12
+
13
+ HF_TOKEN = "HF_TOKEN_REDACTED"
14
+ TARGET_REPO = "OpenTransformer/web-crawl-2026"
15
+ OUTPUT_DIR = "/workspace/scraped_data"
16
+ STATE_FILE = "/workspace/crawl_state_v4.json"
17
+ CHUNK_TARGET_BYTES = 1_200_000_000 # ~1.2GB uncompressed per chunk
18
+ TIMEOUT = 15
19
+ MIN_TEXT_LEN = 200
20
+ MAX_TEXT_LEN = 200_000
21
+ MAX_URLS_PER_DOMAIN = 500
22
+ CRAWL_DELAY = 0.3
23
+
24
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
25
+ login(token=HF_TOKEN, add_to_git_credential=False)
26
+ api = HfApi(token=HF_TOKEN)
27
+
28
+ USER_AGENTS = [
29
+ "Mozilla/5.0 (compatible; OpenTransformerBot/1.0; +https://huggingface.co/OpenTransformer)",
30
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
31
+ ]
32
+
33
+ SEED_DOMAINS = [
34
+ "https://www.reuters.com", "https://apnews.com", "https://www.bbc.com/news",
35
+ "https://www.theguardian.com", "https://www.npr.org", "https://arstechnica.com",
36
+ "https://news.ycombinator.com", "https://lobste.rs", "https://dev.to",
37
+ "https://stackoverflow.blog", "https://www.infoq.com",
38
+ "https://www.scientificamerican.com", "https://www.nature.com/news",
39
+ "https://phys.org", "https://www.quantamagazine.org",
40
+ "https://ocw.mit.edu", "https://plato.stanford.edu",
41
+ "https://en.wikipedia.org/wiki/Special:Random",
42
+ "https://en.wikisource.org", "https://www.gutenberg.org",
43
+ "https://www.usa.gov", "https://www.gov.uk",
44
+ "https://data.gov", "https://www.loc.gov",
45
+ "https://www.smithsonianmag.com", "https://nautil.us",
46
+ "https://longreads.com", "https://theconversation.com",
47
+ "https://fs.blog", "https://waitbutwhy.com",
48
+ "https://www.lesswrong.com", "https://marginalrevolution.com",
49
+ "https://www.wired.com", "https://www.theatlantic.com",
50
+ "https://www.newyorker.com", "https://www.economist.com",
51
+ "https://www.pbs.org", "https://www.vox.com",
52
+ "https://www.propublica.org", "https://fivethirtyeight.com",
53
+ "https://www.technologyreview.com", "https://spectrum.ieee.org",
54
+ "https://www.livescience.com", "https://www.space.com",
55
+ "https://www.sciencedaily.com", "https://www.psychologytoday.com",
56
+ "https://news.mit.edu", "https://www.cam.ac.uk/news",
57
+ "https://hai.stanford.edu/news", "https://www.ox.ac.uk/news",
58
+ "https://www.brookings.edu", "https://www.rand.org",
59
+ "https://www.cfr.org", "https://carnegieendowment.org",
60
+ ]
61
+
62
+ BLOCKED_EXTENSIONS = {".pdf", ".jpg", ".jpeg", ".png", ".gif", ".svg", ".mp3", ".mp4",
63
+ ".avi", ".mov", ".zip", ".tar", ".gz", ".exe", ".dmg", ".iso",
64
+ ".css", ".js", ".woff", ".woff2", ".ttf", ".eot", ".ico", ".webp"}
65
+ BLOCKED_PATTERNS = re.compile(
66
+ r"(login|signup|signin|register|cart|checkout|payment|admin|wp-admin|"
67
+ r"facebook\.com|twitter\.com|instagram\.com|tiktok\.com|"
68
+ r"youtube\.com/watch|amazon\.|ebay\.|\.pdf$|/tag/|/category/|"
69
+ r"/page/\d+|/feed/|/rss|/atom|#comment|/reply|/share)", re.I)
70
+
71
+
72
+ def load_state():
73
+ if os.path.exists(STATE_FILE):
74
+ with open(STATE_FILE) as f:
75
+ return json.load(f)
76
+ return {"chunk_num": 0, "total_docs": 0, "total_bytes_uploaded": 0,
77
+ "seen_hashes": [], "domain_counts": {}}
78
+
79
+
80
+ def save_state(state):
81
+ if len(state.get("seen_hashes", [])) > 500000:
82
+ state["seen_hashes"] = state["seen_hashes"][-200000:]
83
+ with open(STATE_FILE, "w") as f:
84
+ json.dump(state, f)
85
+
86
+
87
+ def is_valid_url(url):
88
+ try:
89
+ p = urlparse(url)
90
+ if p.scheme not in ("http", "https"):
91
+ return False
92
+ if not p.netloc or "." not in p.netloc:
93
+ return False
94
+ ext = os.path.splitext(p.path)[1].lower()
95
+ if ext in BLOCKED_EXTENSIONS:
96
+ return False
97
+ if BLOCKED_PATTERNS.search(url):
98
+ return False
99
+ return True
100
+ except Exception:
101
+ return False
102
+
103
+
104
+ def extract_links(html, base_url):
105
+ links = []
106
+ try:
107
+ soup = BeautifulSoup(html, "html.parser")
108
+ for a in soup.find_all("a", href=True):
109
+ href = a["href"].strip()
110
+ if href.startswith("#") or href.startswith("javascript:"):
111
+ continue
112
+ full = urljoin(base_url, href)
113
+ full = full.split("#")[0]
114
+ if is_valid_url(full):
115
+ links.append(full)
116
+ except Exception:
117
+ pass
118
+ return links
119
+
120
+
121
+ def content_hash(text):
122
+ return hashlib.md5(text[:500].encode("utf-8", errors="ignore")).hexdigest()
123
+
124
+
125
+ def fetch_page(url, session):
126
+ try:
127
+ resp = session.get(url, timeout=TIMEOUT, allow_redirects=True,
128
+ headers={"User-Agent": random.choice(USER_AGENTS),
129
+ "Accept": "text/html,application/xhtml+xml",
130
+ "Accept-Language": "en-US,en;q=0.9"})
131
+ if resp.status_code != 200:
132
+ return None, None
133
+ ct = resp.headers.get("content-type", "")
134
+ if "text/html" not in ct and "xhtml" not in ct:
135
+ return None, None
136
+ return resp.text, resp.url
137
+ except Exception:
138
+ return None, None
139
+
140
+
141
+ def extract_text(html, url):
142
+ try:
143
+ text = trafilatura.extract(html, include_comments=False, include_tables=True,
144
+ no_fallback=False, favor_precision=False, url=url)
145
+ if text and len(text) >= MIN_TEXT_LEN:
146
+ return text[:MAX_TEXT_LEN]
147
+ except Exception:
148
+ pass
149
+ return None
150
+
151
+
152
+ def get_random_wikipedia_urls(n=100):
153
+ urls = []
154
+ try:
155
+ resp = requests.get("https://en.wikipedia.org/w/api.php",
156
+ params={"action": "query", "list": "random",
157
+ "rnnamespace": 0, "rnlimit": min(n, 500), "format": "json"},
158
+ timeout=10)
159
+ data = resp.json()
160
+ for page in data.get("query", {}).get("random", []):
161
+ title = page["title"].replace(" ", "_")
162
+ urls.append("https://en.wikipedia.org/wiki/" + title)
163
+ except Exception:
164
+ pass
165
+ return urls
166
+
167
+
168
+ def get_hn_urls(n=30):
169
+ urls = []
170
+ try:
171
+ resp = requests.get("https://hacker-news.firebaseio.com/v0/topstories.json", timeout=10)
172
+ ids = resp.json()[:n]
173
+ for sid in ids:
174
+ try:
175
+ item = requests.get(
176
+ "https://hacker-news.firebaseio.com/v0/item/%d.json" % sid, timeout=5).json()
177
+ if item and item.get("url"):
178
+ urls.append(item["url"])
179
+ except Exception:
180
+ continue
181
+ except Exception:
182
+ pass
183
+ return urls
184
+
185
+
186
+ def get_lobsters_urls(n=25):
187
+ urls = []
188
+ try:
189
+ resp = requests.get("https://lobste.rs/hottest.json", timeout=10)
190
+ for item in resp.json()[:n]:
191
+ if item.get("url"):
192
+ urls.append(item["url"])
193
+ except Exception:
194
+ pass
195
+ return urls
196
+
197
+
198
+ def upload_chunk(filepath, remote_name):
199
+ fsize = os.path.getsize(filepath) / (1024 * 1024)
200
+ print(" Uploading %s (%.1f MB)..." % (remote_name, fsize), flush=True)
201
+ for attempt in range(5):
202
+ try:
203
+ api.upload_file(
204
+ path_or_fileobj=filepath,
205
+ path_in_repo="data/" + remote_name,
206
+ repo_id=TARGET_REPO,
207
+ repo_type="dataset",
208
+ )
209
+ print(" Uploaded %s (%.1f MB)" % (remote_name, fsize), flush=True)
210
+ return True
211
+ except Exception as e:
212
+ print(" Upload attempt %d failed: %s" % (attempt + 1, e), flush=True)
213
+ time.sleep(30 * (attempt + 1))
214
+ return False
215
+
216
+
217
+ def main():
218
+ print("=" * 60, flush=True)
219
+ print("Fresh Web Crawler V4", flush=True)
220
+ print("Target: %s" % TARGET_REPO, flush=True)
221
+ print("Chunk target: ~%.1fGB uncompressed" % (CHUNK_TARGET_BYTES / 1e9), flush=True)
222
+ print("=" * 60, flush=True)
223
+
224
+ state = load_state()
225
+ seen_hashes = set(state.get("seen_hashes", []))
226
+ domain_counts = state.get("domain_counts", {})
227
+ chunk_num = state.get("chunk_num", 0)
228
+ total_docs = state.get("total_docs", 0)
229
+
230
+ session = requests.Session()
231
+ session.headers.update({"User-Agent": random.choice(USER_AGENTS)})
232
+
233
+ while True:
234
+ # Build URL queue from seeds + discovered links
235
+ url_queue = deque()
236
+ discovered = set()
237
+
238
+ # Add seed URLs
239
+ seeds = list(SEED_DOMAINS)
240
+ random.shuffle(seeds)
241
+ for seed in seeds:
242
+ url_queue.append(seed)
243
+ discovered.add(seed)
244
+
245
+ # Add random Wikipedia articles
246
+ for u in get_random_wikipedia_urls(200):
247
+ if u not in discovered:
248
+ url_queue.append(u)
249
+ discovered.add(u)
250
+
251
+ # Add HN + Lobsters links
252
+ for u in get_hn_urls(30) + get_lobsters_urls(25):
253
+ if u not in discovered:
254
+ url_queue.append(u)
255
+ discovered.add(u)
256
+
257
+ chunk_name = "crawl_v4_chunk%04d.jsonl.gz" % chunk_num
258
+ chunk_path = os.path.join(OUTPUT_DIR, chunk_name)
259
+ f = gzip.open(chunk_path, "wt", encoding="utf-8")
260
+ chunk_bytes = 0
261
+ chunk_docs = 0
262
+ chunk_start = time.time()
263
+
264
+ print("\nStarting chunk %d..." % chunk_num, flush=True)
265
+
266
+ pages_tried = 0
267
+ last_status = time.time()
268
+
269
+ while chunk_bytes < CHUNK_TARGET_BYTES and url_queue:
270
+ url = url_queue.popleft()
271
+ domain = urlparse(url).netloc
272
+
273
+ # Rate limit per domain
274
+ dc = domain_counts.get(domain, 0)
275
+ if dc >= MAX_URLS_PER_DOMAIN:
276
+ continue
277
+
278
+ pages_tried += 1
279
+ html, final_url = fetch_page(url, session)
280
+ if not html:
281
+ time.sleep(0.05)
282
+ continue
283
+
284
+ # Extract text
285
+ text = extract_text(html, final_url or url)
286
+ if not text:
287
+ time.sleep(0.05)
288
+ continue
289
+
290
+ # Dedup
291
+ h = content_hash(text)
292
+ if h in seen_hashes:
293
+ continue
294
+ seen_hashes.add(h)
295
+
296
+ # Write doc
297
+ doc = json.dumps({
298
+ "text": text,
299
+ "url": final_url or url,
300
+ "domain": domain,
301
+ "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
302
+ "source": "crawl_v4",
303
+ }, ensure_ascii=False)
304
+ f.write(doc + "\n")
305
+ doc_bytes = len(doc.encode("utf-8"))
306
+ chunk_bytes += doc_bytes
307
+ chunk_docs += 1
308
+ total_docs += 1
309
+ domain_counts[domain] = dc + 1
310
+
311
+ # Extract and queue new links
312
+ new_links = extract_links(html, final_url or url)
313
+ random.shuffle(new_links)
314
+ for link in new_links[:30]:
315
+ if link not in discovered and len(url_queue) < 200000:
316
+ url_queue.append(link)
317
+ discovered.add(link)
318
+
319
+ # Status every 60s
320
+ now = time.time()
321
+ if now - last_status > 60:
322
+ rate = chunk_docs / max(1, now - chunk_start)
323
+ elapsed_min = (now - chunk_start) / 60
324
+ print(" Chunk %d: %d docs, %.0fMB, %d queued, %.1f docs/s, "
325
+ "tried %d pages, %.0f min elapsed" %
326
+ (chunk_num, chunk_docs, chunk_bytes / 1e6,
327
+ len(url_queue), rate, pages_tried, elapsed_min), flush=True)
328
+ last_status = now
329
+
330
+ time.sleep(CRAWL_DELAY)
331
+
332
+ f.close()
333
+
334
+ if chunk_docs == 0:
335
+ print(" No docs in chunk, cleaning up", flush=True)
336
+ try:
337
+ os.remove(chunk_path)
338
+ except OSError:
339
+ pass
340
+ print(" Waiting 5 min before retrying with fresh seeds...", flush=True)
341
+ time.sleep(300)
342
+ continue
343
+
344
+ elapsed = time.time() - chunk_start
345
+ compressed_size = os.path.getsize(chunk_path)
346
+ print(" Chunk %d complete: %d docs, %.0fMB uncompressed, %.0fMB compressed, %.0f min" %
347
+ (chunk_num, chunk_docs, chunk_bytes / 1e6, compressed_size / 1e6, elapsed / 60), flush=True)
348
+
349
+ # Upload
350
+ if upload_chunk(chunk_path, chunk_name):
351
+ try:
352
+ os.remove(chunk_path)
353
+ except OSError:
354
+ pass
355
+ chunk_num += 1
356
+ state["chunk_num"] = chunk_num
357
+ state["total_docs"] = total_docs
358
+ state["total_bytes_uploaded"] = state.get("total_bytes_uploaded", 0) + compressed_size
359
+ state["seen_hashes"] = list(seen_hashes)
360
+ state["domain_counts"] = domain_counts
361
+ save_state(state)
362
+ print(" Total: %d docs, %d chunks uploaded" % (total_docs, chunk_num), flush=True)
363
+ else:
364
+ print(" Upload failed, will retry", flush=True)
365
+ try:
366
+ os.remove(chunk_path)
367
+ except OSError:
368
+ pass
369
+
370
+ # Brief pause between chunks
371
+ time.sleep(10)
372
+
373
+
374
+ if __name__ == "__main__":
375
+ main()