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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
#!/usr/bin/env python3
"""
OpenTransformers Image Crawler v1.0
Grabby hands for multimodal training data.

Grabs images + context (alt text, captions, surrounding text)
Perfect for vision-language model training.

Usage:
    python image_crawler.py --seeds seeds.txt --output /workspace/images --max-gb 10
    python image_crawler.py --seed "https://unsplash.com" --min-size 256 --workers 50
"""

import asyncio
import aiohttp
import argparse
import hashlib
import json
import os
import re
import time
import random
import base64
from dataclasses import dataclass, asdict
from datetime import datetime
from pathlib import Path
from typing import Optional, Set, Dict, List, Tuple
from urllib.parse import urljoin, urlparse
from collections import defaultdict
import struct
import io

# ============= IMAGE UTILITIES =============

def get_image_size_from_header(data: bytes) -> Tuple[int, int]:
    """Get image dimensions without downloading full image"""
    if len(data) < 24:
        return (0, 0)
    
    # PNG
    if data[:8] == b'\x89PNG\r\n\x1a\n':
        if data[12:16] == b'IHDR':
            w = struct.unpack('>I', data[16:20])[0]
            h = struct.unpack('>I', data[20:24])[0]
            return (w, h)
    
    # JPEG
    if data[:2] == b'\xff\xd8':
        try:
            i = 2
            while i < len(data) - 8:
                if data[i] != 0xff:
                    i += 1
                    continue
                marker = data[i+1]
                if marker in (0xc0, 0xc1, 0xc2):  # SOF markers
                    h = struct.unpack('>H', data[i+5:i+7])[0]
                    w = struct.unpack('>H', data[i+7:i+9])[0]
                    return (w, h)
                elif marker == 0xd9:  # EOI
                    break
                elif marker in (0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0x01):
                    i += 2
                else:
                    length = struct.unpack('>H', data[i+2:i+4])[0]
                    i += 2 + length
        except:
            pass
    
    # GIF
    if data[:6] in (b'GIF87a', b'GIF89a'):
        w = struct.unpack('<H', data[6:8])[0]
        h = struct.unpack('<H', data[8:10])[0]
        return (w, h)
    
    # WebP
    if data[:4] == b'RIFF' and data[8:12] == b'WEBP':
        if data[12:16] == b'VP8 ':
            w = struct.unpack('<H', data[26:28])[0] & 0x3fff
            h = struct.unpack('<H', data[28:30])[0] & 0x3fff
            return (w, h)
        elif data[12:16] == b'VP8L':
            bits = struct.unpack('<I', data[21:25])[0]
            w = (bits & 0x3fff) + 1
            h = ((bits >> 14) & 0x3fff) + 1
            return (w, h)
    
    return (0, 0)


def extract_images_from_html(html: str, base_url: str) -> List[Dict]:
    """Extract all images with context from HTML"""
    images = []
    
    # Standard img tags
    for match in re.finditer(
        r'<img[^>]+src=["\']([^"\']+)["\'][^>]*>',
        html, re.I | re.DOTALL
    ):
        full_tag = match.group(0)
        src = match.group(1)
        
        if src.startswith('data:'):
            continue
            
        # Get alt text
        alt_match = re.search(r'alt=["\']([^"\']*)["\']', full_tag, re.I)
        alt = alt_match.group(1) if alt_match else ""
        
        # Get title
        title_match = re.search(r'title=["\']([^"\']*)["\']', full_tag, re.I)
        title = title_match.group(1) if title_match else ""
        
        # Get srcset for higher res
        srcset_match = re.search(r'srcset=["\']([^"\']+)["\']', full_tag, re.I)
        srcset = srcset_match.group(1) if srcset_match else ""
        
        # Parse srcset for best resolution
        best_src = src
        if srcset:
            best_width = 0
            for item in srcset.split(','):
                parts = item.strip().split()
                if len(parts) >= 2:
                    url = parts[0]
                    descriptor = parts[1]
                    if descriptor.endswith('w'):
                        try:
                            width = int(descriptor[:-1])
                            if width > best_width:
                                best_width = width
                                best_src = url
                        except:
                            pass
        
        # Get surrounding text (50 chars before/after)
        start = max(0, match.start() - 200)
        end = min(len(html), match.end() + 200)
        context = re.sub(r'<[^>]+>', ' ', html[start:end])
        context = re.sub(r'\s+', ' ', context).strip()
        
        try:
            absolute_url = urljoin(base_url, best_src)
            if absolute_url.startswith(('http://', 'https://')):
                images.append({
                    'url': absolute_url,
                    'alt': alt,
                    'title': title,
                    'context': context[:500]
                })
        except:
            pass
    
    # Also grab og:image and twitter:image
    for meta_prop in ['og:image', 'twitter:image']:
        match = re.search(
            f'<meta[^>]+(?:property|name)=["\'{meta_prop}["\'][^>]+content=["\']([^"\']+)["\']',
            html, re.I
        )
        if not match:
            match = re.search(
                f'<meta[^>]+content=["\']([^"\']+)["\'][^>]+(?:property|name)=["\'{meta_prop}["\']',
                html, re.I
            )
        if match:
            src = match.group(1)
            try:
                absolute_url = urljoin(base_url, src)
                if absolute_url.startswith(('http://', 'https://')):
                    images.append({
                        'url': absolute_url,
                        'alt': f'[{meta_prop}]',
                        'title': '',
                        'context': ''
                    })
            except:
                pass
    
    return images


