@auscera/socialscrape 0.0.0-stage → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +111 -2
  2. package/bin/socialscrape.mjs +115 -0
  3. package/engine/README.md +243 -0
  4. package/engine/SKILL.md +194 -0
  5. package/engine/agent.py +665 -0
  6. package/engine/batch_manager.py +622 -0
  7. package/engine/cli.py +23 -0
  8. package/engine/handlers.py +1109 -0
  9. package/engine/plugins/__init__.py +77 -0
  10. package/engine/plugins/instagram-scrape/README.md +164 -0
  11. package/engine/plugins/instagram-scrape/SKILL.md +53 -0
  12. package/engine/plugins/instagram-scrape/cli.py +176 -0
  13. package/engine/plugins/instagram-scrape/core.py +408 -0
  14. package/engine/plugins/instagram-scrape/plugin.json +42 -0
  15. package/engine/plugins/linkedin-scrape/README.md +143 -0
  16. package/engine/plugins/linkedin-scrape/SKILL.md +47 -0
  17. package/engine/plugins/linkedin-scrape/cli.py +126 -0
  18. package/engine/plugins/linkedin-scrape/core.py +188 -0
  19. package/engine/plugins/linkedin-scrape/plugin.json +36 -0
  20. package/engine/plugins/meta-ad-library-scraper/README.md +127 -0
  21. package/engine/plugins/meta-ad-library-scraper/SKILL.md +44 -0
  22. package/engine/plugins/meta-ad-library-scraper/cli.py +161 -0
  23. package/engine/plugins/meta-ad-library-scraper/core.py +348 -0
  24. package/engine/plugins/meta-ad-library-scraper/plugin.json +44 -0
  25. package/engine/plugins/pinterest-scraper/README.md +150 -0
  26. package/engine/plugins/pinterest-scraper/SKILL.md +45 -0
  27. package/engine/plugins/pinterest-scraper/cli.py +193 -0
  28. package/engine/plugins/pinterest-scraper/core.py +420 -0
  29. package/engine/plugins/pinterest-scraper/plugin.json +40 -0
  30. package/engine/plugins/reddit-discussion-scraper/README.md +162 -0
  31. package/engine/plugins/reddit-discussion-scraper/SKILL.md +52 -0
  32. package/engine/plugins/reddit-discussion-scraper/cli.py +218 -0
  33. package/engine/plugins/reddit-discussion-scraper/core.py +546 -0
  34. package/engine/plugins/reddit-discussion-scraper/plugin.json +46 -0
  35. package/engine/plugins/shared/__init__.py +15 -0
  36. package/engine/plugins/shared/paths.py +90 -0
  37. package/engine/plugins/shared/process_runner.py +169 -0
  38. package/engine/plugins/shared/session_manager.py +287 -0
  39. package/engine/plugins/threads-scraper/README.md +139 -0
  40. package/engine/plugins/threads-scraper/SKILL.md +43 -0
  41. package/engine/plugins/threads-scraper/cli.py +178 -0
  42. package/engine/plugins/threads-scraper/core.py +460 -0
  43. package/engine/plugins/threads-scraper/plugin.json +40 -0
  44. package/engine/plugins/tiktok-scrape/README.md +158 -0
  45. package/engine/plugins/tiktok-scrape/SKILL.md +51 -0
  46. package/engine/plugins/tiktok-scrape/cli.py +163 -0
  47. package/engine/plugins/tiktok-scrape/core.py +313 -0
  48. package/engine/plugins/tiktok-scrape/plugin.json +40 -0
  49. package/engine/plugins/twitter-scrape/README.md +158 -0
  50. package/engine/plugins/twitter-scrape/SKILL.md +50 -0
  51. package/engine/plugins/twitter-scrape/cli.py +153 -0
  52. package/engine/plugins/twitter-scrape/core.py +254 -0
  53. package/engine/plugins/twitter-scrape/plugin.json +40 -0
  54. package/engine/plugins/youtube-scrape/README.md +199 -0
  55. package/engine/plugins/youtube-scrape/SKILL.md +115 -0
  56. package/engine/plugins/youtube-scrape/cli.py +340 -0
  57. package/engine/plugins/youtube-scrape/core.py +829 -0
  58. package/engine/plugins/youtube-scrape/plugin.json +48 -0
  59. package/engine/requirements.txt +8 -0
  60. package/engine/socialscrape_cli.py +500 -0
  61. package/engine/storage.py +570 -0
  62. package/engine/ui.py +690 -0
  63. package/package.json +27 -3
