OpenTransformer commited on
Commit
a13d04f
·
verified ·
1 Parent(s): a52c9b9

Upload code/turbo_crawler.go with huggingface_hub

Browse files
Files changed (1) hide show
  1. code/turbo_crawler.go +191 -0
code/turbo_crawler.go ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "bufio"
5
+ "crypto/md5"
6
+ "encoding/hex"
7
+ "encoding/json"
8
+ "fmt"
9
+ "io"
10
+ "io/ioutil"
11
+ "net/http"
12
+ "net/url"
13
+ "os"
14
+ "regexp"
15
+ "strings"
16
+ "sync"
17
+ "sync/atomic"
18
+ "time"
19
+ )
20
+
21
+ type Record struct {
22
+ URL string `json:"url"`
23
+ Text string `json:"text"`
24
+ TS string `json:"ts"`
25
+ }
26
+
27
+ var (
28
+ visited = make(map[string]bool)
29
+ visitedMu sync.RWMutex
30
+ queue = make(chan string, 1000000)
31
+ stats struct {
32
+ pages, bytes, errors int64
33
+ }
34
+ client = &http.Client{
35
+ Timeout: 5 * time.Second,
36
+ Transport: &http.Transport{
37
+ MaxIdleConns: 1000,
38
+ MaxIdleConnsPerHost: 50,
39
+ IdleConnTimeout: 30 * time.Second,
40
+ },
41
+ }
42
+ linkRe = regexp.MustCompile(`href=["']([^"']+)["']`)
43
+ scriptRe = regexp.MustCompile(`(?is)<script[^>]*>.*?</script>|<style[^>]*>.*?</style>`)
44
+ tagRe = regexp.MustCompile(`<[^>]+>`)
45
+ spaceRe = regexp.MustCompile(`\s+`)
46
+ )
47
+
48
+ func hash(s string) string {
49
+ h := md5.Sum([]byte(s))
50
+ return hex.EncodeToString(h[:8])
51
+ }
52
+
53
+ func extractText(html string) string {
54
+ text := scriptRe.ReplaceAllString(html, " ")
55
+ text = tagRe.ReplaceAllString(text, " ")
56
+ text = spaceRe.ReplaceAllString(text, " ")
57
+ text = strings.TrimSpace(text)
58
+ if len(text) > 50000 {
59
+ text = text[:50000]
60
+ }
61
+ return text
62
+ }
63
+
64
+ func extractLinks(html, baseURL string) []string {
65
+ base, err := url.Parse(baseURL)
66
+ if err != nil {
67
+ return nil
68
+ }
69
+ var links []string
70
+ matches := linkRe.FindAllStringSubmatch(html, 100)
71
+ for _, m := range matches {
72
+ if len(m) > 1 {
73
+ href := m[1]
74
+ if u, err := url.Parse(href); err == nil {
75
+ resolved := base.ResolveReference(u)
76
+ if resolved.Scheme == "http" || resolved.Scheme == "https" {
77
+ links = append(links, resolved.String())
78
+ }
79
+ }
80
+ }
81
+ }
82
+ return links
83
+ }
84
+
85
+ func worker(id int, output chan<- Record) {
86
+ for urlStr := range queue {
87
+ h := hash(urlStr)
88
+ visitedMu.RLock()
89
+ seen := visited[h]
90
+ visitedMu.RUnlock()
91
+ if seen {
92
+ continue
93
+ }
94
+ visitedMu.Lock()
95
+ visited[h] = true
96
+ visitedMu.Unlock()
97
+
98
+ resp, err := client.Get(urlStr)
99
+ if err != nil {
100
+ atomic.AddInt64(&stats.errors, 1)
101
+ continue
102
+ }
103
+
104
+ ct := resp.Header.Get("Content-Type")
105
+ if resp.StatusCode != 200 || !strings.Contains(ct, "text/html") {
106
+ resp.Body.Close()
107
+ atomic.AddInt64(&stats.errors, 1)
108
+ continue
109
+ }
110
+
111
+ body, _ := ioutil.ReadAll(io.LimitReader(resp.Body, 1<<20))
112
+ resp.Body.Close()
113
+ html := string(body)
114
+
115
+ text := extractText(html)
116
+ if len(text) > 200 {
117
+ output <- Record{URL: urlStr, Text: text, TS: time.Now().UTC().Format("2006-01-02T15:04:05")}
118
+ atomic.AddInt64(&stats.pages, 1)
119
+ atomic.AddInt64(&stats.bytes, int64(len(text)))
120
+ }
121
+
122
+ for _, link := range extractLinks(html, urlStr) {
123
+ select {
124
+ case queue <- link:
125
+ default:
126
+ }
127
+ }
128
+ }
129
+ }
130
+
131
+ func main() {
132
+ seeds := []string{
133
+ "https://en.wikipedia.org/wiki/Main_Page",
134
+ "https://en.wikipedia.org/wiki/Special:Random",
135
+ "https://news.ycombinator.com/",
136
+ "https://www.reddit.com/r/all/",
137
+ "https://www.reddit.com/r/programming/",
138
+ "https://stackoverflow.com/questions",
139
+ "https://medium.com/",
140
+ "https://dev.to/",
141
+ }
142
+
143
+ for _, s := range seeds {
144
+ queue <- s
145
+ }
146
+
147
+ os.MkdirAll("/workspace/go_crawl", 0755)
148
+ outPath := fmt.Sprintf("/workspace/go_crawl/crawl_%s.jsonl", time.Now().Format("20060102_150405"))
149
+ f, _ := os.Create(outPath)
150
+ defer f.Close()
151
+ w := bufio.NewWriter(f)
152
+ defer w.Flush()
153
+
154
+ output := make(chan Record, 10000)
155
+
156
+ go func() {
157
+ for rec := range output {
158
+ data, _ := json.Marshal(rec)
159
+ w.Write(data)
160
+ w.WriteByte('\n')
161
+ }
162
+ }()
163
+
164
+ start := time.Now()
165
+ go func() {
166
+ for {
167
+ time.Sleep(10 * time.Second)
168
+ elapsed := time.Since(start).Minutes()
169
+ if elapsed > 0 {
170
+ p := atomic.LoadInt64(&stats.pages)
171
+ b := atomic.LoadInt64(&stats.bytes)
172
+ e := atomic.LoadInt64(&stats.errors)
173
+ fmt.Printf("[%s] %d pgs | %.0fMB | %.1fMB/min | Q:%d | Err:%d\n",
174
+ time.Now().Format("15:04:05"), p, float64(b)/1024/1024, float64(b)/1024/1024/elapsed, len(queue), e)
175
+ }
176
+ }
177
+ }()
178
+
179
+ fmt.Printf("=== GO STDLIB CRAWLER ===\nWorkers: 1000\nOutput: %s\n\n", outPath)
180
+
181
+ var wg sync.WaitGroup
182
+ for i := 0; i < 1000; i++ {
183
+ wg.Add(1)
184
+ go func(id int) {
185
+ defer wg.Done()
186
+ worker(id, output)
187
+ }(i)
188
+ }
189
+ wg.Wait()
190
+ close(output)
191
+ }