def extract_links(html: str, base_url: str) -> Set[str]:
    """Extract page links for crawling"""
    links = set()
    for match in re.finditer(r'href=["\']([^"\']+)["\']', html, re.I):
        href = match.group(1)
        if href.startswith(('#', 'javascript:', 'mailto:', 'tel:', 'data:')):
            continue
        try:
            absolute = urljoin(base_url, href)
            if absolute.startswith(('http://', 'https://')):
                absolute = absolute.split('#')[0]
                if len(absolute) < 500:
                    links.add(absolute)
        except:
            pass
    return links


def get_domain(url: str) -> str:
    try:
        return urlparse(url).netloc.lower()
    except:
        return ""


# ============= DATA STRUCTURES =============

@dataclass
class CrawledImage:
    url: str
    source_page: str
    domain: str
    timestamp: str
    alt: str
    title: str
    context: str
    width: int
    height: int
    format: str
    size_bytes: int
    hash: str
    # base64 data stored separately or inline depending on config


class Stats:
    def __init__(self):
        self.pages = 0
        self.images = 0
        self.bytes = 0
        self.skipped_small = 0
        self.skipped_dupe = 0
        self.errors = 0
        self.start = time.time()
        self.by_domain: Dict[str, int] = defaultdict(int)
    
    def report(self) -> str:
        elapsed = time.time() - self.start
        rate = self.images / elapsed if elapsed > 0 else 0
        mb = self.bytes / (1024 * 1024)
        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}"


# ============= CRAWLER =============

