OpenTransformer commited on
Commit
7b8fd18
·
verified ·
1 Parent(s): 5be10c2

Upload source/main_rs_upload.rs with huggingface_hub

Browse files
Files changed (1) hide show
  1. source/main_rs_upload.rs +874 -0
source/main_rs_upload.rs ADDED
@@ -0,0 +1,874 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use dashmap::DashMap;
2
+ use flate2::write::GzEncoder;
3
+ use flate2::Compression;
4
+ use md5::{Digest, Md5};
5
+ use rand::seq::SliceRandom;
6
+ use rand::Rng;
7
+ use regex::Regex;
8
+ use reqwest::Client;
9
+ use scraper::{Html, Selector};
10
+ use serde::Serialize;
11
+ use std::io::Write;
12
+ use std::path::{Path, PathBuf};
13
+ use std::process::Command;
14
+ use std::sync::atomic::{AtomicI64, AtomicU64, Ordering};
15
+ use std::sync::Arc;
16
+ use std::time::{Duration, Instant};
17
+ use tokio::sync::{Mutex, Semaphore};
18
+ use url::Url;
19
+
20
+ const NUM_WORKERS: usize = 500;
21
+ const FETCH_TIMEOUT: Duration = Duration::from_secs(8);
22
+ const MIN_TEXT_LEN: usize = 200;
23
+ const MAX_TEXT_LEN: usize = 200_000;
24
+ const MAX_URLS_PER_DOMAIN: u32 = 1000;
25
+ const CHUNK_TARGET_BYTES: i64 = 1_200_000_000;
26
+ const MAX_QUEUE_SIZE: usize = 5_000_000;
27
+ const STATUS_INTERVAL: Duration = Duration::from_secs(30);
28
+ const HF_TOKEN: &str = "YOUR_HF_TOKEN_HERE";
29
+ const TARGET_REPO: &str = "OpenTransformer/web-crawl-2026";
30
+ const OUTPUT_DIR: &str = "/workspace/scraped_data_rust";
31
+
32
+ static USER_AGENTS: &[&str] = &[
33
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
34
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
35
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15",
36
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:124.0) Gecko/20100101 Firefox/124.0",
37
+ "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:123.0) Gecko/20100101 Firefox/123.0",
38
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0",
39
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
40
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
41
+ ];
42
+
43
+ static BLOCKED_EXTENSIONS: &[&str] = &[
44
+ ".pdf", ".jpg", ".jpeg", ".png", ".gif", ".svg", ".mp3", ".mp4", ".avi",
45
+ ".mov", ".zip", ".tar", ".gz", ".exe", ".dmg", ".css", ".js", ".woff",
46
+ ".woff2", ".ttf", ".ico", ".webp", ".bmp", ".doc", ".docx", ".xls",
47
+ ".xlsx", ".ppt", ".pptx", ".iso", ".rar", ".7z", ".apk", ".deb", ".rpm",
48
+ ];
49
+
50
+ #[derive(Serialize)]
51
+ struct Document {
52
+ text: String,
53
+ url: String,
54
+ domain: String,
55
+ timestamp: String,
56
+ source: String,
57
+ }
58
+
59
+ struct URLQueue {
60
+ queue: Mutex<Vec<String>>,
61
+ }
62
+
63
+ impl URLQueue {
64
+ fn new() -> Self {
65
+ Self {
66
+ queue: Mutex::new(Vec::with_capacity(100_000)),
67
+ }
68
+ }
69
+
70
+ async fn push(&self, url: String) -> bool {
71
+ let mut q = self.queue.lock().await;
72
+ if q.len() >= MAX_QUEUE_SIZE {
73
+ return false;
74
+ }
75
+ q.push(url);
76
+ true
77
+ }
78
+
79
+ async fn push_bulk(&self, urls: Vec<String>) -> usize {
80
+ let mut q = self.queue.lock().await;
81
+ let mut added = 0;
82
+ for url in urls {
83
+ if q.len() >= MAX_QUEUE_SIZE {
84
+ break;
85
+ }
86
+ q.push(url);
87
+ added += 1;
88
+ }
89
+ added
90
+ }
91
+
92
+ async fn pop_batch(&self, n: usize) -> Vec<String> {
93
+ let mut q = self.queue.lock().await;
94
+ let drain_count = n.min(q.len());
95
+ if drain_count == 0 {
96
+ return Vec::new();
97
+ }
98
+ let start = q.len() - drain_count;
99
+ q.drain(start..).collect()
100
+ }
101
+
102
+ async fn len(&self) -> usize {
103
+ self.queue.lock().await.len()
104
+ }
105
+
106
+ async fn shuffle(&self) {
107
+ let mut q = self.queue.lock().await;
108
+ let mut rng = rand::thread_rng();
109
+ q.shuffle(&mut rng);
110
+ }
111
+ }
112
+
113
+ fn is_valid_url(raw: &str) -> bool {
114
+ let u = match Url::parse(raw) {
115
+ Ok(u) => u,
116
+ Err(_) => return false,
117
+ };
118
+ match u.scheme() {
119
+ "http" | "https" => {}
120
+ _ => return false,
121
+ }
122
+ let host = match u.host_str() {
123
+ Some(h) => h,
124
+ None => return false,
125
+ };
126
+ if !host.contains('.') {
127
+ return false;
128
+ }
129
+ let path_lower = u.path().to_lowercase();
130
+ for ext in BLOCKED_EXTENSIONS {
131
+ if path_lower.ends_with(ext) {
132
+ return false;
133
+ }
134
+ }
135
+ let full_lower = raw.to_lowercase();
136
+ if BLOCKED_PATTERN.is_match(&full_lower) {
137
+ return false;
138
+ }
139
+ true
140
+ }
141
+
142
+ fn get_domain(raw: &str) -> String {
143
+ Url::parse(raw)
144
+ .ok()
145
+ .and_then(|u| u.host_str().map(|h| h.to_string()))
146
+ .unwrap_or_default()
147
+ }
148
+
149
+ fn content_hash(text: &str) -> String {
150
+ let mut end = text.len().min(500);
151
+ while end > 0 && !text.is_char_boundary(end) {
152
+ end -= 1;
153
+ }
154
+ let mut hasher = Md5::new();
155
+ hasher.update(text[..end].as_bytes());
156
+ format!("{:x}", hasher.finalize())
157
+ }
158
+
159
+ fn extract_text_from_html(html_str: &str) -> String {
160
+ let document = Html::parse_document(html_str);
161
+ let body_sel = Selector::parse("article, main, [role=main], body").unwrap();
162
+
163
+ let mut text_parts: Vec<String> = Vec::new();
164
+
165
+ // Try to find main content area first, fallback to whole document
166
+ let root = document.select(&body_sel).next();
167
+ if let Some(element) = root {
168
+ for text_node in element.text() {
169
+ let trimmed = text_node.trim();
170
+ if !trimmed.is_empty() {
171
+ text_parts.push(trimmed.to_string());
172
+ }
173
+ }
174
+ } else {
175
+ for text_node in document.root_element().text() {
176
+ let trimmed = text_node.trim();
177
+ if !trimmed.is_empty() {
178
+ text_parts.push(trimmed.to_string());
179
+ }
180
+ }
181
+ }
182
+
183
+ let mut result = text_parts.join(" ");
184
+
185
+ // Collapse whitespace
186
+ let ws_re = Regex::new(r"\s+").unwrap();
187
+ result = ws_re.replace_all(&result, " ").trim().to_string();
188
+
189
+ // Remove any remaining HTML entities
190
+ result = result
191
+ .replace("&amp;", "&")
192
+ .replace("&lt;", "<")
193
+ .replace("&gt;", ">")
194
+ .replace("&quot;", "\"")
195
+ .replace("&#39;", "'")
196
+ .replace("&nbsp;", " ");
197
+
198
+ result
199
+ }
200
+
201
+ fn extract_links(html_str: &str, base_url: &str) -> Vec<String> {
202
+ let base = match Url::parse(base_url) {
203
+ Ok(u) => u,
204
+ Err(_) => return Vec::new(),
205
+ };
206
+ let document = Html::parse_document(html_str);
207
+ let a_sel = Selector::parse("a[href]").unwrap();
208
+ let mut links = Vec::new();
209
+
210
+ for element in document.select(&a_sel) {
211
+ if let Some(href) = element.value().attr("href") {
212
+ let href = href.trim();
213
+ if href.starts_with('#') || href.starts_with("javascript:") || href.starts_with("mailto:") || href.starts_with("tel:") {
214
+ continue;
215
+ }
216
+ if let Ok(resolved) = base.join(href) {
217
+ let mut full = resolved.to_string();
218
+ // Strip fragment
219
+ if let Some(pos) = full.find('#') {
220
+ full.truncate(pos);
221
+ }
222
+ if is_valid_url(&full) {
223
+ links.push(full);
224
+ }
225
+ }
226
+ }
227
+ }
228
+ links
229
+ }
230
+
231
+ async fn fetch_page(client: &Client, url: &str) -> Result<(String, String), String> {
232
+ let ua = {
233
+ let mut rng = rand::thread_rng();
234
+ USER_AGENTS[rng.gen_range(0..USER_AGENTS.len())]
235
+ };
236
+
237
+ let resp = client
238
+ .get(url)
239
+ .header("User-Agent", ua)
240
+ .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
241
+ .header("Accept-Language", "en-US,en;q=0.9")
242
+ .header("Accept-Encoding", "gzip, deflate, br")
243
+ .send()
244
+ .await
245
+ .map_err(|e| e.to_string())?;
246
+
247
+ let status = resp.status();
248
+ if !status.is_success() {
249
+ return Err(format!("status {}", status));
250
+ }
251
+
252
+ let ct = resp
253
+ .headers()
254
+ .get("content-type")
255
+ .and_then(|v| v.to_str().ok())
256
+ .unwrap_or("");
257
+ if !ct.contains("text/html") && !ct.contains("xhtml") {
258
+ return Err(format!("not html: {}", ct));
259
+ }
260
+
261
+ let final_url = resp.url().to_string();
262
+
263
+ // Limit body to 2MB
264
+ let body_bytes = resp.bytes().await.map_err(|e| e.to_string())?;
265
+ if body_bytes.len() > 2 * 1024 * 1024 {
266
+ let body = String::from_utf8_lossy(&body_bytes[..2 * 1024 * 1024]).to_string();
267
+ return Ok((body, final_url));
268
+ }
269
+ let body = String::from_utf8_lossy(&body_bytes).to_string();
270
+ Ok((body, final_url))
271
+ }
272
+
273
+ async fn download_commoncrawl_urls(queue: &URLQueue, target_count: usize) -> usize {
274
+ println!("[seed] Downloading Common Crawl URL index...");
275
+ let client = Client::builder()
276
+ .timeout(Duration::from_secs(60))
277
+ .build()
278
+ .unwrap();
279
+
280
+ let queries = vec![
281
+ "*.com/*", "*.org/*", "*.net/*", "*.edu/*", "*.gov/*",
282
+ "*.co.uk/*", "*.io/*", "*.info/*", "*.us/*", "*.ca/*",
283
+ "*.au/*", "*.de/*", "*.fr/*",
284
+ ];
285
+
286
+ let mut added = 0usize;
287
+ for q in queries {
288
+ if added >= target_count {
289
+ break;
290
+ }
291
+ let api_url = format!(
292
+ "https://index.commoncrawl.org/CC-MAIN-2024-10-index?url={}&output=json&limit=15000&fl=url&filter=languages:eng",
293
+ urlencoding::encode(q)
294
+ );
295
+ let resp = match client.get(&api_url).send().await {
296
+ Ok(r) => r,
297
+ Err(e) => {
298
+ println!("[seed] CC query failed for {}: {}", q, e);
299
+ continue;
300
+ }
301
+ };
302
+ let text = match resp.text().await {
303
+ Ok(t) => t,
304
+ Err(_) => continue,
305
+ };
306
+ let mut batch = Vec::with_capacity(10_000);
307
+ for line in text.lines() {
308
+ if let Ok(val) = serde_json::from_str::<serde_json::Value>(line) {
309
+ if let Some(url) = val.get("url").and_then(|u| u.as_str()) {
310
+ if is_valid_url(url) {
311
+ batch.push(url.to_string());
312
+ if batch.len() >= 10_000 {
313
+ added += queue.push_bulk(batch).await;
314
+ batch = Vec::with_capacity(10_000);
315
+ }
316
+ }
317
+ }
318
+ }
319
+ }
320
+ if !batch.is_empty() {
321
+ added += queue.push_bulk(batch).await;
322
+ }
323
+ println!("[seed] CC {}: total queued so far: {}", q, queue.len().await);
324
+ }
325
+ added
326
+ }
327
+
328
+ async fn download_wikipedia_urls(queue: &URLQueue, count: usize) -> usize {
329
+ println!("[seed] Fetching {} Wikipedia URLs...", count);
330
+ let client = Client::builder()
331
+ .timeout(Duration::from_secs(30))
332
+ .build()
333
+ .unwrap();
334
+
335
+ let mut added = 0;
336
+ let mut failures = 0;
337
+ while added < count && failures < 5 {
338
+ let remaining = (count - added).min(500);
339
+ let url = format!(
340
+ "https://en.wikipedia.org/w/api.php?action=query&list=random&rnnamespace=0&rnlimit={}&format=json",
341
+ remaining
342
+ );
343
+ let resp = match client.get(&url).send().await {
344
+ Ok(r) => r,
345
+ Err(_) => {
346
+ failures += 1;
347
+ tokio::time::sleep(Duration::from_secs(2)).await;
348
+ continue;
349
+ }
350
+ };
351
+ let data: serde_json::Value = match resp.json().await {
352
+ Ok(d) => d,
353
+ Err(_) => {
354
+ failures += 1;
355
+ continue;
356
+ }
357
+ };
358
+ let random = match data["query"]["random"].as_array() {
359
+ Some(a) => a,
360
+ None => {
361
+ failures += 1;
362
+ continue;
363
+ }
364
+ };
365
+ let batch: Vec<String> = random
366
+ .iter()
367
+ .filter_map(|p| p["title"].as_str())
368
+ .map(|t| format!("https://en.wikipedia.org/wiki/{}", t.replace(' ', "_")))
369
+ .collect();
370
+ let n = queue.push_bulk(batch).await;
371
+ added += n;
372
+ if n == 0 {
373
+ failures += 1;
374
+ } else {
375
+ failures = 0;
376
+ }
377
+ println!("[seed] Wikipedia: {} URLs added (total {})", n, added);
378
+ }
379
+ added
380
+ }
381
+
382
+ async fn download_sitemap_urls(queue: &URLQueue) -> usize {
383
+ println!("[seed] Fetching sitemaps from major sites...");
384
+ let client = Client::builder()
385
+ .timeout(Duration::from_secs(15))
386
+ .build()
387
+ .unwrap();
388
+
389
+ let sitemaps = vec![
390
+ "https://www.reuters.com/arc/outboundfeeds/sitemap-index/?outputType=xml",
391
+ "https://www.bbc.com/sitemaps/https-sitemap-com-news-1.xml",
392
+ "https://www.theguardian.com/sitemaps/news.xml",
393
+ "https://www.npr.org/sitemap.xml",
394
+ "https://arstechnica.com/sitemap.xml",
395
+ "https://www.wired.com/sitemap.xml",
396
+ "https://www.theatlantic.com/sitemap.xml",
397
+ "https://www.nature.com/sitemap.xml",
398
+ "https://phys.org/sitemap.xml",
399
+ "https://www.scientificamerican.com/sitemap.xml",
400
+ "https://www.smithsonianmag.com/sitemap.xml",
401
+ "https://www.britannica.com/sitemap.xml",
402
+ "https://www.healthline.com/sitemap.xml",
403
+ "https://www.investopedia.com/sitemap.xml",
404
+ "https://www.geeksforgeeks.org/sitemap.xml",
405
+ "https://realpython.com/sitemap.xml",
406
+ "https://www.freecodecamp.org/news/sitemap.xml",
407
+ "https://hackernoon.com/sitemap.xml",
408
+ "https://dev.to/sitemap.xml",
409
+ "https://www.history.com/sitemap.xml",
410
+ "https://www.livescience.com/sitemap.xml",
411
+ "https://www.space.com/sitemap.xml",
412
+ "https://www.sciencedaily.com/sitemap.xml",
413
+ "https://www.psychologytoday.com/sitemap.xml",
414
+ "https://www.mayoclinic.org/sitemap.xml",
415
+ "https://medlineplus.gov/sitemap.xml",
416
+ "https://plato.stanford.edu/sitemap.xml",
417
+ "https://www.brookings.edu/sitemap.xml",
418
+ "https://www.rand.org/sitemap.xml",
419
+ "https://stackoverflow.com/sitemap.xml",
420
+ "https://docs.python.org/3/sitemap.xml",
421
+ "https://docs.rs/sitemap.xml",
422
+ "https://www.rust-lang.org/sitemap.xml",
423
+ "https://go.dev/sitemap.xml",
424
+ ];
425
+
426
+ let loc_re = Regex::new(r"<loc>([^<]+)</loc>").unwrap();
427
+ let mut added = 0;
428
+
429
+ for sitemap_url in sitemaps {
430
+ let resp = match client.get(sitemap_url).send().await {
431
+ Ok(r) => r,
432
+ Err(_) => continue,
433
+ };
434
+ let body = match resp.text().await {
435
+ Ok(t) => t,
436
+ Err(_) => continue,
437
+ };
438
+ let batch: Vec<String> = loc_re
439
+ .captures_iter(&body)
440
+ .filter_map(|c| {
441
+ let u = c[1].to_string();
442
+ if is_valid_url(&u) && !u.ends_with(".xml") && !u.ends_with(".xml.gz") {
443
+ Some(u)
444
+ } else {
445
+ None
446
+ }
447
+ })
448
+ .collect();
449
+ let n = queue.push_bulk(batch).await;
450
+ if n > 0 {
451
+ println!("[seed] Sitemap {}: +{} URLs", get_domain(sitemap_url), n);
452
+ }
453
+ added += n;
454
+ }
455
+ println!("[seed] Sitemaps total: {} URLs added", added);
456
+ added
457
+ }
458
+
459
+ async fn download_hn_urls(queue: &URLQueue) -> usize {
460
+ let client = Client::builder()
461
+ .timeout(Duration::from_secs(10))
462
+ .build()
463
+ .unwrap();
464
+
465
+ let mut urls = Vec::new();
466
+ for endpoint in &["topstories", "newstories", "beststories"] {
467
+ let api = format!("https://hacker-news.firebaseio.com/v0/{}.json", endpoint);
468
+ let resp = match client.get(&api).send().await {
469
+ Ok(r) => r,
470
+ Err(_) => continue,
471
+ };
472
+ let ids: Vec<u64> = match resp.json::<Vec<u64>>().await {
473
+ Ok(v) => v,
474
+ Err(_) => continue,
475
+ };
476
+ // Fetch items concurrently in batches
477
+ let sem = Arc::new(Semaphore::new(20));
478
+ let mut handles = Vec::new();
479
+ for &id in ids.iter().take(100) {
480
+ let client = client.clone();
481
+ let sem = sem.clone();
482
+ handles.push(tokio::spawn(async move {
483
+ let _permit = sem.acquire().await.ok()?;
484
+ let url = format!("https://hacker-news.firebaseio.com/v0/item/{}.json", id);
485
+ let resp = client.get(&url).send().await.ok()?;
486
+ let item: serde_json::Value = resp.json().await.ok()?;
487
+ item["url"].as_str().map(|s| s.to_string())
488
+ }));
489
+ }
490
+ for h in handles {
491
+ if let Ok(Some(url)) = h.await {
492
+ if !url.is_empty() {
493
+ urls.push(url);
494
+ }
495
+ }
496
+ }
497
+ }
498
+ let n = queue.push_bulk(urls).await;
499
+ println!("[seed] HN: {} URLs added", n);
500
+ n
501
+ }
502
+
503
+ fn upload_chunk(filepath: &str, remote_name: &str) -> bool {
504
+ let script = format!(
505
+ r#"
506
+ from huggingface_hub import HfApi
507
+ api = HfApi(token="{}")
508
+ api.upload_file(path_or_fileobj="{}", path_in_repo="data/{}", repo_id="{}", repo_type="dataset")
509
+ print("OK")
510
+ "#,
511
+ HF_TOKEN, filepath, remote_name, TARGET_REPO
512
+ );
513
+ let output = Command::new("python3").arg("-c").arg(&script).output();
514
+ match output {
515
+ Ok(o) => {
516
+ if o.status.success() {
517
+ println!(" Uploaded {}", remote_name);
518
+ true
519
+ } else {
520
+ println!(
521
+ " Upload failed: {}",
522
+ String::from_utf8_lossy(&o.stderr)
523
+ );
524
+ false
525
+ }
526
+ }
527
+ Err(e) => {
528
+ println!(" Upload error: {}", e);
529
+ false
530
+ }
531
+ }
532
+ }
533
+
534
+ lazy_static::lazy_static! {
535
+ static ref BLOCKED_PATTERN: Regex = Regex::new(
536
+ r"(?i)(login|signup|signin|register|cart|checkout|payment|admin|wp-admin|facebook\.com|twitter\.com|instagram\.com|tiktok\.com|linkedin\.com|youtube\.com/watch|amazon\.|ebay\.|\.pdf$|/tag/|/category/|/page/\d+|/feed/|/rss|/atom|#comment|/reply|/share|mailto:|tel:)"
537
+ ).unwrap();
538
+ }
539
+
540
+ #[tokio::main(flavor = "multi_thread")]
541
+ async fn main() {
542
+ println!("============================================================");
543
+ println!("Rust Web Crawler v1 — Async high-throughput crawler");
544
+ println!("Target: {}", TARGET_REPO);
545
+ println!(
546
+ "Workers: {}, Chunk target: ~{:.1}GB",
547
+ NUM_WORKERS,
548
+ CHUNK_TARGET_BYTES as f64 / 1e9
549
+ );
550
+ println!("============================================================");
551
+
552
+ std::fs::create_dir_all(OUTPUT_DIR).ok();
553
+
554
+ let client = Client::builder()
555
+ .timeout(FETCH_TIMEOUT)
556
+ .pool_max_idle_per_host(20)
557
+ .pool_idle_timeout(Duration::from_secs(30))
558
+ .redirect(reqwest::redirect::Policy::limited(5))
559
+ .danger_accept_invalid_certs(true)
560
+ .tcp_keepalive(Duration::from_secs(15))
561
+ .connect_timeout(Duration::from_secs(5))
562
+ .build()
563
+ .expect("Failed to build HTTP client");
564
+
565
+ let seen_hashes: Arc<DashMap<String, ()>> = Arc::new(DashMap::new());
566
+ let domain_counts: Arc<DashMap<String, u32>> = Arc::new(DashMap::new());
567
+
568
+ // Find next chunk number
569
+ let mut chunk_num: u32 = 0;
570
+ loop {
571
+ let name = format!("crawl_rust_chunk{:04}.jsonl.gz", chunk_num);
572
+ let path = Path::new(OUTPUT_DIR).join(&name);
573
+ if !path.exists() {
574
+ break;
575
+ }
576
+ chunk_num += 1;
577
+ }
578
+
579
+ // === PHASE 1: SEED LOADING ===
580
+ let queue = Arc::new(URLQueue::new());
581
+ println!("\n=== PHASE 1: Loading seed URLs ===");
582
+ let t0 = Instant::now();
583
+
584
+ // Try loading from pre-generated mega seed file first
585
+ let seed_file = "/workspace/mega_seeds.txt";
586
+ if Path::new(seed_file).exists() {
587
+ println!("[seed] Loading from {}...", seed_file);
588
+ let content = std::fs::read_to_string(seed_file).unwrap_or_default();
589
+ let mut batch = Vec::with_capacity(10_000);
590
+ let mut loaded = 0usize;
591
+ for line in content.lines() {
592
+ let url = line.trim();
593
+ if !url.is_empty() && is_valid_url(url) {
594
+ batch.push(url.to_string());
595
+ if batch.len() >= 10_000 {
596
+ loaded += queue.push_bulk(batch).await;
597
+ batch = Vec::with_capacity(10_000);
598
+ }
599
+ }
600
+ }
601
+ if !batch.is_empty() {
602
+ loaded += queue.push_bulk(batch).await;
603
+ }
604
+ println!("[seed] Loaded {} URLs from seed file", loaded);
605
+ }
606
+
607
+ // Supplement with live sources if needed
608
+ if queue.len().await < 100_000 {
609
+ download_commoncrawl_urls(&queue, 4_000_000).await;
610
+ }
611
+ download_wikipedia_urls(&queue, 20_000).await;
612
+ download_sitemap_urls(&queue).await;
613
+ download_hn_urls(&queue).await;
614
+
615
+ println!(
616
+ "\n=== PHASE 1 complete: {} seed URLs loaded in {:.0}s ===\n",
617
+ queue.len().await,
618
+ t0.elapsed().as_secs_f64()
619
+ );
620
+
621
+ queue.shuffle().await;
622
+
623
+ // === PHASE 2: CRAWL ===
624
+ println!("=== PHASE 2: Crawling ===");
625
+
626
+ // Background queue refiller — keeps queue topped up without blocking crawl
627
+ let refill_queue = queue.clone();
628
+ let refilling = Arc::new(AtomicU64::new(0)); // 1 = refill in progress
629
+ let refilling_bg = refilling.clone();
630
+ let _refill_handle = tokio::spawn(async move {
631
+ loop {
632
+ tokio::time::sleep(Duration::from_secs(5)).await;
633
+ let qlen = refill_queue.len().await;
634
+ if qlen < 50_000 && refilling_bg.compare_exchange(0, 1, Ordering::SeqCst, Ordering::SeqCst).is_ok() {
635
+ println!("[bg-refill] Queue at {} — refilling...", qlen);
636
+ download_commoncrawl_urls(&refill_queue, 500_000).await;
637
+ download_wikipedia_urls(&refill_queue, 10_000).await;
638
+ download_sitemap_urls(&refill_queue).await;
639
+ download_hn_urls(&refill_queue).await;
640
+ println!("[bg-refill] Done, queue now at {}", refill_queue.len().await);
641
+ refilling_bg.store(0, Ordering::SeqCst);
642
+ }
643
+ }
644
+ });
645
+
646
+ loop {
647
+ if queue.len().await == 0 {
648
+ println!("Queue empty, waiting for background refiller...");
649
+ // Trigger refill if not already running
650
+ for _ in 0..30 {
651
+ tokio::time::sleep(Duration::from_secs(2)).await;
652
+ if queue.len().await > 0 {
653
+ break;
654
+ }
655
+ }
656
+ if queue.len().await == 0 {
657
+ println!("Still empty after 60s. Force-seeding...");
658
+ download_wikipedia_urls(&queue, 10_000).await;
659
+ }
660
+ continue;
661
+ }
662
+
663
+ let chunk_name = format!("crawl_rust_chunk{:04}.jsonl.gz", chunk_num);
664
+ let chunk_path_str = format!("{}/{}", OUTPUT_DIR, chunk_name);
665
+ let chunk_path = PathBuf::from(&chunk_path_str);
666
+
667
+ let file = std::fs::File::create(&chunk_path).expect("Cannot create chunk file");
668
+ let gz_writer = Arc::new(Mutex::new(GzEncoder::new(file, Compression::fast())));
669
+
670
+ let chunk_bytes = Arc::new(AtomicI64::new(0));
671
+ let chunk_docs = Arc::new(AtomicI64::new(0));
672
+ let pages_tried = Arc::new(AtomicU64::new(0));
673
+ let chunk_start = Instant::now();
674
+
675
+ println!(
676
+ "\nStarting chunk {} ({} URLs queued)...",
677
+ chunk_num,
678
+ queue.len().await
679
+ );
680
+
681
+ // Status printer task
682
+ let cb = chunk_bytes.clone();
683
+ let cd = chunk_docs.clone();
684
+ let pt = pages_tried.clone();
685
+ let ql = queue.clone();
686
+ let cn = chunk_num;
687
+ let status_handle = tokio::spawn(async move {
688
+ let mut interval = tokio::time::interval(STATUS_INTERVAL);
689
+ loop {
690
+ interval.tick().await;
691
+ let docs = cd.load(Ordering::Relaxed);
692
+ let bytes = cb.load(Ordering::Relaxed);
693
+ let tried = pt.load(Ordering::Relaxed);
694
+ let elapsed = chunk_start.elapsed().as_secs_f64();
695
+ let rate = docs as f64 / elapsed.max(1.0);
696
+ println!(
697
+ " Chunk {}: {} docs, {:.0}MB, {} queued, {:.1} docs/s, tried {}, {:.0}s elapsed",
698
+ cn,
699
+ docs,
700
+ bytes as f64 / 1e6,
701
+ ql.len().await,
702
+ rate,
703
+ tried,
704
+ elapsed
705
+ );
706
+ if bytes >= CHUNK_TARGET_BYTES {
707
+ break;
708
+ }
709
+ }
710
+ });
711
+
712
+ // Semaphore for concurrency control
713
+ let semaphore = Arc::new(Semaphore::new(NUM_WORKERS));
714
+ let mut task_handles = Vec::new();
715
+
716
+ // Feed URLs until chunk is full
717
+ while chunk_bytes.load(Ordering::Relaxed) < CHUNK_TARGET_BYTES {
718
+ let batch = queue.pop_batch(100).await;
719
+ if batch.is_empty() {
720
+ // Don't block — just wait briefly for background refiller
721
+ tokio::time::sleep(Duration::from_millis(500)).await;
722
+ if queue.len().await == 0 {
723
+ // Try a small inline refill
724
+ download_wikipedia_urls(&queue, 2_000).await;
725
+ }
726
+ continue;
727
+ }
728
+
729
+ for url in batch {
730
+ let permit = semaphore.clone().acquire_owned().await.unwrap();
731
+ let client = client.clone();
732
+ let seen_hashes = seen_hashes.clone();
733
+ let domain_counts = domain_counts.clone();
734
+ let gz_writer = gz_writer.clone();
735
+ let chunk_bytes = chunk_bytes.clone();
736
+ let chunk_docs = chunk_docs.clone();
737
+ let pages_tried = pages_tried.clone();
738
+ let queue = queue.clone();
739
+
740
+ let handle = tokio::spawn(async move {
741
+ let _permit = permit;
742
+ pages_tried.fetch_add(1, Ordering::Relaxed);
743
+
744
+ let domain = get_domain(&url);
745
+ if let Some(count) = domain_counts.get(&domain) {
746
+ if *count >= MAX_URLS_PER_DOMAIN {
747
+ return;
748
+ }
749
+ }
750
+
751
+ let (body, final_url) = match fetch_page(&client, &url).await {
752
+ Ok((b, u)) => (b, u),
753
+ Err(_) => return,
754
+ };
755
+
756
+ let text = extract_text_from_html(&body);
757
+ if text.len() < MIN_TEXT_LEN {
758
+ return;
759
+ }
760
+ let text = if text.len() > MAX_TEXT_LEN {
761
+ // Find char boundary at or before MAX_TEXT_LEN
762
+ let mut end = MAX_TEXT_LEN;
763
+ while end > 0 && !text.is_char_boundary(end) {
764
+ end -= 1;
765
+ }
766
+ text[..end].to_string()
767
+ } else {
768
+ text
769
+ };
770
+
771
+ let hash = content_hash(&text);
772
+ if seen_hashes.contains_key(&hash) {
773
+ return;
774
+ }
775
+ seen_hashes.insert(hash, ());
776
+
777
+ let doc = Document {
778
+ text,
779
+ url: final_url.clone(),
780
+ domain: domain.clone(),
781
+ timestamp: chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
782
+ source: "crawl_rust_v1".to_string(),
783
+ };
784
+ let json_bytes = match serde_json::to_vec(&doc) {
785
+ Ok(b) => b,
786
+ Err(_) => return,
787
+ };
788
+
789
+ {
790
+ let mut writer = gz_writer.lock().await;
791
+ let _ = writer.write_all(&json_bytes);
792
+ let _ = writer.write_all(b"\n");
793
+ }
794
+ chunk_bytes.fetch_add(json_bytes.len() as i64, Ordering::Relaxed);
795
+ chunk_docs.fetch_add(1, Ordering::Relaxed);
796
+
797
+ domain_counts
798
+ .entry(domain)
799
+ .and_modify(|c| *c += 1)
800
+ .or_insert(1);
801
+
802
+ // Extract and enqueue discovered links
803
+ let mut links = extract_links(&body, &final_url);
804
+ {
805
+ let mut rng = rand::thread_rng();
806
+ links.shuffle(&mut rng);
807
+ }
808
+ links.truncate(50);
809
+ if !links.is_empty() {
810
+ queue.push_bulk(links).await;
811
+ }
812
+ });
813
+ task_handles.push(handle);
814
+
815
+ // Clean up completed handles periodically
816
+ if task_handles.len() > 2000 {
817
+ let mut new_handles = Vec::with_capacity(1000);
818
+ for h in task_handles.drain(..) {
819
+ if !h.is_finished() {
820
+ new_handles.push(h);
821
+ }
822
+ }
823
+ task_handles = new_handles;
824
+ }
825
+ }
826
+ }
827
+
828
+ // Wait for all remaining tasks
829
+ for h in task_handles {
830
+ let _ = h.await;
831
+ }
832
+
833
+ status_handle.abort();
834
+
835
+ // Finalize chunk
836
+ let writer = Arc::try_unwrap(gz_writer)
837
+ .expect("All tasks should be done");
838
+ let writer = writer.into_inner();
839
+ let _ = writer.finish();
840
+
841
+ let docs = chunk_docs.load(Ordering::Relaxed);
842
+ let bytes = chunk_bytes.load(Ordering::Relaxed);
843
+ let elapsed = chunk_start.elapsed().as_secs_f64();
844
+
845
+ if docs == 0 {
846
+ println!(" No docs in chunk, cleaning up");
847
+ let _ = std::fs::remove_file(&chunk_path);
848
+ tokio::time::sleep(Duration::from_secs(300)).await;
849
+ continue;
850
+ }
851
+
852
+ let compressed_size = std::fs::metadata(&chunk_path)
853
+ .map(|m| m.len())
854
+ .unwrap_or(0);
855
+ println!(
856
+ " Chunk {} complete: {} docs, {:.0}MB raw, {:.0}MB compressed, {:.0}s, {:.1} docs/s",
857
+ chunk_num,
858
+ docs,
859
+ bytes as f64 / 1e6,
860
+ compressed_size as f64 / 1e6,
861
+ elapsed,
862
+ docs as f64 / elapsed
863
+ );
864
+
865
+ if upload_chunk(&chunk_path_str, &chunk_name) {
866
+ let _ = std::fs::remove_file(&chunk_path);
867
+ chunk_num += 1;
868
+ println!(" Total chunks uploaded: {}", chunk_num);
869
+ } else {
870
+ println!(" Upload failed, will retry chunk");
871
+ let _ = std::fs::remove_file(&chunk_path);
872
+ }
873
+ }
874
+ }