OpenTransformer commited on
Commit
7e7d6dc
·
verified ·
1 Parent(s): 5b32eaa

Upload video_crawler.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. video_crawler.py +395 -0
video_crawler.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ OpenTransformers Video Crawler v1.0
4
+ Grabby hands for video data - uses yt-dlp for broad site support.
5
+
6
+ Grabs videos + metadata (title, description, duration, tags)
7
+ Supports YouTube, Vimeo, Twitter, Reddit, and 1000+ sites via yt-dlp.
8
+
9
+ Usage:
10
+ python video_crawler.py --seeds video_seeds.txt --output /workspace/video --max-gb 50
11
+ python video_crawler.py --seed "https://www.youtube.com/watch?v=dQw4w9WgXcQ" --max-duration 300
12
+ """
13
+
14
+ import asyncio
15
+ import subprocess
16
+ import argparse
17
+ import hashlib
18
+ import json
19
+ import os
20
+ import re
21
+ import time
22
+ import random
23
+ from dataclasses import dataclass
24
+ from datetime import datetime
25
+ from pathlib import Path
26
+ from typing import Optional, Set, Dict, List
27
+ from urllib.parse import urljoin, urlparse
28
+ import aiohttp
29
+
30
+ # Video URL patterns yt-dlp can handle
31
+ VIDEO_PATTERNS = [
32
+ r'youtube\.com/watch\?v=',
33
+ r'youtu\.be/',
34
+ r'vimeo\.com/\d+',
35
+ r'twitter\.com/.*/status/',
36
+ r'x\.com/.*/status/',
37
+ r'reddit\.com/r/.*/comments/',
38
+ r'tiktok\.com/',
39
+ r'instagram\.com/p/',
40
+ r'instagram\.com/reel/',
41
+ r'facebook\.com/.*/videos/',
42
+ r'twitch\.tv/',
43
+ r'dailymotion\.com/video/',
44
+ r'streamable\.com/',
45
+ r'v\.redd\.it/',
46
+ r'gfycat\.com/',
47
+ r'imgur\.com/.*\.(mp4|gifv)',
48
+ ]
49
+
50
+ VIDEO_PATTERN_RE = re.compile('|'.join(VIDEO_PATTERNS), re.I)
51
+
52
+
53
+ def is_video_url(url: str) -> bool:
54
+ """Check if URL is a video we can download"""
55
+ return bool(VIDEO_PATTERN_RE.search(url))
56
+
57
+
58
+ def extract_video_urls(html: str, base_url: str) -> List[str]:
59
+ """Extract video URLs from HTML"""
60
+ urls = set()
61
+
62
+ # Find all links
63
+ for match in re.finditer(r'href=["\']([^"\']+)["\']', html, re.I):
64
+ href = match.group(1)
65
+ try:
66
+ absolute = urljoin(base_url, href)
67
+ if is_video_url(absolute):
68
+ urls.add(absolute)
69
+ except:
70
+ pass
71
+
72
+ # Find embedded URLs in text/scripts
73
+ for match in re.finditer(r'https?://[^\s"\'<>]+', html):
74
+ url = match.group(0)
75
+ if is_video_url(url):
76
+ urls.add(url.rstrip('.,;:'))
77
+
78
+ return list(urls)
79
+
80
+
81
+ def extract_page_links(html: str, base_url: str) -> Set[str]:
82
+ """Extract page links for crawling"""
83
+ links = set()
84
+ for match in re.finditer(r'href=["\']([^"\']+)["\']', html, re.I):
85
+ href = match.group(1)
86
+ if href.startswith(('#', 'javascript:', 'mailto:')):
87
+ continue
88
+ try:
89
+ absolute = urljoin(base_url, href)
90
+ if absolute.startswith(('http://', 'https://')):
91
+ absolute = absolute.split('#')[0]
92
+ if len(absolute) < 500:
93
+ links.add(absolute)
94
+ except:
95
+ pass
96
+ return links
97
+
98
+
99
+ class VideoCrawler:
100
+ USER_AGENTS = [
101
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36',
102
+ ]
103
+
104
+ def __init__(
105
+ self,
106
+ output_dir: str = 'video_data',
107
+ max_workers: int = 5, # Lower for video - heavy downloads
108
+ max_pages: int = 10000,
109
+ max_bytes: int = 50 * 1024**3, # 50GB default
110
+ max_duration: int = 300, # 5 min max per video
111
+ max_height: int = 720, # 720p max
112
+ metadata_only: bool = False, # Just grab metadata, no video
113
+ ):
114
+ self.output_dir = Path(output_dir)
115
+ self.output_dir.mkdir(parents=True, exist_ok=True)
116
+ (self.output_dir / 'videos').mkdir(exist_ok=True)
117
+
118
+ self.max_workers = max_workers
119
+ self.max_pages = max_pages
120
+ self.max_bytes = max_bytes
121
+ self.max_duration = max_duration
122
+ self.max_height = max_height
123
+ self.metadata_only = metadata_only
124
+
125
+ self.page_queue: asyncio.Queue = asyncio.Queue()
126
+ self.video_queue: asyncio.Queue = asyncio.Queue()
127
+ self.seen_pages: Set[str] = set()
128
+ self.seen_videos: Set[str] = set()
129
+ self.running = True
130
+
131
+ self.stats = {'pages': 0, 'videos': 0, 'bytes': 0, 'skipped': 0, 'errors': 0}
132
+ self.start_time = time.time()
133
+
134
+ self.output_file = None
135
+ self.output_lock = asyncio.Lock()
136
+
137
+ def _report(self) -> str:
138
+ elapsed = time.time() - self.start_time
139
+ mb = self.stats['bytes'] / (1024**2)
140
+ return f"Pages: {self.stats['pages']} | Videos: {self.stats['videos']} | {mb:.1f} MB | Skip: {self.stats['skipped']} | Err: {self.stats['errors']}"
141
+
142
+ async def _fetch_page(self, session: aiohttp.ClientSession, url: str):
143
+ try:
144
+ headers = {'User-Agent': random.choice(self.USER_AGENTS)}
145
+ async with session.get(url, headers=headers, timeout=30, ssl=False, allow_redirects=True) as resp:
146
+ ct = resp.headers.get('content-type', '').lower()
147
+ if 'text/html' not in ct:
148
+ return None, set()
149
+ html = await resp.text(errors='ignore')
150
+ links = extract_page_links(html, url)
151
+ return html, links
152
+ except:
153
+ return None, set()
154
+
155
+ def _download_video(self, url: str, source_page: str) -> Optional[Dict]:
156
+ """Download video using yt-dlp"""
157
+ video_hash = hashlib.md5(url.encode()).hexdigest()[:16]
158
+ output_template = str(self.output_dir / 'videos' / f'{video_hash}.%(ext)s')
159
+
160
+ # Build yt-dlp command
161
+ cmd = [
162
+ 'yt-dlp',
163
+ '--no-playlist',
164
+ '--max-filesize', '500M',
165
+ '--socket-timeout', '30',
166
+ '-f', f'bestvideo[height<={self.max_height}]+bestaudio/best[height<={self.max_height}]',
167
+ '--merge-output-format', 'mp4',
168
+ '-o', output_template,
169
+ '--print-json',
170
+ '--no-progress',
171
+ ]
172
+
173
+ if self.max_duration:
174
+ cmd.extend(['--match-filter', f'duration<={self.max_duration}'])
175
+
176
+ if self.metadata_only:
177
+ cmd.extend(['--skip-download', '--write-info-json'])
178
+
179
+ cmd.append(url)
180
+
181
+ try:
182
+ result = subprocess.run(
183
+ cmd,
184
+ capture_output=True,
185
+ text=True,
186
+ timeout=300 # 5 min timeout
187
+ )
188
+
189
+ if result.returncode != 0:
190
+ self.stats['errors'] += 1
191
+ return None
192
+
193
+ # Parse JSON output
194
+ info = json.loads(result.stdout.strip().split('\n')[-1])
195
+
196
+ # Find downloaded file
197
+ video_file = None
198
+ if not self.metadata_only:
199
+ for f in (self.output_dir / 'videos').glob(f'{video_hash}.*'):
200
+ if f.suffix in ('.mp4', '.mkv', '.webm', '.mov'):
201
+ video_file = f.name
202
+ break
203
+
204
+ file_size = 0
205
+ if video_file:
206
+ file_size = (self.output_dir / 'videos' / video_file).stat().st_size
207
+
208
+ return {
209
+ 'url': url,
210
+ 'source_page': source_page,
211
+ 'timestamp': datetime.utcnow().isoformat(),
212
+ 'title': info.get('title', ''),
213
+ 'description': info.get('description', '')[:1000] if info.get('description') else '',
214
+ 'duration': info.get('duration', 0),
215
+ 'width': info.get('width', 0),
216
+ 'height': info.get('height', 0),
217
+ 'fps': info.get('fps', 0),
218
+ 'view_count': info.get('view_count', 0),
219
+ 'like_count': info.get('like_count', 0),
220
+ 'uploader': info.get('uploader', ''),
221
+ 'upload_date': info.get('upload_date', ''),
222
+ 'tags': info.get('tags', [])[:20] if info.get('tags') else [],
223
+ 'categories': info.get('categories', []),
224
+ 'extractor': info.get('extractor', ''),
225
+ 'format': info.get('format', ''),
226
+ 'size_bytes': file_size,
227
+ 'hash': video_hash,
228
+ 'file': video_file
229
+ }
230
+
231
+ except subprocess.TimeoutExpired:
232
+ self.stats['errors'] += 1
233
+ return None
234
+ except Exception as e:
235
+ self.stats['errors'] += 1
236
+ return None
237
+
238
+ async def _page_worker(self, session: aiohttp.ClientSession, worker_id: int):
239
+ """Crawl pages and find video URLs"""
240
+ while self.running:
241
+ try:
242
+ page_url = await asyncio.wait_for(self.page_queue.get(), timeout=10.0)
243
+ except asyncio.TimeoutError:
244
+ if self.page_queue.empty():
245
+ break
246
+ continue
247
+
248
+ if self.stats['bytes'] >= self.max_bytes or self.stats['pages'] >= self.max_pages:
249
+ self.running = False
250
+ break
251
+
252
+ html, links = await self._fetch_page(session, page_url)
253
+
254
+ if html:
255
+ self.stats['pages'] += 1
256
+
257
+ # Extract video URLs
258
+ video_urls = extract_video_urls(html, page_url)
259
+ for video_url in video_urls:
260
+ if video_url not in self.seen_videos:
261
+ self.seen_videos.add(video_url)
262
+ await self.video_queue.put((video_url, page_url))
263
+
264
+ # Queue new pages
265
+ for link in links:
266
+ if link not in self.seen_pages and self.stats['pages'] < self.max_pages:
267
+ self.seen_pages.add(link)
268
+ await self.page_queue.put(link)
269
+
270
+ if self.stats['pages'] % 20 == 0:
271
+ print(f"[{datetime.now().strftime('%H:%M:%S')}] {self._report()} | Queue: {self.video_queue.qsize()}")
272
+
273
+ self.page_queue.task_done()
274
+
275
+ async def _video_worker(self, worker_id: int):
276
+ """Download videos from queue"""
277
+ loop = asyncio.get_event_loop()
278
+
279
+ while self.running:
280
+ try:
281
+ video_url, source_page = await asyncio.wait_for(self.video_queue.get(), timeout=10.0)
282
+ except asyncio.TimeoutError:
283
+ if self.video_queue.empty() and self.page_queue.empty():
284
+ break
285
+ continue
286
+
287
+ if self.stats['bytes'] >= self.max_bytes:
288
+ self.running = False
289
+ break
290
+
291
+ # Run yt-dlp in thread pool (blocking operation)
292
+ result = await loop.run_in_executor(
293
+ None,
294
+ self._download_video,
295
+ video_url,
296
+ source_page
297
+ )
298
+
299
+ if result:
300
+ self.stats['videos'] += 1
301
+ self.stats['bytes'] += result.get('size_bytes', 0)
302
+
303
+ async with self.output_lock:
304
+ self.output_file.write(json.dumps(result) + '\n')
305
+
306
+ print(f" ✓ {result['title'][:50]}... ({result.get('duration', 0)}s)")
307
+ else:
308
+ self.stats['skipped'] += 1
309
+
310
+ self.video_queue.task_done()
311
+
312
+ async def crawl(self, seeds: List[str]):
313
+ print(f"OpenTransformers Video Crawler starting")
314
+ print(f"Seeds: {len(seeds)} | Page workers: {self.max_workers} | Video workers: 3")
315
+ print(f"Target: {self.max_pages} pages / {self.max_bytes/1024**3:.1f} GB / {self.max_duration}s max")
316
+ print("-" * 60)
317
+
318
+ # Separate direct video URLs from page URLs
319
+ for seed in seeds:
320
+ if is_video_url(seed):
321
+ self.seen_videos.add(seed)
322
+ await self.video_queue.put((seed, 'seed'))
323
+ else:
324
+ self.seen_pages.add(seed)
325
+ await self.page_queue.put(seed)
326
+
327
+ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
328
+ output_path = self.output_dir / f'video_{timestamp}.jsonl'
329
+ self.output_file = open(output_path, 'w', buffering=1)
330
+
331
+ connector = aiohttp.TCPConnector(limit=self.max_workers, ssl=False)
332
+ async with aiohttp.ClientSession(connector=connector) as session:
333
+ # Start page crawlers
334
+ page_workers = [
335
+ asyncio.create_task(self._page_worker(session, i))
336
+ for i in range(self.max_workers)
337
+ ]
338
+ # Start video downloaders (fewer, heavier)
339
+ video_workers = [
340
+ asyncio.create_task(self._video_worker(i))
341
+ for i in range(3)
342
+ ]
343
+
344
+ await asyncio.gather(*page_workers, *video_workers)
345
+
346
+ self.output_file.close()
347
+
348
+ print("-" * 60)
349
+ print(f"DONE! {self._report()}")
350
+ print(f"Metadata: {output_path}")
351
+ video_dir = self.output_dir / 'videos'
352
+ files = list(video_dir.glob('*.mp4')) + list(video_dir.glob('*.webm')) + list(video_dir.glob('*.mkv'))
353
+ total_size = sum(f.stat().st_size for f in files) / (1024**3)
354
+ print(f"Videos: {len(files)} files, {total_size:.2f} GB in {video_dir}")
355
+
356
+
357
+ def main():
358
+ p = argparse.ArgumentParser(description='OpenTransformers Video Crawler')
359
+ p.add_argument('--seeds', type=str, help='File with seed URLs')
360
+ p.add_argument('--seed', type=str, action='append', help='Single seed URL')
361
+ p.add_argument('--output', type=str, default='video_data')
362
+ p.add_argument('--workers', type=int, default=5)
363
+ p.add_argument('--max-pages', type=int, default=10000)
364
+ p.add_argument('--max-gb', type=float, default=50.0)
365
+ p.add_argument('--max-duration', type=int, default=300, help='Max video duration (seconds)')
366
+ p.add_argument('--max-height', type=int, default=720, help='Max video height (pixels)')
367
+ p.add_argument('--metadata-only', action='store_true', help='Only grab metadata, skip video download')
368
+
369
+ args = p.parse_args()
370
+
371
+ seeds = []
372
+ if args.seeds:
373
+ with open(args.seeds) as f:
374
+ seeds.extend(line.strip() for line in f if line.strip())
375
+ if args.seed:
376
+ seeds.extend(args.seed)
377
+ if not seeds:
378
+ print("ERROR: Provide --seeds file or --seed URLs")
379
+ return
380
+
381
+ crawler = VideoCrawler(
382
+ output_dir=args.output,
383
+ max_workers=args.workers,
384
+ max_pages=args.max_pages,
385
+ max_bytes=int(args.max_gb * 1024**3),
386
+ max_duration=args.max_duration,
387
+ max_height=args.max_height,
388
+ metadata_only=args.metadata_only,
389
+ )
390
+
391
+ asyncio.run(crawler.crawl(seeds))
392
+
393
+
394
+ if __name__ == '__main__':
395
+ main()