class ImageCrawler:
    USER_AGENTS = [
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36',
        'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36',
    ]
    
    IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'}
    
    def __init__(
        self,
        output_dir: str = 'image_data',
        max_workers: int = 50,
        max_pages: int = 100000,
        max_bytes: int = 10 * 1024**3,
        timeout: int = 30,
        min_size: int = 256,  # Minimum dimension
        max_size: int = 8192,  # Maximum dimension  
        min_bytes: int = 10000,  # 10KB minimum
        max_bytes_per_image: int = 20 * 1024**2,  # 20MB max per image
        save_inline: bool = False,  # Save base64 in JSONL vs separate files
    ):
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        (self.output_dir / 'images').mkdir(exist_ok=True)
        
        self.max_workers = max_workers
        self.max_pages = max_pages
        self.max_bytes = max_bytes
        self.timeout = timeout
        self.min_size = min_size
        self.max_size = max_size
        self.min_bytes = min_bytes
        self.max_bytes_per_image = max_bytes_per_image
        self.save_inline = save_inline
        
        self.page_queue: asyncio.Queue = asyncio.Queue()
        self.seen_pages: Set[str] = set()
        self.seen_images: Set[str] = set()
        self.seen_hashes: Set[str] = set()
        self.stats = Stats()
        self.running = True
        
        self.output_file = None
        self.output_lock = asyncio.Lock()
    
    def _should_crawl_page(self, url: str) -> bool:
        if url in self.seen_pages:
            return False
        skip_ext = {'.jpg', '.jpeg', '.png', '.gif', '.pdf', '.zip', '.mp3', '.mp4',
                   '.avi', '.mov', '.exe', '.css', '.js', '.ico', '.svg'}
        lower = url.lower()
        if any(lower.endswith(ext) for ext in skip_ext):
            return False
        return True
    
    async def _fetch_page(self, session: aiohttp.ClientSession, url: str) -> Tuple[Optional[str], Set[str]]:
        """Fetch a page and extract images + links"""
        try:
            headers = {'User-Agent': random.choice(self.USER_AGENTS)}
            async with session.get(url, headers=headers, timeout=self.timeout,
                                   ssl=False, allow_redirects=True) as resp:
                ct = resp.headers.get('content-type', '').lower()
                if 'text/html' not in ct:
                    return None, set()
                html = await resp.text(errors='ignore')
                links = extract_links(html, url)
                return html, links
        except:
            return None, set()
    
    async def _fetch_image(self, session: aiohttp.ClientSession, img_info: Dict, source_page: str) -> Optional[Dict]:
        """Fetch and validate a single image"""
        url = img_info['url']
        
        if url in self.seen_images:
            return None
        self.seen_images.add(url)
        
        try:
            headers = {'User-Agent': random.choice(self.USER_AGENTS)}
            async with session.get(url, headers=headers, timeout=self.timeout,
                                   ssl=False, allow_redirects=True) as resp:
                
                ct = resp.headers.get('content-type', '').lower()
                if not any(t in ct for t in ['image/jpeg', 'image/png', 'image/gif', 'image/webp']):
                    return None
                
                # Check content-length first
                cl = resp.headers.get('content-length')
                if cl:
                    size = int(cl)
                    if size < self.min_bytes or size > self.max_bytes_per_image:
                        self.stats.skipped_small += 1
                        return None
                
                data = await resp.read()
                
                if len(data) < self.min_bytes:
                    self.stats.skipped_small += 1
                    return None
                
                # Get dimensions
                width, height = get_image_size_from_header(data)
                if width < self.min_size or height < self.min_size:
                    self.stats.skipped_small += 1
                    return None
                if width > self.max_size or height > self.max_size:
                    self.stats.skipped_small += 1
                    return None
                
                # Dedupe by hash
                img_hash = hashlib.md5(data).hexdigest()
                if img_hash in self.seen_hashes:
                    self.stats.skipped_dupe += 1
                    return None
                self.seen_hashes.add(img_hash)
                
                # Determine format
                fmt = 'unknown'
                if data[:8] == b'\x89PNG\r\n\x1a\n':
                    fmt = 'png'
                elif data[:2] == b'\xff\xd8':
                    fmt = 'jpeg'
                elif data[:6] in (b'GIF87a', b'GIF89a'):
                    fmt = 'gif'
                elif data[:4] == b'RIFF' and data[8:12] == b'WEBP':
                    fmt = 'webp'
                
                result = {
                    'url': url,
                    'source_page': source_page,
                    'domain': get_domain(url),
                    'timestamp': datetime.utcnow().isoformat(),
                    'alt': img_info.get('alt', ''),
                    'title': img_info.get('title', ''),
                    'context': img_info.get('context', ''),
                    'width': width,
                    'height': height,
                    'format': fmt,
                    'size_bytes': len(data),
                    'hash': img_hash,
                }
                
                if self.save_inline:
                    result['data'] = base64.b64encode(data).decode('ascii')
                else:
                    # Save to file
                    ext = {'jpeg': 'jpg', 'png': 'png', 'gif': 'gif', 'webp': 'webp'}.get(fmt, 'bin')
                    fname = f"{img_hash}.{ext}"
                    fpath = self.output_dir / 'images' / fname
                    with open(fpath, 'wb') as f:
                        f.write(data)
                    result['file'] = fname
                
                return result
                
        except Exception as e:
            self.stats.errors += 1
            return None
    
    async def _worker(self, session: aiohttp.ClientSession, worker_id: int):
        """Worker processes pages and their images"""
        while self.running:
            try:
                page_url = await asyncio.wait_for(self.page_queue.get(), timeout=10.0)
            except asyncio.TimeoutError:
                if self.page_queue.empty():
                    break
                continue
            
            if self.stats.bytes >= self.max_bytes or self.stats.pages >= self.max_pages:
                self.running = False
                break
            
            html, links = await self._fetch_page(session, page_url)
            
            if html:
                self.stats.pages += 1
                
                # Extract and fetch images
                images = extract_images_from_html(html, page_url)
                for img_info in images:
                    if not self.running:
                        break
                    
                    result = await self._fetch_image(session, img_info, page_url)
                    if result:
                        self.stats.images += 1
                        self.stats.bytes += result['size_bytes']
                        self.stats.by_domain[result['domain']] += 1
                        
                        async with self.output_lock:
                            self.output_file.write(json.dumps(result) + '\n')
                
                # Queue new pages
                for link in links:
                    if self._should_crawl_page(link) and self.stats.pages < self.max_pages:
                        self.seen_pages.add(link)
                        await self.page_queue.put(link)
                
                if self.stats.pages % 50 == 0:
                    print(f"[{datetime.now().strftime('%H:%M:%S')}] {self.stats.report()}")
            
            self.page_queue.task_done()
    
    async def crawl(self, seeds: List[str]):
        print(f"OpenTransformers Image Crawler starting")
        print(f"Seeds: {len(seeds)} | Workers: {self.max_workers} | Min size: {self.min_size}px")
        print(f"Target: {self.max_pages} pages / {self.max_bytes/1024**3:.1f} GB")
        print("-" * 60)
        
        for seed in seeds:
            self.seen_pages.add(seed)
            await self.page_queue.put(seed)
        
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        output_path = self.output_dir / f'images_{timestamp}.jsonl'
        self.output_file = open(output_path, 'w', buffering=1)
        
        connector = aiohttp.TCPConnector(limit=self.max_workers, ssl=False)
        async with aiohttp.ClientSession(connector=connector) as session:
            workers = [asyncio.create_task(self._worker(session, i)) for i in range(self.max_workers)]
            await asyncio.gather(*workers)
        
        self.output_file.close()
        
        print("-" * 60)
        print(f"DONE! {self.stats.report()}")
        print(f"Metadata: {output_path}")
        if not self.save_inline:
            img_dir = self.output_dir / 'images'
            img_count = len(list(img_dir.glob('*')))
            img_size = sum(f.stat().st_size for f in img_dir.glob('*')) / (1024**2)
            print(f"Images: {img_dir} ({img_count} files, {img_size:.1f} MB)")


