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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"bufio"
|
| 5 |
+
"compress/gzip"
|
| 6 |
+
"crypto/md5"
|
| 7 |
+
"encoding/hex"
|
| 8 |
+
"encoding/json"
|
| 9 |
+
"fmt"
|
| 10 |
+
"io"
|
| 11 |
+
"math/rand"
|
| 12 |
+
"net/http"
|
| 13 |
+
"net/url"
|
| 14 |
+
"os"
|
| 15 |
+
"os/exec"
|
| 16 |
+
"path/filepath"
|
| 17 |
+
"regexp"
|
| 18 |
+
"strings"
|
| 19 |
+
"sync"
|
| 20 |
+
"sync/atomic"
|
| 21 |
+
"time"
|
| 22 |
+
|
| 23 |
+
"golang.org/x/net/html"
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
const (
|
| 27 |
+
NumWorkers = 150
|
| 28 |
+
FetchTimeout = 10 * time.Second
|
| 29 |
+
MinTextLen = 200
|
| 30 |
+
MaxTextLen = 200000
|
| 31 |
+
MaxURLsPerDomain = 1000
|
| 32 |
+
ChunkTargetBytes = 1_200_000_000
|
| 33 |
+
MaxQueueSize = 5_000_000
|
| 34 |
+
StatusInterval = 30 * time.Second
|
| 35 |
+
HFToken = "YOUR_HF_TOKEN_HERE"
|
| 36 |
+
TargetRepo = "OpenTransformer/web-crawl-2026"
|
| 37 |
+
OutputDir = "/workspace/scraped_data_go"
|
| 38 |
+
SeedCacheDir = "/workspace/seed_cache"
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
var blockedExtensions = map[string]bool{
|
| 42 |
+
".pdf": true, ".jpg": true, ".jpeg": true, ".png": true, ".gif": true,
|
| 43 |
+
".svg": true, ".mp3": true, ".mp4": true, ".avi": true, ".mov": true,
|
| 44 |
+
".zip": true, ".tar": true, ".gz": true, ".exe": true, ".dmg": true,
|
| 45 |
+
".css": true, ".js": true, ".woff": true, ".woff2": true, ".ttf": true,
|
| 46 |
+
".ico": true, ".webp": true, ".bmp": true, ".doc": true, ".docx": true,
|
| 47 |
+
".xls": true, ".xlsx": true, ".ppt": true, ".pptx": true, ".iso": true,
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
var blockedPattern = regexp.MustCompile(
|
| 51 |
+
`(?i)(login|signup|signin|register|cart|checkout|payment|admin|wp-admin|` +
|
| 52 |
+
`facebook\.com|twitter\.com|instagram\.com|tiktok\.com|linkedin\.com|` +
|
| 53 |
+
`youtube\.com/watch|amazon\.|ebay\.|\.pdf$|/tag/|/category/|` +
|
| 54 |
+
`/page/\d+|/feed/|/rss|/atom|#comment|/reply|/share|mailto:|tel:)`)
|
| 55 |
+
|
| 56 |
+
var tagStripper = regexp.MustCompile(`<script[^>]*>[\s\S]*?</script>|<style[^>]*>[\s\S]*?</style>|<[^>]+>`)
|
| 57 |
+
var whitespaceCollapse = regexp.MustCompile(`\s+`)
|
| 58 |
+
|
| 59 |
+
var userAgents = []string{
|
| 60 |
+
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
|
| 61 |
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
|
| 62 |
+
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Safari/605.1.15",
|
| 63 |
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:123.0) Gecko/20100101 Firefox/123.0",
|
| 64 |
+
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:122.0) Gecko/20100101 Firefox/122.0",
|
| 65 |
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
type Document struct {
|
| 69 |
+
Text string `json:"text"`
|
| 70 |
+
URL string `json:"url"`
|
| 71 |
+
Domain string `json:"domain"`
|
| 72 |
+
Timestamp string `json:"timestamp"`
|
| 73 |
+
Source string `json:"source"`
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
type URLQueue struct {
|
| 77 |
+
mu sync.Mutex
|
| 78 |
+
queue []string
|
| 79 |
+
// No seen map — saves memory. Duplicate URLs are harmless since
|
| 80 |
+
// we deduplicate by content hash anyway.
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
func NewURLQueue() *URLQueue {
|
| 84 |
+
return &URLQueue{
|
| 85 |
+
queue: make([]string, 0, 100000),
|
| 86 |
+
}
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
func (q *URLQueue) Push(u string) bool {
|
| 90 |
+
q.mu.Lock()
|
| 91 |
+
defer q.mu.Unlock()
|
| 92 |
+
if len(q.queue) >= MaxQueueSize {
|
| 93 |
+
return false
|
| 94 |
+
}
|
| 95 |
+
q.queue = append(q.queue, u)
|
| 96 |
+
return true
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
func (q *URLQueue) PushBulk(urls []string) int {
|
| 100 |
+
q.mu.Lock()
|
| 101 |
+
defer q.mu.Unlock()
|
| 102 |
+
added := 0
|
| 103 |
+
for _, u := range urls {
|
| 104 |
+
if len(q.queue) < MaxQueueSize {
|
| 105 |
+
q.queue = append(q.queue, u)
|
| 106 |
+
added++
|
| 107 |
+
}
|
| 108 |
+
}
|
| 109 |
+
return added
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
func (q *URLQueue) Pop() (string, bool) {
|
| 113 |
+
q.mu.Lock()
|
| 114 |
+
defer q.mu.Unlock()
|
| 115 |
+
if len(q.queue) == 0 {
|
| 116 |
+
return "", false
|
| 117 |
+
}
|
| 118 |
+
u := q.queue[0]
|
| 119 |
+
q.queue = q.queue[1:]
|
| 120 |
+
return u, true
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
func (q *URLQueue) Len() int {
|
| 124 |
+
q.mu.Lock()
|
| 125 |
+
defer q.mu.Unlock()
|
| 126 |
+
return len(q.queue)
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
func (q *URLQueue) Shuffle() {
|
| 130 |
+
q.mu.Lock()
|
| 131 |
+
defer q.mu.Unlock()
|
| 132 |
+
rand.Shuffle(len(q.queue), func(i, j int) {
|
| 133 |
+
q.queue[i], q.queue[j] = q.queue[j], q.queue[i]
|
| 134 |
+
})
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
func isValidURL(rawURL string) bool {
|
| 138 |
+
u, err := url.Parse(rawURL)
|
| 139 |
+
if err != nil {
|
| 140 |
+
return false
|
| 141 |
+
}
|
| 142 |
+
if u.Scheme != "http" && u.Scheme != "https" {
|
| 143 |
+
return false
|
| 144 |
+
}
|
| 145 |
+
if u.Host == "" || !strings.Contains(u.Host, ".") {
|
| 146 |
+
return false
|
| 147 |
+
}
|
| 148 |
+
ext := strings.ToLower(filepath.Ext(u.Path))
|
| 149 |
+
if blockedExtensions[ext] {
|
| 150 |
+
return false
|
| 151 |
+
}
|
| 152 |
+
if blockedPattern.MatchString(rawURL) {
|
| 153 |
+
return false
|
| 154 |
+
}
|
| 155 |
+
return true
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
func getDomain(rawURL string) string {
|
| 159 |
+
u, err := url.Parse(rawURL)
|
| 160 |
+
if err != nil {
|
| 161 |
+
return ""
|
| 162 |
+
}
|
| 163 |
+
return u.Host
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
func contentHash(text string) string {
|
| 167 |
+
end := len(text)
|
| 168 |
+
if end > 500 {
|
| 169 |
+
end = 500
|
| 170 |
+
}
|
| 171 |
+
h := md5.Sum([]byte(text[:end]))
|
| 172 |
+
return hex.EncodeToString(h[:])
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
func extractText(body string) string {
|
| 176 |
+
text := tagStripper.ReplaceAllString(body, " ")
|
| 177 |
+
text = strings.ReplaceAll(text, "&", "&")
|
| 178 |
+
text = strings.ReplaceAll(text, "<", "<")
|
| 179 |
+
text = strings.ReplaceAll(text, ">", ">")
|
| 180 |
+
text = strings.ReplaceAll(text, """, "\"")
|
| 181 |
+
text = strings.ReplaceAll(text, "'", "'")
|
| 182 |
+
text = strings.ReplaceAll(text, " ", " ")
|
| 183 |
+
text = whitespaceCollapse.ReplaceAllString(text, " ")
|
| 184 |
+
text = strings.TrimSpace(text)
|
| 185 |
+
return text
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
func extractLinks(body, baseURL string) []string {
|
| 189 |
+
var links []string
|
| 190 |
+
base, err := url.Parse(baseURL)
|
| 191 |
+
if err != nil {
|
| 192 |
+
return links
|
| 193 |
+
}
|
| 194 |
+
tokenizer := html.NewTokenizer(strings.NewReader(body))
|
| 195 |
+
for {
|
| 196 |
+
tt := tokenizer.Next()
|
| 197 |
+
if tt == html.ErrorToken {
|
| 198 |
+
break
|
| 199 |
+
}
|
| 200 |
+
if tt == html.StartTagToken || tt == html.SelfClosingTagToken {
|
| 201 |
+
t := tokenizer.Token()
|
| 202 |
+
if t.Data == "a" {
|
| 203 |
+
for _, attr := range t.Attr {
|
| 204 |
+
if attr.Key == "href" {
|
| 205 |
+
href := strings.TrimSpace(attr.Val)
|
| 206 |
+
if strings.HasPrefix(href, "#") || strings.HasPrefix(href, "javascript:") {
|
| 207 |
+
continue
|
| 208 |
+
}
|
| 209 |
+
ref, err := url.Parse(href)
|
| 210 |
+
if err != nil {
|
| 211 |
+
continue
|
| 212 |
+
}
|
| 213 |
+
resolved := base.ResolveReference(ref)
|
| 214 |
+
resolved.Fragment = ""
|
| 215 |
+
full := resolved.String()
|
| 216 |
+
if isValidURL(full) {
|
| 217 |
+
links = append(links, full)
|
| 218 |
+
}
|
| 219 |
+
}
|
| 220 |
+
}
|
| 221 |
+
}
|
| 222 |
+
}
|
| 223 |
+
}
|
| 224 |
+
return links
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
func fetchPage(client *http.Client, rawURL string) (body string, finalURL string, err error) {
|
| 228 |
+
req, err := http.NewRequest("GET", rawURL, nil)
|
| 229 |
+
if err != nil {
|
| 230 |
+
return "", "", err
|
| 231 |
+
}
|
| 232 |
+
req.Header.Set("User-Agent", userAgents[rand.Intn(len(userAgents))])
|
| 233 |
+
req.Header.Set("Accept", "text/html,application/xhtml+xml")
|
| 234 |
+
req.Header.Set("Accept-Language", "en-US,en;q=0.9")
|
| 235 |
+
|
| 236 |
+
resp, err := client.Do(req)
|
| 237 |
+
if err != nil {
|
| 238 |
+
return "", "", err
|
| 239 |
+
}
|
| 240 |
+
defer resp.Body.Close()
|
| 241 |
+
|
| 242 |
+
if resp.StatusCode != 200 {
|
| 243 |
+
io.Copy(io.Discard, resp.Body)
|
| 244 |
+
return "", "", fmt.Errorf("status %d", resp.StatusCode)
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
ct := resp.Header.Get("Content-Type")
|
| 248 |
+
if !strings.Contains(ct, "text/html") && !strings.Contains(ct, "xhtml") {
|
| 249 |
+
io.Copy(io.Discard, resp.Body)
|
| 250 |
+
return "", "", fmt.Errorf("not html: %s", ct)
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
limited := io.LimitReader(resp.Body, 2*1024*1024)
|
| 254 |
+
data, err := io.ReadAll(limited)
|
| 255 |
+
if err != nil {
|
| 256 |
+
return "", "", err
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
return string(data), resp.Request.URL.String(), nil
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
// ============================================================
|
| 263 |
+
// BULK SEED LOADING — downloads millions of URLs before crawling
|
| 264 |
+
// ============================================================
|
| 265 |
+
|
| 266 |
+
// downloadCommonCrawlURLs fetches URL lists from Common Crawl's columnar index.
|
| 267 |
+
// CC publishes .gz files listing all crawled URLs per segment.
|
| 268 |
+
func downloadCommonCrawlURLs(queue *URLQueue, targetCount int) int {
|
| 269 |
+
fmt.Println("[seed] Downloading Common Crawl URL index...")
|
| 270 |
+
os.MkdirAll(SeedCacheDir, 0755)
|
| 271 |
+
|
| 272 |
+
// CC-MAIN-2024-10 cluster.idx lists pages by URL prefix
|
| 273 |
+
// We download individual WARC path listings and extract URLs
|
| 274 |
+
// Using the cdx-api to get URL samples across many domains
|
| 275 |
+
client := &http.Client{Timeout: 60 * time.Second}
|
| 276 |
+
|
| 277 |
+
added := 0
|
| 278 |
+
// Query the CC index API for URLs matching common TLDs
|
| 279 |
+
// Each query returns up to 15000 results
|
| 280 |
+
queries := []string{
|
| 281 |
+
"*.com/*", "*.org/*", "*.net/*", "*.edu/*", "*.gov/*",
|
| 282 |
+
"*.co.uk/*", "*.io/*", "*.info/*", "*.us/*", "*.ca/*",
|
| 283 |
+
"*.au/*", "*.de/*", "*.fr/*",
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
for _, q := range queries {
|
| 287 |
+
if added >= targetCount {
|
| 288 |
+
break
|
| 289 |
+
}
|
| 290 |
+
apiURL := fmt.Sprintf(
|
| 291 |
+
"https://index.commoncrawl.org/CC-MAIN-2024-10-index?url=%s&output=json&limit=15000&fl=url&filter=languages:eng",
|
| 292 |
+
url.QueryEscape(q))
|
| 293 |
+
|
| 294 |
+
resp, err := client.Get(apiURL)
|
| 295 |
+
if err != nil {
|
| 296 |
+
fmt.Printf("[seed] CC query failed for %s: %v\n", q, err)
|
| 297 |
+
continue
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
scanner := bufio.NewScanner(resp.Body)
|
| 301 |
+
scanner.Buffer(make([]byte, 1024*1024), 1024*1024)
|
| 302 |
+
batch := make([]string, 0, 10000)
|
| 303 |
+
for scanner.Scan() {
|
| 304 |
+
line := scanner.Text()
|
| 305 |
+
var rec struct {
|
| 306 |
+
URL string `json:"url"`
|
| 307 |
+
}
|
| 308 |
+
if json.Unmarshal([]byte(line), &rec) == nil && rec.URL != "" && isValidURL(rec.URL) {
|
| 309 |
+
batch = append(batch, rec.URL)
|
| 310 |
+
if len(batch) >= 10000 {
|
| 311 |
+
added += queue.PushBulk(batch)
|
| 312 |
+
batch = batch[:0]
|
| 313 |
+
}
|
| 314 |
+
}
|
| 315 |
+
}
|
| 316 |
+
resp.Body.Close()
|
| 317 |
+
if len(batch) > 0 {
|
| 318 |
+
added += queue.PushBulk(batch)
|
| 319 |
+
}
|
| 320 |
+
fmt.Printf("[seed] CC %s: total queued so far: %d\n", q, queue.Len())
|
| 321 |
+
}
|
| 322 |
+
return added
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
// downloadWikipediaURLs bulk-fetches Wikipedia article URLs via the API
|
| 326 |
+
func downloadWikipediaURLs(queue *URLQueue, count int) int {
|
| 327 |
+
fmt.Printf("[seed] Fetching %d Wikipedia URLs...\n", count)
|
| 328 |
+
client := &http.Client{Timeout: 30 * time.Second}
|
| 329 |
+
added := 0
|
| 330 |
+
batchSize := 500
|
| 331 |
+
failures := 0
|
| 332 |
+
for added < count && failures < 5 {
|
| 333 |
+
remaining := count - added
|
| 334 |
+
if remaining > batchSize {
|
| 335 |
+
remaining = batchSize
|
| 336 |
+
}
|
| 337 |
+
resp, err := client.Get(fmt.Sprintf(
|
| 338 |
+
"https://en.wikipedia.org/w/api.php?action=query&list=random&rnnamespace=0&rnlimit=%d&format=json",
|
| 339 |
+
remaining))
|
| 340 |
+
if err != nil {
|
| 341 |
+
failures++
|
| 342 |
+
time.Sleep(2 * time.Second)
|
| 343 |
+
continue
|
| 344 |
+
}
|
| 345 |
+
var data struct {
|
| 346 |
+
Query struct {
|
| 347 |
+
Random []struct {
|
| 348 |
+
Title string `json:"title"`
|
| 349 |
+
} `json:"random"`
|
| 350 |
+
} `json:"query"`
|
| 351 |
+
}
|
| 352 |
+
json.NewDecoder(resp.Body).Decode(&data)
|
| 353 |
+
resp.Body.Close()
|
| 354 |
+
|
| 355 |
+
if len(data.Query.Random) == 0 {
|
| 356 |
+
failures++
|
| 357 |
+
continue
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
batch := make([]string, 0, len(data.Query.Random))
|
| 361 |
+
for _, p := range data.Query.Random {
|
| 362 |
+
title := strings.ReplaceAll(p.Title, " ", "_")
|
| 363 |
+
batch = append(batch, "https://en.wikipedia.org/wiki/"+title)
|
| 364 |
+
}
|
| 365 |
+
n := queue.PushBulk(batch)
|
| 366 |
+
added += n
|
| 367 |
+
if n == 0 {
|
| 368 |
+
failures++
|
| 369 |
+
} else {
|
| 370 |
+
failures = 0
|
| 371 |
+
}
|
| 372 |
+
fmt.Printf("[seed] Wikipedia: %d URLs added (total %d)\n", n, added)
|
| 373 |
+
}
|
| 374 |
+
return added
|
| 375 |
+
}
|
| 376 |
+
|
| 377 |
+
// downloadSitemapURLs fetches sitemap.xml from major sites and extracts URLs
|
| 378 |
+
func downloadSitemapURLs(queue *URLQueue) int {
|
| 379 |
+
fmt.Println("[seed] Fetching sitemaps from major sites...")
|
| 380 |
+
client := &http.Client{Timeout: 15 * time.Second}
|
| 381 |
+
|
| 382 |
+
sitemapSites := []string{
|
| 383 |
+
"https://www.reuters.com/arc/outboundfeeds/sitemap-index/?outputType=xml",
|
| 384 |
+
"https://www.bbc.com/sitemaps/https-sitemap-com-news-1.xml",
|
| 385 |
+
"https://www.theguardian.com/sitemaps/news.xml",
|
| 386 |
+
"https://www.npr.org/sitemap.xml",
|
| 387 |
+
"https://arstechnica.com/sitemap.xml",
|
| 388 |
+
"https://www.wired.com/sitemap.xml",
|
| 389 |
+
"https://www.theatlantic.com/sitemap.xml",
|
| 390 |
+
"https://www.vox.com/sitemaps/entries/1",
|
| 391 |
+
"https://www.nature.com/sitemap.xml",
|
| 392 |
+
"https://phys.org/sitemap.xml",
|
| 393 |
+
"https://www.scientificamerican.com/sitemap.xml",
|
| 394 |
+
"https://www.smithsonianmag.com/sitemap.xml",
|
| 395 |
+
"https://www.britannica.com/sitemap.xml",
|
| 396 |
+
"https://www.healthline.com/sitemap.xml",
|
| 397 |
+
"https://www.investopedia.com/sitemap.xml",
|
| 398 |
+
"https://www.geeksforgeeks.org/sitemap.xml",
|
| 399 |
+
"https://realpython.com/sitemap.xml",
|
| 400 |
+
"https://www.freecodecamp.org/news/sitemap.xml",
|
| 401 |
+
"https://hackernoon.com/sitemap.xml",
|
| 402 |
+
"https://dev.to/sitemap.xml",
|
| 403 |
+
"https://www.history.com/sitemap.xml",
|
| 404 |
+
"https://www.livescience.com/sitemap.xml",
|
| 405 |
+
"https://www.space.com/sitemap.xml",
|
| 406 |
+
"https://www.sciencedaily.com/sitemap.xml",
|
| 407 |
+
"https://www.psychologytoday.com/sitemap.xml",
|
| 408 |
+
"https://www.mayoclinic.org/sitemap.xml",
|
| 409 |
+
"https://medlineplus.gov/sitemap.xml",
|
| 410 |
+
"https://plato.stanford.edu/sitemap.xml",
|
| 411 |
+
"https://www.brookings.edu/sitemap.xml",
|
| 412 |
+
"https://www.rand.org/sitemap.xml",
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
added := 0
|
| 416 |
+
locRe := regexp.MustCompile(`<loc>([^<]+)</loc>`)
|
| 417 |
+
|
| 418 |
+
for _, sitemapURL := range sitemapSites {
|
| 419 |
+
resp, err := client.Get(sitemapURL)
|
| 420 |
+
if err != nil {
|
| 421 |
+
continue
|
| 422 |
+
}
|
| 423 |
+
// Only read top-level sitemap (2MB max) — skip sub-sitemaps to save memory
|
| 424 |
+
body, err := io.ReadAll(io.LimitReader(resp.Body, 2*1024*1024))
|
| 425 |
+
resp.Body.Close()
|
| 426 |
+
if err != nil {
|
| 427 |
+
continue
|
| 428 |
+
}
|
| 429 |
+
|
| 430 |
+
matches := locRe.FindAllSubmatch(body, -1)
|
| 431 |
+
batch := make([]string, 0, len(matches))
|
| 432 |
+
for _, m := range matches {
|
| 433 |
+
u := string(m[1])
|
| 434 |
+
if isValidURL(u) && !strings.HasSuffix(u, ".xml") && !strings.HasSuffix(u, ".xml.gz") {
|
| 435 |
+
batch = append(batch, u)
|
| 436 |
+
}
|
| 437 |
+
}
|
| 438 |
+
n := queue.PushBulk(batch)
|
| 439 |
+
added += n
|
| 440 |
+
if n > 0 {
|
| 441 |
+
fmt.Printf("[seed] Sitemap %s: +%d URLs\n", getDomain(sitemapURL), n)
|
| 442 |
+
}
|
| 443 |
+
}
|
| 444 |
+
fmt.Printf("[seed] Sitemaps total: %d URLs added\n", added)
|
| 445 |
+
return added
|
| 446 |
+
}
|
| 447 |
+
|
| 448 |
+
func getHNURLs(n int) []string {
|
| 449 |
+
var urls []string
|
| 450 |
+
client := &http.Client{Timeout: 10 * time.Second}
|
| 451 |
+
for _, endpoint := range []string{"topstories", "newstories", "beststories"} {
|
| 452 |
+
resp, err := client.Get("https://hacker-news.firebaseio.com/v0/" + endpoint + ".json")
|
| 453 |
+
if err != nil {
|
| 454 |
+
continue
|
| 455 |
+
}
|
| 456 |
+
var ids []int
|
| 457 |
+
json.NewDecoder(resp.Body).Decode(&ids)
|
| 458 |
+
resp.Body.Close()
|
| 459 |
+
if len(ids) > n {
|
| 460 |
+
ids = ids[:n]
|
| 461 |
+
}
|
| 462 |
+
for _, id := range ids {
|
| 463 |
+
itemResp, err := client.Get(fmt.Sprintf("https://hacker-news.firebaseio.com/v0/item/%d.json", id))
|
| 464 |
+
if err != nil {
|
| 465 |
+
continue
|
| 466 |
+
}
|
| 467 |
+
var item struct {
|
| 468 |
+
URL string `json:"url"`
|
| 469 |
+
}
|
| 470 |
+
json.NewDecoder(itemResp.Body).Decode(&item)
|
| 471 |
+
itemResp.Body.Close()
|
| 472 |
+
if item.URL != "" {
|
| 473 |
+
urls = append(urls, item.URL)
|
| 474 |
+
}
|
| 475 |
+
}
|
| 476 |
+
}
|
| 477 |
+
return urls
|
| 478 |
+
}
|
| 479 |
+
|
| 480 |
+
func uploadChunk(filepath, remoteName string) bool {
|
| 481 |
+
cmd := exec.Command("python3", "-c", fmt.Sprintf(`
|
| 482 |
+
from huggingface_hub import HfApi
|
| 483 |
+
api = HfApi(token="%s")
|
| 484 |
+
api.upload_file(path_or_fileobj="%s", path_in_repo="data/%s", repo_id="%s", repo_type="dataset")
|
| 485 |
+
print("OK")
|
| 486 |
+
`, HFToken, filepath, remoteName, TargetRepo))
|
| 487 |
+
out, err := cmd.CombinedOutput()
|
| 488 |
+
if err != nil {
|
| 489 |
+
fmt.Printf(" Upload failed: %s\n%s\n", err, string(out))
|
| 490 |
+
return false
|
| 491 |
+
}
|
| 492 |
+
fmt.Printf(" Uploaded %s\n", remoteName)
|
| 493 |
+
return true
|
| 494 |
+
}
|
| 495 |
+
|
| 496 |
+
func main() {
|
| 497 |
+
fmt.Println("============================================================")
|
| 498 |
+
fmt.Println("Go Web Crawler v2 — Bulk-seeded high-throughput crawler")
|
| 499 |
+
fmt.Printf("Target: %s\n", TargetRepo)
|
| 500 |
+
fmt.Printf("Workers: %d, Chunk target: ~%.1fGB\n", NumWorkers, float64(ChunkTargetBytes)/1e9)
|
| 501 |
+
fmt.Println("============================================================")
|
| 502 |
+
|
| 503 |
+
os.MkdirAll(OutputDir, 0755)
|
| 504 |
+
|
| 505 |
+
// Use connection pooling with higher limits
|
| 506 |
+
transport := &http.Transport{
|
| 507 |
+
MaxIdleConns: 300,
|
| 508 |
+
MaxIdleConnsPerHost: 10,
|
| 509 |
+
IdleConnTimeout: 30 * time.Second,
|
| 510 |
+
}
|
| 511 |
+
client := &http.Client{
|
| 512 |
+
Timeout: FetchTimeout,
|
| 513 |
+
Transport: transport,
|
| 514 |
+
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
| 515 |
+
if len(via) >= 5 {
|
| 516 |
+
return fmt.Errorf("too many redirects")
|
| 517 |
+
}
|
| 518 |
+
return nil
|
| 519 |
+
},
|
| 520 |
+
}
|
| 521 |
+
|
| 522 |
+
seenHashes := sync.Map{}
|
| 523 |
+
domainCounts := sync.Map{}
|
| 524 |
+
|
| 525 |
+
chunkNum := 0
|
| 526 |
+
for {
|
| 527 |
+
name := fmt.Sprintf("crawl_go_chunk%04d.jsonl.gz", chunkNum)
|
| 528 |
+
if _, err := os.Stat(filepath.Join(OutputDir, name)); os.IsNotExist(err) {
|
| 529 |
+
break
|
| 530 |
+
}
|
| 531 |
+
chunkNum++
|
| 532 |
+
}
|
| 533 |
+
|
| 534 |
+
// ============================================================
|
| 535 |
+
// PHASE 1: BULK SEED LOADING — fill queue with millions of URLs
|
| 536 |
+
// ============================================================
|
| 537 |
+
queue := NewURLQueue()
|
| 538 |
+
|
| 539 |
+
fmt.Println("\n=== PHASE 1: Loading seed URLs ===")
|
| 540 |
+
t0 := time.Now()
|
| 541 |
+
|
| 542 |
+
// 1. Common Crawl index — millions of known-good English URLs
|
| 543 |
+
downloadCommonCrawlURLs(queue, 2_000_000)
|
| 544 |
+
|
| 545 |
+
// 2. Wikipedia — 10k random articles (high quality, lots of outlinks)
|
| 546 |
+
downloadWikipediaURLs(queue, 10000)
|
| 547 |
+
|
| 548 |
+
// 3. Sitemaps from major content sites
|
| 549 |
+
downloadSitemapURLs(queue)
|
| 550 |
+
|
| 551 |
+
// 4. HN links
|
| 552 |
+
for _, u := range getHNURLs(100) {
|
| 553 |
+
queue.Push(u)
|
| 554 |
+
}
|
| 555 |
+
|
| 556 |
+
elapsed := time.Since(t0)
|
| 557 |
+
fmt.Printf("\n=== PHASE 1 complete: %d seed URLs loaded in %.0f seconds ===\n\n", queue.Len(), elapsed.Seconds())
|
| 558 |
+
|
| 559 |
+
// Shuffle the queue for domain diversity
|
| 560 |
+
queue.Shuffle()
|
| 561 |
+
|
| 562 |
+
// ============================================================
|
| 563 |
+
// PHASE 2: CRAWL — process URLs and discover new ones
|
| 564 |
+
// ============================================================
|
| 565 |
+
fmt.Println("=== PHASE 2: Crawling ===")
|
| 566 |
+
|
| 567 |
+
for {
|
| 568 |
+
if queue.Len() == 0 {
|
| 569 |
+
fmt.Println("Queue exhausted. Reloading seeds...")
|
| 570 |
+
downloadCommonCrawlURLs(queue, 500_000)
|
| 571 |
+
downloadWikipediaURLs(queue, 5000)
|
| 572 |
+
downloadSitemapURLs(queue)
|
| 573 |
+
if queue.Len() == 0 {
|
| 574 |
+
fmt.Println("Cannot refill queue. Waiting 5 min...")
|
| 575 |
+
time.Sleep(5 * time.Minute)
|
| 576 |
+
continue
|
| 577 |
+
}
|
| 578 |
+
}
|
| 579 |
+
|
| 580 |
+
chunkName := fmt.Sprintf("crawl_go_chunk%04d.jsonl.gz", chunkNum)
|
| 581 |
+
chunkPath := filepath.Join(OutputDir, chunkName)
|
| 582 |
+
|
| 583 |
+
f, err := os.Create(chunkPath)
|
| 584 |
+
if err != nil {
|
| 585 |
+
fmt.Printf("Error creating chunk: %v\n", err)
|
| 586 |
+
time.Sleep(30 * time.Second)
|
| 587 |
+
continue
|
| 588 |
+
}
|
| 589 |
+
gzw := gzip.NewWriter(f)
|
| 590 |
+
|
| 591 |
+
var writeMu sync.Mutex
|
| 592 |
+
var chunkBytes int64
|
| 593 |
+
var chunkDocs int64
|
| 594 |
+
var pagesTried int64
|
| 595 |
+
chunkStart := time.Now()
|
| 596 |
+
|
| 597 |
+
fmt.Printf("\nStarting chunk %d (%d URLs queued)...\n", chunkNum, queue.Len())
|
| 598 |
+
|
| 599 |
+
// Status printer
|
| 600 |
+
stopStatus := make(chan struct{})
|
| 601 |
+
go func() {
|
| 602 |
+
ticker := time.NewTicker(StatusInterval)
|
| 603 |
+
defer ticker.Stop()
|
| 604 |
+
for {
|
| 605 |
+
select {
|
| 606 |
+
case <-ticker.C:
|
| 607 |
+
docs := atomic.LoadInt64(&chunkDocs)
|
| 608 |
+
bytes := atomic.LoadInt64(&chunkBytes)
|
| 609 |
+
tried := atomic.LoadInt64(&pagesTried)
|
| 610 |
+
elapsed := time.Since(chunkStart).Seconds()
|
| 611 |
+
rate := float64(docs) / elapsed
|
| 612 |
+
fmt.Printf(" Chunk %d: %d docs, %.0fMB, %d queued, %.1f docs/s, tried %d, %.0fs elapsed\n",
|
| 613 |
+
chunkNum, docs, float64(bytes)/1e6, queue.Len(), rate, tried, elapsed)
|
| 614 |
+
case <-stopStatus:
|
| 615 |
+
return
|
| 616 |
+
}
|
| 617 |
+
}
|
| 618 |
+
}()
|
| 619 |
+
|
| 620 |
+
// Worker pool
|
| 621 |
+
urlChan := make(chan string, NumWorkers*4)
|
| 622 |
+
var wg sync.WaitGroup
|
| 623 |
+
|
| 624 |
+
for i := 0; i < NumWorkers; i++ {
|
| 625 |
+
wg.Add(1)
|
| 626 |
+
go func() {
|
| 627 |
+
defer wg.Done()
|
| 628 |
+
for rawURL := range urlChan {
|
| 629 |
+
atomic.AddInt64(&pagesTried, 1)
|
| 630 |
+
|
| 631 |
+
domain := getDomain(rawURL)
|
| 632 |
+
if v, ok := domainCounts.Load(domain); ok && v.(int) >= MaxURLsPerDomain {
|
| 633 |
+
continue
|
| 634 |
+
}
|
| 635 |
+
|
| 636 |
+
body, finalURL, err := fetchPage(client, rawURL)
|
| 637 |
+
if err != nil {
|
| 638 |
+
continue
|
| 639 |
+
}
|
| 640 |
+
|
| 641 |
+
text := extractText(body)
|
| 642 |
+
if len(text) < MinTextLen {
|
| 643 |
+
continue
|
| 644 |
+
}
|
| 645 |
+
if len(text) > MaxTextLen {
|
| 646 |
+
text = text[:MaxTextLen]
|
| 647 |
+
}
|
| 648 |
+
|
| 649 |
+
h := contentHash(text)
|
| 650 |
+
if _, loaded := seenHashes.LoadOrStore(h, true); loaded {
|
| 651 |
+
continue
|
| 652 |
+
}
|
| 653 |
+
|
| 654 |
+
doc := Document{
|
| 655 |
+
Text: text,
|
| 656 |
+
URL: finalURL,
|
| 657 |
+
Domain: domain,
|
| 658 |
+
Timestamp: time.Now().UTC().Format("2006-01-02T15:04:05Z"),
|
| 659 |
+
Source: "crawl_go_v2",
|
| 660 |
+
}
|
| 661 |
+
jsonBytes, err := json.Marshal(doc)
|
| 662 |
+
if err != nil {
|
| 663 |
+
continue
|
| 664 |
+
}
|
| 665 |
+
|
| 666 |
+
writeMu.Lock()
|
| 667 |
+
gzw.Write(jsonBytes)
|
| 668 |
+
gzw.Write([]byte("\n"))
|
| 669 |
+
atomic.AddInt64(&chunkBytes, int64(len(jsonBytes)))
|
| 670 |
+
atomic.AddInt64(&chunkDocs, 1)
|
| 671 |
+
writeMu.Unlock()
|
| 672 |
+
|
| 673 |
+
if v, ok := domainCounts.Load(domain); ok {
|
| 674 |
+
domainCounts.Store(domain, v.(int)+1)
|
| 675 |
+
} else {
|
| 676 |
+
domainCounts.Store(domain, 1)
|
| 677 |
+
}
|
| 678 |
+
|
| 679 |
+
// Discover new links from crawled pages
|
| 680 |
+
links := extractLinks(body, finalURL)
|
| 681 |
+
rand.Shuffle(len(links), func(i, j int) { links[i], links[j] = links[j], links[i] })
|
| 682 |
+
maxLinks := 50
|
| 683 |
+
if len(links) > maxLinks {
|
| 684 |
+
links = links[:maxLinks]
|
| 685 |
+
}
|
| 686 |
+
queue.PushBulk(links)
|
| 687 |
+
}
|
| 688 |
+
}()
|
| 689 |
+
}
|
| 690 |
+
|
| 691 |
+
// Feed URLs to workers
|
| 692 |
+
for atomic.LoadInt64(&chunkBytes) < ChunkTargetBytes {
|
| 693 |
+
u, ok := queue.Pop()
|
| 694 |
+
if !ok {
|
| 695 |
+
// Queue depleted mid-chunk, refill inline
|
| 696 |
+
fmt.Println(" Queue low, fetching more Wikipedia URLs...")
|
| 697 |
+
downloadWikipediaURLs(queue, 5000)
|
| 698 |
+
if queue.Len() == 0 {
|
| 699 |
+
break
|
| 700 |
+
}
|
| 701 |
+
continue
|
| 702 |
+
}
|
| 703 |
+
urlChan <- u
|
| 704 |
+
}
|
| 705 |
+
close(urlChan)
|
| 706 |
+
wg.Wait()
|
| 707 |
+
close(stopStatus)
|
| 708 |
+
|
| 709 |
+
gzw.Close()
|
| 710 |
+
f.Close()
|
| 711 |
+
|
| 712 |
+
docs := atomic.LoadInt64(&chunkDocs)
|
| 713 |
+
bytes := atomic.LoadInt64(&chunkBytes)
|
| 714 |
+
chunkElapsed := time.Since(chunkStart).Seconds()
|
| 715 |
+
|
| 716 |
+
if docs == 0 {
|
| 717 |
+
fmt.Println(" No docs in chunk, cleaning up")
|
| 718 |
+
os.Remove(chunkPath)
|
| 719 |
+
time.Sleep(5 * time.Minute)
|
| 720 |
+
continue
|
| 721 |
+
}
|
| 722 |
+
|
| 723 |
+
fi, _ := os.Stat(chunkPath)
|
| 724 |
+
compressedSize := fi.Size()
|
| 725 |
+
fmt.Printf(" Chunk %d complete: %d docs, %.0fMB raw, %.0fMB compressed, %.0fs, %.1f docs/s\n",
|
| 726 |
+
chunkNum, docs, float64(bytes)/1e6, float64(compressedSize)/1e6,
|
| 727 |
+
chunkElapsed, float64(docs)/chunkElapsed)
|
| 728 |
+
|
| 729 |
+
if uploadChunk(chunkPath, chunkName) {
|
| 730 |
+
os.Remove(chunkPath)
|
| 731 |
+
chunkNum++
|
| 732 |
+
fmt.Printf(" Total chunks uploaded: %d\n", chunkNum)
|
| 733 |
+
} else {
|
| 734 |
+
fmt.Println(" Upload failed, will retry chunk")
|
| 735 |
+
os.Remove(chunkPath)
|
| 736 |
+
}
|
| 737 |
+
}
|
| 738 |
+
}
|