@@ -0,0 +1,829 @@
1
+ """
2
+ YouTube Scrape Plugin SDK (`core.py`)
3
+ Modular, pure-function library for YouTube extraction operations:
4
+ - Transcripts (Android/iOS bypass, zero-cookie, zero-browser)
5
+ - Video & Shorts Metadata (Views, Likes, Tags, Description, Upload Date)
6
+ - Comments (Top comments, author, timestamps, engagement)
7
+ - Media & Thumbnail Downloader (Video MP4, Audio M4A/MP3, Thumbnails)
8
+ - Channel Discovery (Videos, Live Streams, Shorts)
9
+
10
+ STRICT RULE: Pure functions only. Zero print(), input(), or sys.exit() calls.
11
+ """
12
+
13
+ import os
14
+ import sys
15
+ import re
16
+ import json
17
+ import time
18
+ import random
19
+ import urllib.request
20
+ import urllib.error
21
+ from xml.sax.saxutils import escape
22
+ from pathlib import Path
23
+ from urllib.parse import urlparse, parse_qs
24
+ from typing import Optional, Dict, List, Any, Union
25
+
26
+ try:
27
+ from plugins.shared.paths import get_plugin_outputs_dir, is_allowed_output_dir
28
+ except ImportError:
29
+ _shared_parent = str(Path(__file__).parent.parent.resolve())
30
+ if _shared_parent not in sys.path:
31
+ sys.path.insert(0, _shared_parent)
32
+ from shared.paths import get_plugin_outputs_dir, is_allowed_output_dir
33
+
34
+ # Optional dependencies with graceful fallbacks
35
+ try:
36
+ import yt_dlp
37
+ HAS_YT_DLP = True
38
+ except ImportError:
39
+ HAS_YT_DLP = False
40
+
41
+ try:
42
+ from youtube_transcript_api import YouTubeTranscriptApi
43
+ HAS_TRANSCRIPT_API = True
44
+ except ImportError:
45
+ HAS_TRANSCRIPT_API = False
46
+
47
+ PLUGIN_DIR = Path(__file__).parent.resolve()
48
+ PROJECT_ROOT = PLUGIN_DIR.parent.parent.resolve()
49
+ DEFAULT_OUTPUTS_DIR = get_plugin_outputs_dir(PLUGIN_DIR)
50
+ ALLOWED_YOUTUBE_DOMAINS = {"youtube.com", "www.youtube.com", "m.youtube.com", "youtu.be"}
51
+
52
+ USER_AGENTS = [
53
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
54
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
55
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
56
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0",
57
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0",
58
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_4_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4.1 Safari/605.1.15",
59
+ ]
60
+
61
+ # Standard mobile bypass extractor args for yt-dlp
62
+ COMMON_EXTRACTOR_ARGS = {
63
+ "youtube": {
64
+ "player_client": ["android", "ios", "mweb"]
65
+ }
66
+ }
67
+
68
+
69
+ def get_random_user_agent() -> str:
70
+ """Returns a randomly selected modern desktop User-Agent string."""
71
+ return random.choice(USER_AGENTS)
72
+
73
+
74
+ def _safe_urlopen(
75
+ req: Union[urllib.request.Request, str],
76
+ timeout: int = 15,
77
+ max_retries: int = 3
78
+ ) -> bytes:
79
+ """Safely executes an HTTP request with exponential backoff retry logic."""
80
+ for attempt in range(1, max_retries + 1):
81
+ try:
82
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
83
+ return resp.read()
84
+ except urllib.error.HTTPError as e:
85
+ if e.code in (429, 500, 502, 503, 504) and attempt < max_retries:
86
+ time.sleep(2 ** attempt)
87
+ continue
88
+ raise
89
+ except (urllib.error.URLError, TimeoutError):
90
+ if attempt < max_retries:
91
+ time.sleep(2 ** attempt)
92
+ continue
93
+ raise
94
+
95
+
96
+ def validate_output_dir(output_dir: Optional[Union[Path, str]] = None) -> Path:
97
+ """
98
+ Validates and resolves output directory boundaries to prevent Path Traversal.
99
+ Ensures that resolved paths stay within permitted project, plugin, or user data boundaries.
100
+ """
101
+ if output_dir is None:
102
+ target = get_plugin_outputs_dir(PLUGIN_DIR).resolve()
103
+ else:
104
+ target = Path(output_dir).expanduser().resolve()
105
+
106
+ if not is_allowed_output_dir(target, PLUGIN_DIR, PROJECT_ROOT):
107
+ raise ValueError(
108
+ f"Security error: Output directory '{target}' escapes allowed project or user data boundaries."
109
+ )
110
+
111
+ return target
112
+
113
+
114
+ def validate_youtube_url(url: str) -> str:
115
+ """Validates a YouTube URL against whitelist domains to prevent SSRF vulnerabilities."""
116
+ clean_url = url.strip()
117
+ if not clean_url:
118
+ raise ValueError("URL cannot be empty.")
119
+
120
+ if not clean_url.startswith(("http://", "https://")):
121
+ clean_url = f"https://www.youtube.com/{clean_url.lstrip('/')}"
122
+
123
+ parsed = urlparse(clean_url)
124
+ if parsed.scheme not in ("http", "https"):
125
+ raise ValueError(f"Security error: Invalid URL scheme '{parsed.scheme}'. Only HTTP/HTTPS allowed.")
126
+
127
+ hostname = (parsed.hostname or "").lower()
128
+ if hostname not in ALLOWED_YOUTUBE_DOMAINS:
129
+ raise ValueError(
130
+ f"Security error: Host '{hostname}' is not an authorized YouTube domain. "
131
+ f"Permitted: {', '.join(sorted(ALLOWED_YOUTUBE_DOMAINS))}"
132
+ )
133
+
134
+ return clean_url
135
+
136
+
137
+ def extract_video_id(url_or_id: str) -> str:
138
+ """Extract YouTube video ID from various URL formats or raw 11-char ID."""
139
+ url_str = url_or_id.strip()
140
+ if not url_str:
141
+ return ""
142
+
143
+ if len(url_str) == 11 and not ("/" in url_str or "?" in url_str or "&" in url_str):
144
+ return url_str
145
+
146
+ parsed = urlparse(url_str)
147
+
148
+ if parsed.hostname in ("youtu.be", "www.youtu.be"):
149
+ return parsed.path.lstrip("/").split("?")[0].split("&")[0]
150
+
151
+ if parsed.hostname in ("youtube.com", "www.youtube.com", "m.youtube.com"):
152
+ if parsed.path == "/watch":
153
+ queries = parse_qs(parsed.query)
154
+ if "v" in queries:
155
+ return queries["v"][0]
156
+ elif parsed.path.startswith(("/live/", "/shorts/", "/embed/", "/v/")):
157
+ parts = [p for p in parsed.path.split("/") if p]
158
+ if len(parts) >= 2:
159
+ return parts[1].split("?")[0].split("&")[0]
160
+
161
+ match = re.search(r"(?:v=|\/live\/|\/shorts\/|\/embed\/|\/v\/|youtu\.be\/)([a-zA-Z0-9_-]{11})", url_str)
162
+ if match:
163
+ return match.group(1)
164
+
165
+ return url_str
166
+
167
+
168
+ def get_content_type(url_or_id: str) -> str:
169
+ """Determines if the URL corresponds to shorts, live stream, or standard video."""
170
+ url_lower = url_or_id.lower()
171
+ if "/shorts/" in url_lower or "shorts" in url_lower:
172
+ return "shorts"
173
+ elif "/live/" in url_lower or "live" in url_lower:
174
+ return "live"
175
+ return "videos"
176
+
177
+
178
+ # ==============================================================================
179
+ # 1. TRANSCRIPT EXTRACTION
180
+ # ==============================================================================
181
+
182
+ def get_transcript(video_id_or_url: str) -> Dict[str, Any]:
183
+ """
184
+ Extract transcript using yt-dlp Android/iOS client bypass.
185
+ Bypasses YouTube bot checks without needing cookies or browser rendering.
186
+ """
187
+ video_id = extract_video_id(video_id_or_url)
188
+ if not video_id:
189
+ return {
190
+ "video_id": "",
191
+ "status": "error",
192
+ "error": "Invalid video ID or URL",
193
+ "text": "",
194
+ "segments": []
195
+ }
196
+
197
+ if HAS_YT_DLP:
198
+ url = f"https://www.youtube.com/watch?v={video_id}"
199
+ ydl_opts = {
200
+ "skip_download": True,
201
+ "writesubtitles": True,
202
+ "writeautomaticsub": True,
203
+ "subtitleslangs": ["en", "en-orig", "en-US", "en-GB"],
204
+ "extractor_args": COMMON_EXTRACTOR_ARGS,
205
+ "quiet": True,
206
+ "no_warnings": True,
207
+ }
208
+
209
+ try:
210
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
211
+ info = ydl.extract_info(url, download=False)
212
+ title = info.get("title", "")
213
+ subtitles = info.get("subtitles", {}) or {}
214
+ auto_captions = info.get("automatic_captions", {}) or {}
215
+
216
+ selected_sub = None
217
+ for lang in ["en", "en-orig", "en-US", "en-GB"]:
218
+ if lang in auto_captions:
219
+ selected_sub = auto_captions[lang]
220
+ break
221
+ if lang in subtitles:
222
+ selected_sub = subtitles[lang]
223
+ break
224
+
225
+ if not selected_sub:
226
+ if auto_captions:
227
+ selected_sub = next(iter(auto_captions.values()))
228
+ elif subtitles:
229
+ selected_sub = next(iter(subtitles.values()))
230
+
231
+ if not selected_sub:
232
+ return {
233
+ "video_id": video_id,
234
+ "title": title,
235
+ "status": "not_found",
236
+ "error": "No subtitles or captions found for this video",
237
+ "text": "",
238
+ "segments": []
239
+ }
240
+
241
+ json3_url = next((f["url"] for f in selected_sub if f.get("ext") == "json3"), None)
242
+ vtt_url = next((f["url"] for f in selected_sub if f.get("ext") == "vtt"), None)
243
+ target_url = json3_url or vtt_url or selected_sub[0].get("url")
244
+ sub_parsed = urlparse(target_url)
245
+ sub_host = (sub_parsed.hostname or "").lower()
246
+ if not (sub_host.endswith(".youtube.com") or sub_host == "youtube.com" or sub_host.endswith(".googlevideo.com") or sub_host == "googlevideo.com"):
247
+ return {
248
+ "video_id": video_id,
249
+ "status": "error",
250
+ "error": f"Security error: Subtitle URL host '{sub_host}' is not a trusted Google/YouTube domain",
251
+ "text": "",
252
+ "segments": []
253
+ }
254
+
255
+ req = urllib.request.Request(target_url, headers={"User-Agent": get_random_user_agent()})
256
+ raw_bytes = _safe_urlopen(req, timeout=12, max_retries=3)
257
+ raw_content = raw_bytes.decode("utf-8", errors="ignore")
258
+
259
+ segments = []
260
+ if json3_url:
261
+ cdata = json.loads(raw_content)
262
+ for ev in cdata.get("events", []):
263
+ segs = ev.get("segs", [])
264
+ t = "".join([s.get("utf8", "") for s in segs]).strip()
265
+ start_ms = ev.get("tStartMs", 0)
266
+ dur_ms = ev.get("dDurationMs", 0)
267
+ if t and t != "\n":
268
+ segments.append({
269
+ "text": t,
270
+ "start": start_ms / 1000.0,
271
+ "duration": dur_ms / 1000.0
272
+ })
273
+ else:
274
+ for line in raw_content.splitlines():
275
+ l = line.strip()
276
+ if not l or l.startswith("WEBVTT") or "-->" in l or l.isdigit():
277
+ continue
278
+ clean = re.sub(r"<[^>]+>", "", l)
279
+ if clean and (not segments or segments[-1]["text"] != clean):
280
+ segments.append({"text": clean, "start": 0.0, "duration": 0.0})
281
+
282
+ full_text = " ".join([s["text"] for s in segments])
283
+ return {
284
+ "video_id": video_id,
285
+ "title": title,
286
+ "status": "success",
287
+ "text": full_text,
288
+ "segments": segments,
289
+ "error": None
290
+ }
291
+ except Exception:
292
+ pass
293
+
294
+ # Fallback to youtube-transcript-api if yt-dlp failed or missing
295
+ if HAS_TRANSCRIPT_API:
296
+ try:
297
+ api = YouTubeTranscriptApi()
298
+ raw_data = api.fetch(video_id)
299
+ segments = []
300
+ for s in raw_data:
301
+ t = s.get("text", "") if isinstance(s, dict) else getattr(s, "text", "")
302
+ st = s.get("start", 0.0) if isinstance(s, dict) else getattr(s, "start", 0.0)
303
+ du = s.get("duration", 0.0) if isinstance(s, dict) else getattr(s, "duration", 0.0)
304
+ if t:
305
+ segments.append({"text": t, "start": st, "duration": du})
306
+ full_text = " ".join([s["text"] for s in segments])
307
+ return {
308
+ "video_id": video_id,
309
+ "status": "success",
310
+ "text": full_text,
311
+ "segments": segments,
312
+ "error": None
313
+ }
314
+ except Exception as e:
315
+ return {"video_id": video_id, "status": "error", "error": str(e), "text": "", "segments": []}
316
+
317
+ return {"video_id": video_id, "status": "error", "error": "No extraction engine available", "text": "", "segments": []}
318
+
319
+
320
+ # ==============================================================================
321
+ # 2. VIDEO METADATA SCRAPING
322
+ # ==============================================================================
323
+
324
+ def get_video_metadata(video_id_or_url: str) -> Dict[str, Any]:
325
+ """
326
+ Extract comprehensive video metadata:
327
+ Title, Description, Channel info, View count, Like count, Upload Date, Duration, Tags, etc.
328
+ """
329
+ video_id = extract_video_id(video_id_or_url)
330
+ if not video_id:
331
+ return {"video_id": "", "status": "error", "error": "Invalid video ID or URL"}
332
+
333
+ if not HAS_YT_DLP:
334
+ return {"video_id": video_id, "status": "error", "error": "yt-dlp is required for metadata extraction."}
335
+
336
+ url = f"https://www.youtube.com/watch?v={video_id}"
337
+ ydl_opts = {
338
+ "skip_download": True,
339
+ "quiet": True,
340
+ "no_warnings": True,
341
+ "extractor_args": COMMON_EXTRACTOR_ARGS
342
+ }
343
+
344
+ try:
345
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
346
+ info = ydl.extract_info(url, download=False)
347
+ metadata = {
348
+ "video_id": video_id,
349
+ "title": info.get("title", ""),
350
+ "description": info.get("description", ""),
351
+ "channel": info.get("uploader", "") or info.get("channel", ""),
352
+ "channel_id": info.get("channel_id", "") or info.get("uploader_id", ""),
353
+ "channel_url": info.get("channel_url", "") or info.get("uploader_url", ""),
354
+ "upload_date": info.get("upload_date", ""),
355
+ "duration": info.get("duration", 0),
356
+ "duration_string": info.get("duration_string", ""),
357
+ "view_count": info.get("view_count", 0),
358
+ "like_count": info.get("like_count", 0),
359
+ "comment_count": info.get("comment_count", 0),
360
+ "tags": info.get("tags", []) or [],
361
+ "categories": info.get("categories", []) or [],
362
+ "thumbnail": info.get("thumbnail", ""),
363
+ "age_limit": info.get("age_limit", 0),
364
+ "live_status": info.get("live_status", "not_live"),
365
+ "is_short": ("/shorts/" in video_id_or_url.lower()) or (info.get("duration", 0) <= 60 and info.get("aspect_ratio", 1.0) < 1.0),
366
+ "status": "success",
367
+ "error": None
368
+ }
369
+ return metadata
370
+ except Exception as e:
371
+ return {
372
+ "video_id": video_id,
373
+ "status": "error",
374
+ "error": str(e)
375
+ }
376
+
377
+
378
+ # ==============================================================================
379
+ # 3. COMMENTS EXTRACTION
380
+ # ==============================================================================
381
+
382
+ def get_video_comments(video_id_or_url: str, max_comments: int = 50) -> Dict[str, Any]:
383
+ """
384
+ Extracts top video comments and replies.
385
+ Returns structured list containing author, text, likes, timestamp, and reply counts.
386
+ """
387
+ video_id = extract_video_id(video_id_or_url)
388
+ if not video_id:
389
+ return {"video_id": "", "status": "error", "error": "Invalid video ID or URL", "comments": []}
390
+
391
+ if not HAS_YT_DLP:
392
+ return {"video_id": video_id, "status": "error", "error": "yt-dlp is required for comment extraction.", "comments": []}
393
+
394
+ url = f"https://www.youtube.com/watch?v={video_id}"
395
+ ydl_opts = {
396
+ "skip_download": True,
397
+ "getcomments": True,
398
+ "extractor_args": {
399
+ "youtube": {
400
+ "player_client": ["android", "ios", "mweb"],
401
+ "max_comments": [str(max_comments), "all", "all", "0"]
402
+ }
403
+ },
404
+ "quiet": True,
405
+ "no_warnings": True,
406
+ }
407
+
408
+ try:
409
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
410
+ info = ydl.extract_info(url, download=False)
411
+ raw_comments = info.get("comments", []) or []
412
+
413
+ clean_comments = []
414
+ for c in raw_comments[:max_comments]:
415
+ clean_comments.append({
416
+ "id": c.get("id", ""),
417
+ "author": c.get("author", ""),
418
+ "author_id": c.get("author_id", ""),
419
+ "text": c.get("text", ""),
420
+ "like_count": c.get("like_count", 0),
421
+ "timestamp": c.get("timestamp", 0),
422
+ "time_text": c.get("_time_text", ""),
423
+ "parent": c.get("parent", "root"),
424
+ "is_favorited": c.get("is_favorited", False),
425
+ "author_is_uploader": c.get("author_is_uploader", False)
426
+ })
427
+
428
+ return {
429
+ "video_id": video_id,
430
+ "status": "success",
431
+ "count": len(clean_comments),
432
+ "comments": clean_comments,
433
+ "error": None
434
+ }
435
+ except Exception as e:
436
+ return {
437
+ "video_id": video_id,
438
+ "status": "error",
439
+ "error": str(e),
440
+ "count": 0,
441
+ "comments": []
442
+ }
443
+
444
+
445
+ def _build_format_selector(resolution: str = "best") -> str:
446
+ """Builds yt-dlp format selector string based on chosen resolution."""
447
+ res_clean = (resolution or "best").strip().lower()
448
+ height_map = {
449
+ "360p": 360, "360": 360,
450
+ "480p": 480, "480": 480,
451
+ "720p": 720, "720": 720,
452
+ "1080p": 1080, "1080": 1080,
453
+ "1440p": 1440, "1440": 1440, "2k": 1440,
454
+ "2160p": 2160, "2160": 2160, "4k": 2160,
455
+ }
456
+ if res_clean == "worst":
457
+ return "worstvideo[ext=mp4]+worstaudio[ext=m4a]/worst"
458
+ if res_clean in height_map:
459
+ h = height_map[res_clean]
460
+ return f"bestvideo[height<={h}][ext=mp4]+bestaudio[ext=m4a]/best[height<={h}][ext=mp4]/best[height<={h}]/best"
461
+ return "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"
462
+
463
+
464
+ # ==============================================================================
465
+ # 4. MEDIA & THUMBNAIL DOWNLOADER
466
+ # ==============================================================================
467
+
468
+ def download_media(
469
+ video_id_or_url: str,
470
+ output_dir: Union[Path, str],
471
+ download_video: bool = True,
472
+ download_audio: bool = False,
473
+ download_thumbnail: bool = True,
474
+ quality: str = "best"
475
+ ) -> Dict[str, Any]:
476
+ """
477
+ Downloads the actual video file, audio, and/or thumbnail to the specified output directory.
478
+ Output filenames:
479
+ - video: output_dir / "video.%(ext)s"
480
+ - audio: output_dir / "audio.%(ext)s"
481
+ - thumbnail: output_dir / "thumbnail.%(ext)s"
482
+ """
483
+ video_id = extract_video_id(video_id_or_url)
484
+ if not video_id:
485
+ return {"video_id": "", "status": "error", "error": "Invalid video ID or URL"}
486
+
487
+ if not HAS_YT_DLP:
488
+ return {"video_id": video_id, "status": "error", "error": "yt-dlp is required for media downloading."}
489
+
490
+ target_dir = Path(output_dir)
491
+ target_dir.mkdir(parents=True, exist_ok=True)
492
+
493
+ url = f"https://www.youtube.com/watch?v={video_id}"
494
+ results: Dict[str, Any] = {
495
+ "video_id": video_id,
496
+ "status": "success",
497
+ "video_path": None,
498
+ "audio_path": None,
499
+ "thumbnail_path": None,
500
+ "error": None
501
+ }
502
+
503
+ try:
504
+ # Download Thumbnail
505
+ if download_thumbnail:
506
+ thumb_opts = {
507
+ "skip_download": True,
508
+ "writethumbnail": True,
509
+ "outtmpl": str(target_dir / "thumbnail.%(ext)s"),
510
+ "extractor_args": COMMON_EXTRACTOR_ARGS,
511
+ "quiet": True,
512
+ "no_warnings": True,
513
+ }
514
+ try:
515
+ with yt_dlp.YoutubeDL(thumb_opts) as ydl:
516
+ ydl.download([url])
517
+ # Locate saved thumbnail
518
+ for ext in ["jpg", "webp", "png", "jpeg"]:
519
+ p = target_dir / f"thumbnail.{ext}"
520
+ if p.exists():
521
+ results["thumbnail_path"] = str(p)
522
+ break
523
+ except Exception as e:
524
+ # Direct fallback for thumbnail URL
525
+ m = get_video_metadata(video_id)
526
+ if m.get("thumbnail"):
527
+ try:
528
+ req = urllib.request.Request(m["thumbnail"], headers={"User-Agent": get_random_user_agent()})
529
+ data = _safe_urlopen(req, timeout=10)
530
+ thumb_file = target_dir / "thumbnail.jpg"
531
+ with open(thumb_file, "wb") as f:
532
+ f.write(data)
533
+ results["thumbnail_path"] = str(thumb_file)
534
+ except Exception:
535
+ pass
536
+
537
+ # Download Video
538
+ if download_video:
539
+ video_format = _build_format_selector(quality)
540
+ video_opts = {
541
+ "format": video_format,
542
+ "outtmpl": str(target_dir / "video.%(ext)s"),
543
+ "extractor_args": COMMON_EXTRACTOR_ARGS,
544
+ "quiet": True,
545
+ "no_warnings": True,
546
+ }
547
+ with yt_dlp.YoutubeDL(video_opts) as ydl:
548
+ ydl.download([url])
549
+ for ext in ["mp4", "webm", "mkv"]:
550
+ p = target_dir / f"video.{ext}"
551
+ if p.exists():
552
+ results["video_path"] = str(p)
553
+ break
554
+
555
+ # Download Audio Only
556
+ if download_audio:
557
+ audio_opts = {
558
+ "format": "bestaudio/best",
559
+ "outtmpl": str(target_dir / "audio.%(ext)s"),
560
+ "extractor_args": COMMON_EXTRACTOR_ARGS,
561
+ "quiet": True,
562
+ "no_warnings": True,
563
+ }
564
+ with yt_dlp.YoutubeDL(audio_opts) as ydl:
565
+ ydl.download([url])
566
+ for ext in ["mp3", "m4a", "webm"]:
567
+ p = target_dir / f"audio.{ext}"
568
+ if p.exists():
569
+ results["audio_path"] = str(p)
570
+ break
571
+
572
+ return results
573
+
574
+ except Exception as e:
575
+ results["status"] = "error"
576
+ results["error"] = str(e)
577
+ return results
578
+
579
+
580
+ # ==============================================================================
581
+ # 5. CHANNEL VIDEO DISCOVERY
582
+ # ==============================================================================
583
+
584
+ def _parse_yt_initial_data(html: str) -> Optional[Dict[str, Any]]:
585
+ """Extracts and decodes the ytInitialData JSON structure from YouTube channel HTML."""
586
+ pattern = r"var ytInitialData\s*=\s*({.*?});</script>"
587
+ match = re.search(pattern, html, re.DOTALL)
588
+ if not match:
589
+ pattern = r"ytInitialData\s*=\s*({.*?});"
590
+ match = re.search(pattern, html, re.DOTALL)
591
+
592
+ if not match:
593
+ return None
594
+
595
+ try:
596
+ return json.loads(match.group(1))
597
+ except json.JSONDecodeError:
598
+ return None
599
+
600
+
601
+ def _extract_videos_from_data(
602
+ data: Dict[str, Any],
603
+ content_type: str,
604
+ limit: int,
605
+ seen_ids: set
606
+ ) -> List[Dict[str, str]]:
607
+ """Extracts video metadata items from parsed ytInitialData structure."""
608
+ video_items: List[Dict[str, str]] = []
609
+ tabs = data.get("contents", {}).get("twoColumnBrowseResultsRenderer", {}).get("tabs", [])
610
+
611
+ for tab in tabs:
612
+ tab_renderer = tab.get("tabRenderer", {})
613
+ if not tab_renderer.get("selected", False):
614
+ continue
615
+
616
+ content = tab_renderer.get("content", {})
617
+ rich_grid = content.get("richGridRenderer", {})
618
+ contents = rich_grid.get("contents", [])
619
+
620
+ for item in contents:
621
+ rich_item = item.get("richItemRenderer", {}).get("content", {})
622
+ renderer = rich_item.get("videoRenderer") or rich_item.get("reelItemRenderer")
623
+ if not renderer:
624
+ continue
625
+
626
+ vid = renderer.get("videoId")
627
+ if not vid or vid in seen_ids:
628
+ continue
629
+
630
+ title_obj = renderer.get("title", {})
631
+ title = ""
632
+ if "runs" in title_obj and title_obj["runs"]:
633
+ title = title_obj["runs"][0].get("text", "")
634
+ elif "simpleText" in title_obj:
635
+ title = title_obj["simpleText"]
636
+
637
+ seen_ids.add(vid)
638
+ video_items.append({
639
+ "id": vid,
640
+ "title": title,
641
+ "type": content_type,
642
+ "url": f"https://www.youtube.com/watch?v={vid}" if content_type != "shorts" else f"https://www.youtube.com/shorts/{vid}"
643
+ })
644
+
645
+ if len(video_items) >= limit:
646
+ return video_items
647
+
648
+ return video_items
649
+
650
+
651
+ def _extract_videos_from_html_fallback(
652
+ html: str,
653
+ content_type: str,
654
+ limit: int,
655
+ seen_ids: set
656
+ ) -> List[Dict[str, str]]:
657
+ """Regex fallback to extract video IDs directly from HTML when ytInitialData parsing fails."""
658
+ video_items: List[Dict[str, str]] = []
659
+ found_ids = re.findall(r'"videoId":"([a-zA-Z0-9_-]{11})"', html)
660
+ for vid in found_ids:
661
+ if vid not in seen_ids:
662
+ seen_ids.add(vid)
663
+ video_items.append({
664
+ "id": vid,
665
+ "title": "",
666
+ "type": content_type,
667
+ "url": f"https://www.youtube.com/watch?v={vid}"
668
+ })
669
+ if len(video_items) >= limit:
670
+ break
671
+ return video_items
672
+
673
+
674
+ def get_channel_videos(
675
+ channel_url: str,
676
+ content_type: str = "videos",
677
+ limit: int = 10
678
+ ) -> List[Dict[str, str]]:
679
+ """
680
+ Scrapes video IDs and titles from a YouTube channel tab.
681
+ content_type: "videos", "streams" (or "live"), "shorts", or "all"
682
+ """
683
+ clean_url = validate_youtube_url(channel_url).rstrip("/")
684
+
685
+ types_to_fetch = []
686
+ if content_type in ("all", "both"):
687
+ types_to_fetch = ["videos", "streams", "shorts"]
688
+ elif content_type in ("streams", "live"):
689
+ types_to_fetch = ["streams"]
690
+ elif content_type in ("shorts", "short"):
691
+ types_to_fetch = ["shorts"]
692
+ else:
693
+ types_to_fetch = ["videos"]
694
+
695
+ all_videos = []
696
+ seen_ids = set()
697
+
698
+ for ctype in types_to_fetch:
699
+ base_clean = re.sub(r"/(videos|streams|shorts|playlists|community|about)$", "", clean_url)
700
+ target_url = f"{base_clean}/{ctype}"
701
+
702
+ headers = {
703
+ "User-Agent": get_random_user_agent(),
704
+ "Accept-Language": "en-US,en;q=0.9",
705
+ }
706
+
707
+ try:
708
+ req = urllib.request.Request(target_url, headers=headers)
709
+ raw_bytes = _safe_urlopen(req, timeout=15, max_retries=3)
710
+ html = raw_bytes.decode("utf-8", errors="ignore")
711
+ except Exception:
712
+ continue
713
+
714
+ remaining_limit = limit - len(all_videos) if content_type not in ("all", "both") else limit
715
+ video_items = []
716
+
717
+ data = _parse_yt_initial_data(html)
718
+ if data:
719
+ video_items = _extract_videos_from_data(data, ctype, remaining_limit, seen_ids)
720
+
721
+ if not video_items:
722
+ video_items = _extract_videos_from_html_fallback(html, ctype, remaining_limit, seen_ids)
723
+
724
+ all_videos.extend(video_items)
725
+ if len(all_videos) >= limit and content_type not in ("all", "both"):
726
+ break
727
+
728
+ return all_videos[:limit] if content_type not in ("all", "both") else all_videos
729
+
730
+
731
+ # ==============================================================================
732
+ # 6. UNIFIED BUNDLE SCRAPER (Scrapes & saves into Outputs/ hierarchy)
733
+ # ==============================================================================
734
+
735
+ def scrape_youtube_item(
736
+ url_or_id: str,
737
+ output_base_dir: Optional[Union[Path, str]] = None,
738
+ content_type: Optional[str] = None,
739
+ fetch_transcript: bool = True,
740
+ fetch_metadata: bool = True,
741
+ fetch_comments: bool = False,
742
+ download_video_file: bool = False,
743
+ download_thumb_file: bool = False,
744
+ video_quality: str = "best",
745
+ max_comments: int = 50,
746
+ sandbox_transcript: bool = True,
747
+ ) -> Dict[str, Any]:
748
+ """
749
+ Unified end-to-end extraction function for a single YouTube item.
750
+ Organizes results into the standard Hub-and-Spoke folder hierarchy:
751
+ Outputs/videos/<video_id>/
752
+ Outputs/shorts/<short_id>/
753
+ Outputs/live/<live_id>/
754
+ """
755
+ vid = extract_video_id(url_or_id)
756
+ if not vid:
757
+ return {"video_id": "", "status": "error", "error": "Invalid video ID or URL"}
758
+
759
+ ctype = content_type or get_content_type(url_or_id)
760
+ base_dir = validate_output_dir(output_base_dir)
761
+ item_dir = base_dir / ctype / vid
762
+ item_dir.mkdir(parents=True, exist_ok=True)
763
+
764
+ result_bundle: Dict[str, Any] = {
765
+ "video_id": vid,
766
+ "content_type": ctype,
767
+ "item_directory": str(item_dir),
768
+ "transcript": None,
769
+ "metadata": None,
770
+ "comments": None,
771
+ "media": None,
772
+ "status": "success",
773
+ "errors": []
774
+ }
775
+
776
+ # 1. Transcript
777
+ if fetch_transcript:
778
+ t_res = get_transcript(vid)
779
+ result_bundle["transcript"] = t_res
780
+ if t_res["status"] == "success":
781
+ txt_path = item_dir / "transcript.txt"
782
+ content = f"<transcript>\n{escape(t_res['text'])}\n</transcript>" if sandbox_transcript else t_res["text"]
783
+ with open(txt_path, "w", encoding="utf-8") as f:
784
+ f.write(content)
785
+ json_path = item_dir / "transcript.json"
786
+ with open(json_path, "w", encoding="utf-8") as f:
787
+ json.dump(t_res, f, ensure_ascii=False, indent=2)
788
+ elif t_res.get("error"):
789
+ result_bundle["errors"].append(f"Transcript: {t_res['error']}")
790
+
791
+ # 2. Metadata
792
+ if fetch_metadata:
793
+ m_res = get_video_metadata(vid)
794
+ result_bundle["metadata"] = m_res
795
+ if m_res.get("status") == "success":
796
+ meta_path = item_dir / "metadata.json"
797
+ with open(meta_path, "w", encoding="utf-8") as f:
798
+ json.dump(m_res, f, ensure_ascii=False, indent=2)
799
+ elif m_res.get("error"):
800
+ result_bundle["errors"].append(f"Metadata: {m_res['error']}")
801
+
802
+ # 3. Comments
803
+ if fetch_comments:
804
+ c_res = get_video_comments(vid, max_comments=max_comments)
805
+ result_bundle["comments"] = c_res
806
+ if c_res.get("status") == "success":
807
+ comm_path = item_dir / "comments.json"
808
+ with open(comm_path, "w", encoding="utf-8") as f:
809
+ json.dump(c_res, f, ensure_ascii=False, indent=2)
810
+ elif c_res.get("error"):
811
+ result_bundle["errors"].append(f"Comments: {c_res['error']}")
812
+
813
+ # 4. Media & Thumbnail
814
+ if download_video_file or download_thumb_file:
815
+ d_res = download_media(
816
+ vid,
817
+ output_dir=item_dir,
818
+ download_video=download_video_file,
819
+ download_thumbnail=download_thumb_file,
820
+ quality=video_quality
821
+ )
822
+ result_bundle["media"] = d_res
823
+ if d_res.get("status") != "success" and d_res.get("error"):
824
+ result_bundle["errors"].append(f"Media download: {d_res['error']}")
825
+
826
+ if len(result_bundle["errors"]) > 0 and not (result_bundle["transcript"] or result_bundle["metadata"]):
827
+ result_bundle["status"] = "error"
828
+
829
+ return result_bundle