OpenTransformer commited on
Commit
97dfee2
·
verified ·
1 Parent(s): ac32758

Upload image_crawler.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. image_crawler.py +525 -0
image_crawler.py ADDED
@@ -0,0 +1,525 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ OpenTransformers Image Crawler v1.0
4
+ Grabby hands for multimodal training data.
5
+
6
+ Grabs images + context (alt text, captions, surrounding text)
7
+ Perfect for vision-language model training.
8
+
9
+ Usage:
10
+ python image_crawler.py --seeds seeds.txt --output /workspace/images --max-gb 10
11
+ python image_crawler.py --seed "https://unsplash.com" --min-size 256 --workers 50
12
+ """
13
+
14
+ import asyncio
15
+ import aiohttp
16
+ import argparse
17
+ import hashlib
18
+ import json
19
+ import os
20
+ import re
21
+ import time
22
+ import random
23
+ import base64
24
+ from dataclasses import dataclass, asdict
25
+ from datetime import datetime
26
+ from pathlib import Path
27
+ from typing import Optional, Set, Dict, List, Tuple
28
+ from urllib.parse import urljoin, urlparse
29
+ from collections import defaultdict
30
+ import struct
31
+ import io
32
+
33
+ # ============= IMAGE UTILITIES =============
34
+
35
+ def get_image_size_from_header(data: bytes) -> Tuple[int, int]:
36
+ """Get image dimensions without downloading full image"""
37
+ if len(data) < 24:
38
+ return (0, 0)
39
+
40
+ # PNG
41
+ if data[:8] == b'\x89PNG\r\n\x1a\n':
42
+ if data[12:16] == b'IHDR':
43
+ w = struct.unpack('>I', data[16:20])[0]
44
+ h = struct.unpack('>I', data[20:24])[0]
45
+ return (w, h)
46
+
47
+ # JPEG
48
+ if data[:2] == b'\xff\xd8':
49
+ try:
50
+ i = 2
51
+ while i < len(data) - 8:
52
+ if data[i] != 0xff:
53
+ i += 1
54
+ continue
55
+ marker = data[i+1]
56
+ if marker in (0xc0, 0xc1, 0xc2): # SOF markers
57
+ h = struct.unpack('>H', data[i+5:i+7])[0]
58
+ w = struct.unpack('>H', data[i+7:i+9])[0]
59
+ return (w, h)
60
+ elif marker == 0xd9: # EOI
61
+ break
62
+ elif marker in (0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0x01):
63
+ i += 2
64
+ else:
65
+ length = struct.unpack('>H', data[i+2:i+4])[0]
66
+ i += 2 + length
67
+ except:
68
+ pass
69
+
70
+ # GIF
71
+ if data[:6] in (b'GIF87a', b'GIF89a'):
72
+ w = struct.unpack('<H', data[6:8])[0]
73
+ h = struct.unpack('<H', data[8:10])[0]
74
+ return (w, h)
75
+
76
+ # WebP
77
+ if data[:4] == b'RIFF' and data[8:12] == b'WEBP':
78
+ if data[12:16] == b'VP8 ':
79
+ w = struct.unpack('<H', data[26:28])[0] & 0x3fff
80
+ h = struct.unpack('<H', data[28:30])[0] & 0x3fff
81
+ return (w, h)
82
+ elif data[12:16] == b'VP8L':
83
+ bits = struct.unpack('<I', data[21:25])[0]
84
+ w = (bits & 0x3fff) + 1
85
+ h = ((bits >> 14) & 0x3fff) + 1
86
+ return (w, h)
87
+
88
+ return (0, 0)
89
+
90
+
91
+ def extract_images_from_html(html: str, base_url: str) -> List[Dict]:
92
+ """Extract all images with context from HTML"""
93
+ images = []
94
+
95
+ # Standard img tags
96
+ for match in re.finditer(
97
+ r'<img[^>]+src=["\']([^"\']+)["\'][^>]*>',
98
+ html, re.I | re.DOTALL
99
+ ):
100
+ full_tag = match.group(0)
101
+ src = match.group(1)
102
+
103
+ if src.startswith('data:'):
104
+ continue
105
+
106
+ # Get alt text
107
+ alt_match = re.search(r'alt=["\']([^"\']*)["\']', full_tag, re.I)
108
+ alt = alt_match.group(1) if alt_match else ""
109
+
110
+ # Get title
111
+ title_match = re.search(r'title=["\']([^"\']*)["\']', full_tag, re.I)
112
+ title = title_match.group(1) if title_match else ""
113
+
114
+ # Get srcset for higher res
115
+ srcset_match = re.search(r'srcset=["\']([^"\']+)["\']', full_tag, re.I)
116
+ srcset = srcset_match.group(1) if srcset_match else ""
117
+
118
+ # Parse srcset for best resolution
119
+ best_src = src
120
+ if srcset:
121
+ best_width = 0
122
+ for item in srcset.split(','):
123
+ parts = item.strip().split()
124
+ if len(parts) >= 2:
125
+ url = parts[0]
126
+ descriptor = parts[1]
127
+ if descriptor.endswith('w'):
128
+ try:
129
+ width = int(descriptor[:-1])
130
+ if width > best_width:
131
+ best_width = width
132
+ best_src = url
133
+ except:
134
+ pass
135
+
136
+ # Get surrounding text (50 chars before/after)
137
+ start = max(0, match.start() - 200)
138
+ end = min(len(html), match.end() + 200)
139
+ context = re.sub(r'<[^>]+>', ' ', html[start:end])
140
+ context = re.sub(r'\s+', ' ', context).strip()
141
+
142
+ try:
143
+ absolute_url = urljoin(base_url, best_src)
144
+ if absolute_url.startswith(('http://', 'https://')):
145
+ images.append({
146
+ 'url': absolute_url,
147
+ 'alt': alt,
148
+ 'title': title,
149
+ 'context': context[:500]
150
+ })
151
+ except:
152
+ pass
153
+
154
+ # Also grab og:image and twitter:image
155
+ for meta_prop in ['og:image', 'twitter:image']:
156
+ match = re.search(
157
+ f'<meta[^>]+(?:property|name)=["\'{meta_prop}["\'][^>]+content=["\']([^"\']+)["\']',
158
+ html, re.I
159
+ )
160
+ if not match:
161
+ match = re.search(
162
+ f'<meta[^>]+content=["\']([^"\']+)["\'][^>]+(?:property|name)=["\'{meta_prop}["\']',
163
+ html, re.I
164
+ )
165
+ if match:
166
+ src = match.group(1)
167
+ try:
168
+ absolute_url = urljoin(base_url, src)
169
+ if absolute_url.startswith(('http://', 'https://')):
170
+ images.append({
171
+ 'url': absolute_url,
172
+ 'alt': f'[{meta_prop}]',
173
+ 'title': '',
174
+ 'context': ''
175
+ })
176
+ except:
177
+ pass
178
+
179
+ return images
180
+
181
+
182
+ def extract_links(html: str, base_url: str) -> Set[str]:
183
+ """Extract page links for crawling"""
184
+ links = set()
185
+ for match in re.finditer(r'href=["\']([^"\']+)["\']', html, re.I):
186
+ href = match.group(1)
187
+ if href.startswith(('#', 'javascript:', 'mailto:', 'tel:', 'data:')):
188
+ continue
189
+ try:
190
+ absolute = urljoin(base_url, href)
191
+ if absolute.startswith(('http://', 'https://')):
192
+ absolute = absolute.split('#')[0]
193
+ if len(absolute) < 500:
194
+ links.add(absolute)
195
+ except:
196
+ pass
197
+ return links
198
+
199
+
200
+ def get_domain(url: str) -> str:
201
+ try:
202
+ return urlparse(url).netloc.lower()
203
+ except:
204
+ return ""
205
+
206
+
207
+ # ============= DATA STRUCTURES =============
208
+
209
+ @dataclass
210
+ class CrawledImage:
211
+ url: str
212
+ source_page: str
213
+ domain: str
214
+ timestamp: str
215
+ alt: str
216
+ title: str
217
+ context: str
218
+ width: int
219
+ height: int
220
+ format: str
221
+ size_bytes: int
222
+ hash: str
223
+ # base64 data stored separately or inline depending on config
224
+
225
+
226
+ class Stats:
227
+ def __init__(self):
228
+ self.pages = 0
229
+ self.images = 0
230
+ self.bytes = 0
231
+ self.skipped_small = 0
232
+ self.skipped_dupe = 0
233
+ self.errors = 0
234
+ self.start = time.time()
235
+ self.by_domain: Dict[str, int] = defaultdict(int)
236
+
237
+ def report(self) -> str:
238
+ elapsed = time.time() - self.start
239
+ rate = self.images / elapsed if elapsed > 0 else 0
240
+ mb = self.bytes / (1024 * 1024)
241
+ return f"Pages: {self.pages} | Imgs: {self.images} | {mb:.1f} MB | {rate:.1f} img/s | Skip: {self.skipped_small}s/{self.skipped_dupe}d | Err: {self.errors}"
242
+
243
+
244
+ # ============= CRAWLER =============
245
+
246
+ class ImageCrawler:
247
+ USER_AGENTS = [
248
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36',
249
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36',
250
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36',
251
+ ]
252
+
253
+ IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'}
254
+
255
+ def __init__(
256
+ self,
257
+ output_dir: str = 'image_data',
258
+ max_workers: int = 50,
259
+ max_pages: int = 100000,
260
+ max_bytes: int = 10 * 1024**3,
261
+ timeout: int = 30,
262
+ min_size: int = 256, # Minimum dimension
263
+ max_size: int = 8192, # Maximum dimension
264
+ min_bytes: int = 10000, # 10KB minimum
265
+ max_bytes_per_image: int = 20 * 1024**2, # 20MB max per image
266
+ save_inline: bool = False, # Save base64 in JSONL vs separate files
267
+ ):
268
+ self.output_dir = Path(output_dir)
269
+ self.output_dir.mkdir(parents=True, exist_ok=True)
270
+ (self.output_dir / 'images').mkdir(exist_ok=True)
271
+
272
+ self.max_workers = max_workers
273
+ self.max_pages = max_pages
274
+ self.max_bytes = max_bytes
275
+ self.timeout = timeout
276
+ self.min_size = min_size
277
+ self.max_size = max_size
278
+ self.min_bytes = min_bytes
279
+ self.max_bytes_per_image = max_bytes_per_image
280
+ self.save_inline = save_inline
281
+
282
+ self.page_queue: asyncio.Queue = asyncio.Queue()
283
+ self.seen_pages: Set[str] = set()
284
+ self.seen_images: Set[str] = set()
285
+ self.seen_hashes: Set[str] = set()
286
+ self.stats = Stats()
287
+ self.running = True
288
+
289
+ self.output_file = None
290
+ self.output_lock = asyncio.Lock()
291
+
292
+ def _should_crawl_page(self, url: str) -> bool:
293
+ if url in self.seen_pages:
294
+ return False
295
+ skip_ext = {'.jpg', '.jpeg', '.png', '.gif', '.pdf', '.zip', '.mp3', '.mp4',
296
+ '.avi', '.mov', '.exe', '.css', '.js', '.ico', '.svg'}
297
+ lower = url.lower()
298
+ if any(lower.endswith(ext) for ext in skip_ext):
299
+ return False
300
+ return True
301
+
302
+ async def _fetch_page(self, session: aiohttp.ClientSession, url: str) -> Tuple[Optional[str], Set[str]]:
303
+ """Fetch a page and extract images + links"""
304
+ try:
305
+ headers = {'User-Agent': random.choice(self.USER_AGENTS)}
306
+ async with session.get(url, headers=headers, timeout=self.timeout,
307
+ ssl=False, allow_redirects=True) as resp:
308
+ ct = resp.headers.get('content-type', '').lower()
309
+ if 'text/html' not in ct:
310
+ return None, set()
311
+ html = await resp.text(errors='ignore')
312
+ links = extract_links(html, url)
313
+ return html, links
314
+ except:
315
+ return None, set()
316
+
317
+ async def _fetch_image(self, session: aiohttp.ClientSession, img_info: Dict, source_page: str) -> Optional[Dict]:
318
+ """Fetch and validate a single image"""
319
+ url = img_info['url']
320
+
321
+ if url in self.seen_images:
322
+ return None
323
+ self.seen_images.add(url)
324
+
325
+ try:
326
+ headers = {'User-Agent': random.choice(self.USER_AGENTS)}
327
+ async with session.get(url, headers=headers, timeout=self.timeout,
328
+ ssl=False, allow_redirects=True) as resp:
329
+
330
+ ct = resp.headers.get('content-type', '').lower()
331
+ if not any(t in ct for t in ['image/jpeg', 'image/png', 'image/gif', 'image/webp']):
332
+ return None
333
+
334
+ # Check content-length first
335
+ cl = resp.headers.get('content-length')
336
+ if cl:
337
+ size = int(cl)
338
+ if size < self.min_bytes or size > self.max_bytes_per_image:
339
+ self.stats.skipped_small += 1
340
+ return None
341
+
342
+ data = await resp.read()
343
+
344
+ if len(data) < self.min_bytes:
345
+ self.stats.skipped_small += 1
346
+ return None
347
+
348
+ # Get dimensions
349
+ width, height = get_image_size_from_header(data)
350
+ if width < self.min_size or height < self.min_size:
351
+ self.stats.skipped_small += 1
352
+ return None
353
+ if width > self.max_size or height > self.max_size:
354
+ self.stats.skipped_small += 1
355
+ return None
356
+
357
+ # Dedupe by hash
358
+ img_hash = hashlib.md5(data).hexdigest()
359
+ if img_hash in self.seen_hashes:
360
+ self.stats.skipped_dupe += 1
361
+ return None
362
+ self.seen_hashes.add(img_hash)
363
+
364
+ # Determine format
365
+ fmt = 'unknown'
366
+ if data[:8] == b'\x89PNG\r\n\x1a\n':
367
+ fmt = 'png'
368
+ elif data[:2] == b'\xff\xd8':
369
+ fmt = 'jpeg'
370
+ elif data[:6] in (b'GIF87a', b'GIF89a'):
371
+ fmt = 'gif'
372
+ elif data[:4] == b'RIFF' and data[8:12] == b'WEBP':
373
+ fmt = 'webp'
374
+
375
+ result = {
376
+ 'url': url,
377
+ 'source_page': source_page,
378
+ 'domain': get_domain(url),
379
+ 'timestamp': datetime.utcnow().isoformat(),
380
+ 'alt': img_info.get('alt', ''),
381
+ 'title': img_info.get('title', ''),
382
+ 'context': img_info.get('context', ''),
383
+ 'width': width,
384
+ 'height': height,
385
+ 'format': fmt,
386
+ 'size_bytes': len(data),
387
+ 'hash': img_hash,
388
+ }
389
+
390
+ if self.save_inline:
391
+ result['data'] = base64.b64encode(data).decode('ascii')
392
+ else:
393
+ # Save to file
394
+ ext = {'jpeg': 'jpg', 'png': 'png', 'gif': 'gif', 'webp': 'webp'}.get(fmt, 'bin')
395
+ fname = f"{img_hash}.{ext}"
396
+ fpath = self.output_dir / 'images' / fname
397
+ with open(fpath, 'wb') as f:
398
+ f.write(data)
399
+ result['file'] = fname
400
+
401
+ return result
402
+
403
+ except Exception as e:
404
+ self.stats.errors += 1
405
+ return None
406
+
407
+ async def _worker(self, session: aiohttp.ClientSession, worker_id: int):
408
+ """Worker processes pages and their images"""
409
+ while self.running:
410
+ try:
411
+ page_url = await asyncio.wait_for(self.page_queue.get(), timeout=10.0)
412
+ except asyncio.TimeoutError:
413
+ if self.page_queue.empty():
414
+ break
415
+ continue
416
+
417
+ if self.stats.bytes >= self.max_bytes or self.stats.pages >= self.max_pages:
418
+ self.running = False
419
+ break
420
+
421
+ html, links = await self._fetch_page(session, page_url)
422
+
423
+ if html:
424
+ self.stats.pages += 1
425
+
426
+ # Extract and fetch images
427
+ images = extract_images_from_html(html, page_url)
428
+ for img_info in images:
429
+ if not self.running:
430
+ break
431
+
432
+ result = await self._fetch_image(session, img_info, page_url)
433
+ if result:
434
+ self.stats.images += 1
435
+ self.stats.bytes += result['size_bytes']
436
+ self.stats.by_domain[result['domain']] += 1
437
+
438
+ async with self.output_lock:
439
+ self.output_file.write(json.dumps(result) + '\n')
440
+
441
+ # Queue new pages
442
+ for link in links:
443
+ if self._should_crawl_page(link) and self.stats.pages < self.max_pages:
444
+ self.seen_pages.add(link)
445
+ await self.page_queue.put(link)
446
+
447
+ if self.stats.pages % 50 == 0:
448
+ print(f"[{datetime.now().strftime('%H:%M:%S')}] {self.stats.report()}")
449
+
450
+ self.page_queue.task_done()
451
+
452
+ async def crawl(self, seeds: List[str]):
453
+ print(f"OpenTransformers Image Crawler starting")
454
+ print(f"Seeds: {len(seeds)} | Workers: {self.max_workers} | Min size: {self.min_size}px")
455
+ print(f"Target: {self.max_pages} pages / {self.max_bytes/1024**3:.1f} GB")
456
+ print("-" * 60)
457
+
458
+ for seed in seeds:
459
+ self.seen_pages.add(seed)
460
+ await self.page_queue.put(seed)
461
+
462
+ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
463
+ output_path = self.output_dir / f'images_{timestamp}.jsonl'
464
+ self.output_file = open(output_path, 'w', buffering=1)
465
+
466
+ connector = aiohttp.TCPConnector(limit=self.max_workers, ssl=False)
467
+ async with aiohttp.ClientSession(connector=connector) as session:
468
+ workers = [asyncio.create_task(self._worker(session, i)) for i in range(self.max_workers)]
469
+ await asyncio.gather(*workers)
470
+
471
+ self.output_file.close()
472
+
473
+ print("-" * 60)
474
+ print(f"DONE! {self.stats.report()}")
475
+ print(f"Metadata: {output_path}")
476
+ if not self.save_inline:
477
+ img_dir = self.output_dir / 'images'
478
+ img_count = len(list(img_dir.glob('*')))
479
+ img_size = sum(f.stat().st_size for f in img_dir.glob('*')) / (1024**2)
480
+ print(f"Images: {img_dir} ({img_count} files, {img_size:.1f} MB)")
481
+
482
+
483
+ def main():
484
+ p = argparse.ArgumentParser(description='OpenTransformers Image Crawler')
485
+ p.add_argument('--seeds', type=str, help='File with seed URLs')
486
+ p.add_argument('--seed', type=str, action='append', help='Single seed URL')
487
+ p.add_argument('--output', type=str, default='image_data')
488
+ p.add_argument('--workers', type=int, default=50)
489
+ p.add_argument('--max-pages', type=int, default=100000)
490
+ p.add_argument('--max-gb', type=float, default=10.0)
491
+ p.add_argument('--timeout', type=int, default=30)
492
+ p.add_argument('--min-size', type=int, default=256, help='Min image dimension (px)')
493
+ p.add_argument('--max-size', type=int, default=8192, help='Max image dimension (px)')
494
+ p.add_argument('--min-kb', type=int, default=10, help='Min image size (KB)')
495
+ p.add_argument('--inline', action='store_true', help='Save base64 in JSONL instead of files')
496
+
497
+ args = p.parse_args()
498
+
499
+ seeds = []
500
+ if args.seeds:
501
+ with open(args.seeds) as f:
502
+ seeds.extend(line.strip() for line in f if line.strip())
503
+ if args.seed:
504
+ seeds.extend(args.seed)
505
+ if not seeds:
506
+ print("ERROR: Provide --seeds file or --seed URLs")
507
+ return
508
+
509
+ crawler = ImageCrawler(
510
+ output_dir=args.output,
511
+ max_workers=args.workers,
512
+ max_pages=args.max_pages,
513
+ max_bytes=int(args.max_gb * 1024**3),
514
+ timeout=args.timeout,
515
+ min_size=args.min_size,
516
+ max_size=args.max_size,
517
+ min_bytes=args.min_kb * 1024,
518
+ save_inline=args.inline,
519
+ )
520
+
521
+ asyncio.run(crawler.crawl(seeds))
522
+
523
+
524
+ if __name__ == '__main__':
525
+ main()