def main():
    p = argparse.ArgumentParser(description='OpenTransformers Image Crawler')
    p.add_argument('--seeds', type=str, help='File with seed URLs')
    p.add_argument('--seed', type=str, action='append', help='Single seed URL')
    p.add_argument('--output', type=str, default='image_data')
    p.add_argument('--workers', type=int, default=50)
    p.add_argument('--max-pages', type=int, default=100000)
    p.add_argument('--max-gb', type=float, default=10.0)
    p.add_argument('--timeout', type=int, default=30)
    p.add_argument('--min-size', type=int, default=256, help='Min image dimension (px)')
    p.add_argument('--max-size', type=int, default=8192, help='Max image dimension (px)')
    p.add_argument('--min-kb', type=int, default=10, help='Min image size (KB)')
    p.add_argument('--inline', action='store_true', help='Save base64 in JSONL instead of files')
    
    args = p.parse_args()
    
    seeds = []
    if args.seeds:
        with open(args.seeds) as f:
            seeds.extend(line.strip() for line in f if line.strip())
    if args.seed:
        seeds.extend(args.seed)
    if not seeds:
        print("ERROR: Provide --seeds file or --seed URLs")
        return
    
    crawler = ImageCrawler(
        output_dir=args.output,
        max_workers=args.workers,
        max_pages=args.max_pages,
        max_bytes=int(args.max_gb * 1024**3),
        timeout=args.timeout,
        min_size=args.min_size,
        max_size=args.max_size,
        min_bytes=args.min_kb * 1024,
        save_inline=args.inline,
    )
    
    asyncio.run(crawler.crawl(seeds))


if __name__ == '__main__':
    main()