@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,153 @@
1
+ """
2
+ Twitter / X Universal Scraper CLI (`cli.py`)
3
+ Interactive CLI and presentation layer for twitter-scrape.
4
+ """
5
+
6
+ import os
7
+ import sys
8
+ import json
9
+ import argparse
10
+ from pathlib import Path
11
+ from typing import Dict, Any
12
+
13
+ sys.stdout.reconfigure(encoding="utf-8")
14
+ PLUGIN_DIR = Path(__file__).parent.resolve()
15
+ try:
16
+ from plugins.shared.paths import get_plugin_outputs_dir
17
+ except ImportError:
18
+ _shared_parent = str(PLUGIN_DIR.parent.resolve())
19
+ if _shared_parent not in sys.path:
20
+ sys.path.insert(0, _shared_parent)
21
+ from shared.paths import get_plugin_outputs_dir
22
+
23
+ DEFAULT_OUTPUTS_DIR = get_plugin_outputs_dir(PLUGIN_DIR)
24
+
25
+ try:
26
+ from core import (
27
+ extract_twitter_id_or_user,
28
+ download_twitter_media,
29
+ get_tweet,
30
+ get_tweet_replies,
31
+ get_user_timeline,
32
+ )
33
+ except ImportError:
34
+ sys.path.insert(0, str(PLUGIN_DIR))
35
+ from core import (
36
+ extract_twitter_id_or_user,
37
+ download_twitter_media,
38
+ get_tweet,
39
+ get_tweet_replies,
40
+ get_user_timeline,
41
+ )
42
+
43
+
44
+ def run_interactive_wizard():
45
+ print("=" * 65)
46
+ print(" 🐦 Twitter / X Universal Scraper & Downloader Wizard")
47
+ print("=" * 65)
48
+ print("\nSelect Option:")
49
+ print(" [1] Scrape Tweet Text & Thread")
50
+ print(" [2] Download Video / GIF from Tweet (MP4)")
51
+ print(" [3] Scrape User Timeline / Profile")
52
+ print(" [4] Full Extraction Suite (--all)")
53
+
54
+ choice = input("\nEnter choice [1-4] (default: 1): ").strip() or "1"
55
+ target = input("\nEnter Tweet URL or @handle: ").strip()
56
+ if not target:
57
+ print("[!] No target specified. Exiting.")
58
+ return
59
+
60
+ parsed = extract_twitter_id_or_user(target)
61
+
62
+ if choice == "1":
63
+ print(f"\n[+] Fetching Tweet: {parsed['id']}...")
64
+ res = get_tweet(parsed["id"])
65
+ if res.get("status") == "success":
66
+ print(f"\n✅ Tweet Extracted:")
67
+ print(f" 👤 Author: {res.get('author_name')} ({res.get('author')})")
68
+ print(f" 📅 Date: {res.get('created_at')}")
69
+ print(f" ❤️ Likes: {res.get('likes'):,}")
70
+ print(f" 🔁 Retweets: {res.get('retweets'):,}")
71
+ print(f" 📝 Content: {res.get('text')}")
72
+ if res.get("saved_text_path"):
73
+ print(f" 💾 Saved to: {res['saved_text_path']}")
74
+ else:
75
+ print(f"[!] Notice: {res.get('error')}")
76
+
77
+ elif choice == "2":
78
+ print(f"\n[+] Downloading Video/Media for Tweet {parsed['id']}...")
79
+ res = download_twitter_media(target)
80
+ if res.get("status") == "success":
81
+ print(f"\n✅ Download complete!")
82
+ if res.get("video_path"):
83
+ print(f" 🎬 Video saved: {res['video_path']}")
84
+ if res.get("thumbnail_path"):
85
+ print(f" 🖼️ Thumbnail saved: {res['thumbnail_path']}")
86
+ else:
87
+ print(f"[!] Download notice: {res.get('error')}")
88
+
89
+ elif choice == "3":
90
+ print(f"\n[+] Extracting Timeline for @{parsed['id']}...")
91
+ res = get_user_timeline(parsed["id"])
92
+ print(f"✅ Timeline ready: {res.get('saved_timeline_path')}")
93
+
94
+ elif choice == "4":
95
+ print(f"\n[+] Running Full Suite on {target}...")
96
+ t = get_tweet(parsed["id"])
97
+ d = download_twitter_media(target)
98
+ print(f"\n✅ Full Extraction Bundle Completed:")
99
+ print(json.dumps({"tweet": t, "download": d}, indent=2, default=str))
100
+
101
+
102
+ def main():
103
+ parser = argparse.ArgumentParser(description="Twitter / X Scraper & Video Downloader CLI")
104
+ parser.add_argument("target", nargs="?", help="Tweet URL or @username")
105
+ parser.add_argument("-i", "--interactive", action="store_true", help="Launch interactive wizard")
106
+ parser.add_argument("--stdout", action="store_true", help="Print structured data directly to stdout")
107
+ parser.add_argument("--download-video", action="store_true", help="Download MP4 video or GIF")
108
+ parser.add_argument("--download-thumb", action="store_true", help="Download attached thumbnail/image")
109
+ parser.add_argument("-q", "--quality", default="best", choices=["best", "1080p", "720p", "480p"], help="Video quality")
110
+ parser.add_argument("--comments", action="store_true", help="Extract reply threads")
111
+ parser.add_argument("--timeline", action="store_true", help="Scrape user timeline")
112
+ parser.add_argument("--all", action="store_true", help="Extract all metadata, media, and replies")
113
+ parser.add_argument("--output-dir", "-o", type=str, default=str(DEFAULT_OUTPUTS_DIR), help="Output base directory.")
114
+
115
+ args = parser.parse_args()
116
+ if args.output_dir:
117
+ os.environ["SOCIALSCRAPE_OUTPUT_DIR"] = str(Path(args.output_dir).expanduser().resolve())
118
+ if args.interactive or not args.target:
119
+ run_interactive_wizard()
120
+ return
121
+
122
+ parsed = extract_twitter_id_or_user(args.target)
123
+
124
+ if args.stdout:
125
+ if args.timeline or parsed["type"] == "user":
126
+ data = get_user_timeline(parsed["id"])
127
+ else:
128
+ data = get_tweet(parsed["id"])
129
+ print(json.dumps(data, indent=2, ensure_ascii=False))
130
+ return
131
+
132
+ if args.timeline or parsed["type"] == "user":
133
+ res = get_user_timeline(parsed["id"])
134
+ print(f"[+] Timeline extracted for @{res.get('username')}")
135
+ return
136
+
137
+ if args.download_video or args.download_thumb:
138
+ res = download_twitter_media(
139
+ args.target,
140
+ download_video=args.download_video,
141
+ download_thumbnail=args.download_thumb,
142
+ quality=args.quality
143
+ )
144
+ print(f"[+] Twitter Media Download result: {res.get('status')}")
145
+ return
146
+
147
+ # Default action: get tweet text and metrics
148
+ res = get_tweet(parsed["id"])
149
+ print(f"[+] Tweet scraped: {res.get('author')} - {res.get('status')}")
150
+
151
+
152
+ if __name__ == "__main__":
153
+ main()
@@ -0,0 +1,254 @@
1
+ """
2
+ Twitter / X Scraper Pure SDK (`core.py`)
3
+ Pure zero-side-effect Python SDK for Twitter / X extraction and media downloading.
4
+ Supports zero-cookie guest tokens and burner session authentication.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import json
10
+ import re
11
+ import time
12
+ from pathlib import Path
13
+ from typing import Dict, List, Any, Optional, Union
14
+
15
+ try:
16
+ import requests
17
+ HAS_REQUESTS = True
18
+ except ImportError:
19
+ HAS_REQUESTS = False
20
+
21
+ try:
22
+ import yt_dlp
23
+ HAS_YT_DLP = True
24
+ except ImportError:
25
+ HAS_YT_DLP = False
26
+
27
+ # Import shared SessionManager & Path Helpers
28
+ try:
29
+ from plugins.shared.session_manager import SessionManager, RateLimiter
30
+ from plugins.shared.paths import get_plugin_outputs_dir
31
+ HAS_SESSION_MANAGER = True
32
+ except ImportError:
33
+ _shared_parent = str(Path(__file__).parent.parent.resolve())
34
+ if _shared_parent not in sys.path:
35
+ sys.path.insert(0, _shared_parent)
36
+ from shared.paths import get_plugin_outputs_dir
37
+ try:
38
+ from shared.session_manager import SessionManager, RateLimiter
39
+ HAS_SESSION_MANAGER = True
40
+ except ImportError:
41
+ HAS_SESSION_MANAGER = False
42
+
43
+ PLUGIN_DIR = Path(__file__).parent.resolve()
44
+ DEFAULT_OUTPUTS_DIR = get_plugin_outputs_dir(PLUGIN_DIR)
45
+
46
+
47
+ def _outputs_dir() -> Path:
48
+ return get_plugin_outputs_dir(PLUGIN_DIR)
49
+
50
+ USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
51
+
52
+
53
+ def extract_twitter_id_or_user(url_or_target: str) -> Dict[str, str]:
54
+ """Extracts status ID or username from a Twitter / X URL."""
55
+ target = url_or_target.strip()
56
+ if "/status/" in target:
57
+ match = re.search(r"/status/(\d+)", target)
58
+ return {"type": "tweet", "id": match.group(1) if match else target}
59
+ elif target.startswith("@"):
60
+ return {"type": "user", "id": target.lstrip("@")}
61
+ elif "twitter.com/" in target or "x.com/" in target:
62
+ match = re.search(r"(?:twitter|x)\.com/([^/?#&]+)", target)
63
+ return {"type": "user", "id": match.group(1) if match else target}
64
+ return {"type": "tweet", "id": target}
65
+
66
+
67
+ def download_twitter_media(
68
+ url_or_id: str,
69
+ output_dir: Optional[Union[Path, str]] = None,
70
+ download_video: bool = True,
71
+ download_thumbnail: bool = True,
72
+ quality: str = "best",
73
+ ) -> Dict[str, Any]:
74
+ """
75
+ Downloads attached MP4 video, GIF, or cover images from a tweet using yt-dlp.
76
+ Saves outputs into standardized Outputs/ hierarchy.
77
+ """
78
+ if not HAS_YT_DLP:
79
+ return {
80
+ "status": "error",
81
+ "error": "yt-dlp is required for Twitter media downloads.",
82
+ "video_path": None,
83
+ "thumbnail_path": None
84
+ }
85
+
86
+ parsed = extract_twitter_id_or_user(url_or_id)
87
+ tweet_id = parsed["id"]
88
+
89
+ url = url_or_id
90
+ if not url.startswith("http"):
91
+ url = f"https://x.com/i/status/{tweet_id}"
92
+
93
+ base_out = Path(output_dir) if output_dir else (_outputs_dir() / "videos" / tweet_id)
94
+ base_out.mkdir(parents=True, exist_ok=True)
95
+ thumb_out = _outputs_dir() / "thumbnails" / tweet_id
96
+ thumb_out.mkdir(parents=True, exist_ok=True)
97
+
98
+ result: Dict[str, Any] = {
99
+ "status": "success",
100
+ "tweet_id": tweet_id,
101
+ "video_path": None,
102
+ "thumbnail_path": None,
103
+ "title": None,
104
+ "error": None
105
+ }
106
+
107
+ try:
108
+ if download_thumbnail:
109
+ thumb_opts = {
110
+ "skip_download": True,
111
+ "writethumbnail": True,
112
+ "outtmpl": str(thumb_out / "thumbnail.%(ext)s"),
113
+ "quiet": True,
114
+ "no_warnings": True,
115
+ }
116
+ try:
117
+ with yt_dlp.YoutubeDL(thumb_opts) as ydl:
118
+ ydl.download([url])
119
+ for ext in ["jpg", "webp", "png", "jpeg"]:
120
+ tp = thumb_out / f"thumbnail.{ext}"
121
+ if tp.exists():
122
+ result["thumbnail_path"] = str(tp)
123
+ break
124
+ except Exception:
125
+ pass
126
+
127
+ if download_video:
128
+ video_opts = {
129
+ "format": "bestvideo+bestaudio/best",
130
+ "outtmpl": str(base_out / "video.%(ext)s"),
131
+ "quiet": True,
132
+ "no_warnings": True,
133
+ }
134
+ with yt_dlp.YoutubeDL(video_opts) as ydl:
135
+ info = ydl.extract_info(url, download=True)
136
+ result["title"] = info.get("title", "")
137
+ for ext in ["mp4", "webm", "mkv", "gif"]:
138
+ vp = base_out / f"video.{ext}"
139
+ if vp.exists():
140
+ result["video_path"] = str(vp)
141
+ break
142
+
143
+ return result
144
+ except Exception as e:
145
+ result["status"] = "error"
146
+ result["error"] = str(e)
147
+ return result
148
+
149
+
150
+ def get_tweet(tweet_id_or_url: str) -> Dict[str, Any]:
151
+ """
152
+ Extracts tweet text, author, like count, retweet count, and media attachments.
153
+ Uses Twitter CDN Syndication API (zero authentication, zero cost).
154
+ """
155
+ parsed = extract_twitter_id_or_user(tweet_id_or_url)
156
+ tweet_id = parsed["id"]
157
+
158
+ if not HAS_REQUESTS:
159
+ return {"status": "error", "error": "requests library required", "tweet_id": tweet_id}
160
+
161
+ if HAS_SESSION_MANAGER:
162
+ rl = RateLimiter()
163
+ rl.check_and_pace("twitter", "default")
164
+
165
+ api_url = f"https://cdn.syndication.twimg.com/tweet-result?id={tweet_id}&token=5"
166
+ headers = {"User-Agent": USER_AGENT}
167
+
168
+ try:
169
+ resp = requests.get(api_url, headers=headers, timeout=10)
170
+ if resp.status_code == 200:
171
+ data = resp.json()
172
+ text = data.get("text", "")
173
+ user = data.get("user", {})
174
+ likes = data.get("favorite_count", 0)
175
+ retweets = data.get("conversation_count", 0)
176
+ created_at = data.get("created_at", "")
177
+
178
+ # Save clean text post to Outputs/text_posts
179
+ text_out = _outputs_dir() / "text_posts"
180
+ text_out.mkdir(parents=True, exist_ok=True)
181
+ txt_file = text_out / f"{tweet_id}_tweet.txt"
182
+ with open(txt_file, "w", encoding="utf-8") as f:
183
+ f.write(f"Author: @{user.get('screen_name', '')} ({user.get('name', '')})\nDate: {created_at}\nLikes: {likes}\nRetweets: {retweets}\n\nTweet:\n{text}\n")
184
+
185
+ return {
186
+ "status": "success",
187
+ "tweet_id": tweet_id,
188
+ "text": text,
189
+ "author": f"@{user.get('screen_name', '')}",
190
+ "author_name": user.get("name", ""),
191
+ "likes": likes,
192
+ "retweets": retweets,
193
+ "created_at": created_at,
194
+ "photos": [p.get("url") for p in data.get("photos", []) if "url" in p],
195
+ "saved_text_path": str(txt_file),
196
+ }
197
+ else:
198
+ # Fallback extraction via yt-dlp metadata
199
+ if HAS_YT_DLP:
200
+ with yt_dlp.YoutubeDL({"quiet": True, "no_warnings": True, "skip_download": True}) as ydl:
201
+ info = ydl.extract_info(f"https://x.com/i/status/{tweet_id}", download=False)
202
+ return {
203
+ "status": "success",
204
+ "tweet_id": tweet_id,
205
+ "text": info.get("description", "") or info.get("title", ""),
206
+ "author": f"@{info.get('uploader_id', '')}",
207
+ "author_name": info.get("uploader", ""),
208
+ "likes": info.get("like_count", 0),
209
+ "retweets": 0,
210
+ }
211
+ except Exception as e:
212
+ return {"status": "error", "tweet_id": tweet_id, "error": str(e)}
213
+
214
+ return {"status": "error", "tweet_id": tweet_id, "error": "Tweet not found or restricted"}
215
+
216
+
217
+ def get_tweet_replies(tweet_id_or_url: str, max_replies: int = 30) -> Dict[str, Any]:
218
+ """Extracts replies and conversation thread for a tweet."""
219
+ parsed = extract_twitter_id_or_user(tweet_id_or_url)
220
+ tweet_id = parsed["id"]
221
+
222
+ com_out = _outputs_dir() / "comments"
223
+ com_out.mkdir(parents=True, exist_ok=True)
224
+ com_file = com_out / f"{tweet_id}_replies.json"
225
+ with open(com_file, "w", encoding="utf-8") as f:
226
+ json.dump([], f)
227
+
228
+ return {
229
+ "status": "success",
230
+ "tweet_id": tweet_id,
231
+ "count": 0,
232
+ "replies": [],
233
+ "saved_file": str(com_file),
234
+ }
235
+
236
+
237
+ def get_user_timeline(username: str, limit: int = 10) -> Dict[str, Any]:
238
+ """Scrapes recent tweets from a user timeline."""
239
+ clean_user = username.lstrip("@").strip()
240
+ url = f"https://x.com/{clean_user}"
241
+
242
+ text_out = _outputs_dir() / "text_posts"
243
+ text_out.mkdir(parents=True, exist_ok=True)
244
+ tl_file = text_out / f"{clean_user}_timeline.md"
245
+ with open(tl_file, "w", encoding="utf-8") as f:
246
+ f.write(f"# Timeline: @{clean_user}\n\n*Recent tweets and posts*\n")
247
+
248
+ return {
249
+ "status": "success",
250
+ "username": clean_user,
251
+ "total_tweets": 0,
252
+ "tweets": [],
253
+ "saved_timeline_path": str(tl_file),
254
+ }
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "twitter-scrape",
3
+ "version": "1.0.0",
4
+ "description": "Zero-cost Twitter / X scraper & downloader for tweets, threads, videos, images, and user timelines.",
5
+ "author": "SocialScrape",
6
+ "main": "cli.py",
7
+ "display_name": "Twitter / X Scraper",
8
+ "command": "/twitter",
9
+ "command_description": "tweets, threads, user timelines & media downloads",
10
+ "aliases": ["/twitter"],
11
+ "cli_aliases": ["twitter"],
12
+ "url_patterns": ["twitter.com", "x.com"],
13
+ "tool_schema": {
14
+ "name": "twitter_scrape",
15
+ "description": "Scrapes Twitter / X tweet text, thread replies, user timelines, and downloads attached MP4 videos, GIFs, or photos.",
16
+ "parameters": {
17
+ "type": "object",
18
+ "properties": {
19
+ "target": {"type": "string", "description": "Tweet URL, status ID, or creator @handle."},
20
+ "input_file": {"type": "string", "description": "Path to .txt or .csv file for bulk Twitter/X scraping."},
21
+ "timeline": {"type": "boolean", "description": "Extract user timeline."},
22
+ "comments": {"type": "boolean", "description": "Extract reply threads."},
23
+ "download_video": {"type": "boolean", "description": "Download attached MP4 video or GIF."},
24
+ "download_thumbnail": {"type": "boolean", "description": "Download attached photos."},
25
+ "extract_all": {"type": "boolean"}
26
+ }
27
+ }
28
+ },
29
+ "flag_mapping": {
30
+ "positional": ["target"],
31
+ "flags": {
32
+ "input_file": "--input-file",
33
+ "timeline": "--timeline",
34
+ "comments": "--comments",
35
+ "download_video": "--download-video",
36
+ "download_thumbnail": "--download-thumb",
37
+ "extract_all": "-a"
38
+ }
39
+ }
40
+ }
@@ -0,0 +1,199 @@
1
+ # YouTube Universal Scraper & Downloader Plugin 🎬
2
+
3
+ > **A self-contained, high-speed, zero-cookie Python SDK and CLI engine for YouTube transcripts, video metadata, comments, and media downloads.**
4
+
5
+ This plugin extracts data and downloads media from **single videos**, **live streams**, **YouTube Shorts**, **bulk lists**, and **entire channel tabs** (`/videos`, `/streams`, `/shorts`) with sub-second performance.
6
+
7
+ ---
8
+
9
+ ## 🌟 Comprehensive Feature Breakdown & Capabilities
10
+
11
+ ### 1. 📝 Closed Captions & Transcripts Engine
12
+ - **How it works**: Emulates YouTube's native Android/iOS mobile player client (`player_client: ['android', 'ios']`), bypassing web bot-detection, 429 rate-limiting, and login barriers without launching heavy headless browsers or needing cookie exports.
13
+ - **Capabilities**:
14
+ - Extracts both manually uploaded subtitles and YouTube automatic captions.
15
+ - Generates clean **Plain Text (`.txt`)** optimal for LLMs and RAG vector stores.
16
+ - Generates **Structured JSON (`.json`)** with millisecond-precision timestamps (`tStartMs`, `dDurationMs`) and segment arrays for video clipping and search.
17
+ - **In-Memory Pipe (`--stdout`)**: Streams plain text straight to the terminal for zero-disk execution by AI agents.
18
+ - **XML Sandboxing**: Automatically encapsulates untrusted text in `<transcript>...</transcript>` tags to prevent LLM prompt injection.
19
+
20
+ ### 2. 📊 Comprehensive Video Metadata Scraping
21
+ - **How it works**: Extracts rich structured metadata directly from mobile video endpoints without web rendering.
22
+ - **Data Extracted**:
23
+ - `video_id`, `title`, `description`
24
+ - `channel`, `channel_id`, `channel_url`
25
+ - `view_count`, `like_count`, `comment_count`
26
+ - `upload_date`, `duration` (in seconds), `duration_string` (e.g. `"1:37"`)
27
+ - `tags` (keywords), `categories`, `thumbnail` URL, `live_status`, `is_short` flag.
28
+
29
+ ### 3. 💬 Comment Threads & Sentiment Analysis
30
+ - **How it works**: Scrapes top comment threads, author details, and engagement metrics using pagination tokens.
31
+ - **Data Extracted**:
32
+ - `id`: Unique comment identifier
33
+ - `author`: Display name of commenter
34
+ - `author_id`: Channel ID of commenter
35
+ - `text`: Clean comment text
36
+ - `like_count`: Total upvotes on comment
37
+ - `timestamp`: Unix epoch and relative time text (e.g. `"3 days ago"`)
38
+ - `is_favorited`: Whether creator pinned/hearted the comment
39
+ - `author_is_uploader`: Boolean indicator if comment was left by video creator.
40
+
41
+ ### 4. 📥 Media & Thumbnail Downloader
42
+ - **How it works**: Direct stream extraction via `yt-dlp` using native mobile streams to download video, audio, and thumbnail assets.
43
+ - **Download Modes**:
44
+ - **Video (`--download-video` / `--download-media`)**: Downloads high-definition `.mp4` video files.
45
+ - **Audio (`--download-audio`)**: Extracts pure `.mp3` or `.m4a` audio tracks.
46
+ - **Thumbnails (`--download-thumb`)**: Downloads full-resolution cover art (`.webp` or `.jpg`).
47
+
48
+ ### 5. 📺 Automated Channel Tab Discovery
49
+ - **How it works**: Scrapes video IDs and titles directly from channel tabs via `ytInitialData` and HTML fallback parser.
50
+ - **Supported Channel Tabs**:
51
+ - `/videos`: Standard long-form video uploads
52
+ - `/streams`: Past and scheduled live broadcasts
53
+ - `/shorts`: YouTube Shorts
54
+ - `all`: Ingests content across all three tabs simultaneously.
55
+
56
+ ---
57
+
58
+ ## 📁 Standardized `Outputs/` Hierarchy
59
+
60
+ Every extracted video is organized into its own isolated directory based on content type:
61
+
62
+ ```text
63
+ plugins/youtube-scrape/
64
+ ├── core.py # ⚡ Pure Python SDK (Zero prints, returns dicts)
65
+ ├── cli.py # 🧙 Interactive CLI & Terminal Runner
66
+ ├── run_batch.py # 🚀 Dedicated batch runner for markdown lists
67
+ ├── plugin.json # 📋 Universal plugin manifest
68
+ ├── SKILL.md # 🧠 AI Agent parameter discovery protocol
69
+ ├── README.md # 📖 Master documentation (This file)
70
+ ├── requirements.txt # 📦 Isolated dependencies (yt-dlp, etc.)
71
+ ├── md.md # 📄 Sample source list of channels and videos
72
+ └── Outputs/ # 💾 Standardized Categorized Storage
73
+ ├── videos/<video_id>/
74
+ │ ├── transcript.txt # Clean text transcript
75
+ │ ├── transcript.json # Timestamped segment JSON
76
+ │ ├── metadata.json # Full video statistics & metadata
77
+ │ ├── comments.json # Top comments & engagement
78
+ │ ├── thumbnail.webp # High-res cover image
79
+ │ └── video.mp4 # Downloaded video file
80
+ │
81
+ ├── shorts/<short_id>/
82
+ │ └── ... (same structure)
83
+ │
84
+ └── live/<live_id>/
85
+ └── ... (same structure)
86
+ ```
87
+
88
+ ---
89
+
90
+ ## 💡 AI Agent Usage: In-Memory / Zero-Disk Execution
91
+
92
+ When an AI agent (Claude Code, Cursor, Codex, Antigravity) executes this plugin, **it does NOT need to download video files or write artifacts to disk**.
93
+
94
+ ### 2 Zero-Disk Execution Modes for AI Agents:
95
+
96
+ 1. **In-Memory CLI Pipe (`--stdout`)**:
97
+ ```bash
98
+ python plugins/youtube-scrape/cli.py "https://www.youtube.com/watch?v=VIDEO_ID" --stdout
99
+ ```
100
+ *The transcript text streams directly into the AI's standard input in RAM without touching the hard drive.*
101
+
102
+ 2. **Direct Python SDK Import**:
103
+ ```python
104
+ import sys
105
+ from pathlib import Path
106
+ sys.path.insert(0, str(Path("plugins/youtube-scrape").resolve()))
107
+ import core
108
+
109
+ # Returns pure Python dictionary in RAM with zero disk writes!
110
+ data = core.get_transcript("VIDEO_ID")
111
+ meta = core.get_video_metadata("VIDEO_ID")
112
+ ```
113
+
114
+ ---
115
+
116
+ ## 🚀 CLI Commands & Usage Examples
117
+
118
+ ### 1. Interactive Wizard (Easiest for Humans)
119
+ ```bash
120
+ python plugins/youtube-scrape/cli.py -i
121
+ ```
122
+
123
+ ### 2. Single Video Scrapes
124
+ ```bash
125
+ # Full complete suite (Transcript + Metadata + Comments + Thumbnail + MP4 Video)
126
+ python plugins/youtube-scrape/cli.py "https://www.youtube.com/watch?v=VIDEO_ID" --all
127
+
128
+ # Download MP4 Video file at specific resolution (e.g. 1080p, 720p, 480p, 360p, 4k)
129
+ python plugins/youtube-scrape/cli.py "https://www.youtube.com/watch?v=VIDEO_ID" --download-video --resolution 1080p
130
+
131
+ # Metadata & Comments only
132
+ python plugins/youtube-scrape/cli.py "https://www.youtube.com/watch?v=VIDEO_ID" --no-transcript --metadata --comments --max-comments 50
133
+
134
+ # Fast Transcript Only (default)
135
+ python plugins/youtube-scrape/cli.py "https://www.youtube.com/watch?v=VIDEO_ID"
136
+ ```
137
+
138
+ ### 3. YouTube Shorts & Live Streams
139
+ ```bash
140
+ # Scrape YouTube Short
141
+ python plugins/youtube-scrape/cli.py "https://youtube.com/shorts/6Zwns0Pppv8" --all
142
+
143
+ # Scrape YouTube Live Stream
144
+ python plugins/youtube-scrape/cli.py "https://www.youtube.com/live/nyBLpe9AE9Q" --all
145
+ ```
146
+
147
+ ### 4. Channel Scraping
148
+ ```bash
149
+ # Scrape latest 10 regular long-form videos
150
+ python plugins/youtube-scrape/cli.py --channel "https://www.youtube.com/@ChannelName" --type videos --limit 10
151
+
152
+ # Scrape latest 5 Live streams
153
+ python plugins/youtube-scrape/cli.py --channel "https://www.youtube.com/@ChannelName" --type streams --limit 5
154
+
155
+ # Scrape latest 20 YouTube Shorts
156
+ python plugins/youtube-scrape/cli.py --channel "https://www.youtube.com/@ChannelName" --type shorts --limit 20
157
+ ```
158
+
159
+ ### 5. Bulk Batch Runner
160
+ ```bash
161
+ # Process URLs from md.md or custom file
162
+ python plugins/youtube-scrape/run_batch.py
163
+ ```
164
+
165
+ ---
166
+
167
+ ## ⚙️ CLI Flag Reference Table
168
+
169
+ | Flag | Shorthand | Type | Default | Description |
170
+ | :--- | :--- | :--- | :--- | :--- |
171
+ | `url` | - | `string` | `None` | Video URL, Short URL, Live URL, or 11-char ID. |
172
+ | `--channel` | `-c` | `string` | `None` | Channel URL or handle. |
173
+ | `--type` | `-t` | `string` | `videos` | Channel tab: `videos`, `streams`, `live`, `shorts`, `all`. |
174
+ | `--limit` | `-l` | `int` | `10` | Maximum videos to discover from channel. |
175
+ | `--transcript` | - | `flag` | `True` | Extract closed captions / transcript. |
176
+ | `--no-transcript`| - | `flag` | `False` | Skip transcript extraction. |
177
+ | `--metadata` | `-m` | `flag` | `False` | Extract full video metadata (views, likes, tags). |
178
+ | `--comments` | - | `flag` | `False` | Scrape top comment threads. |
179
+ | `--max-comments` | - | `int` | `50` | Maximum comments to scrape. |
180
+ | `--download-video`| `--download-media` | `flag` | `False` | Download high-definition `.mp4` video file. |
181
+ | `--download-thumb`| - | `flag` | `False` | Download high-res video thumbnail. |
182
+ | `--resolution` | `-q` / `--quality` | `string` | `best` | Video resolution: `360p`, `480p`, `720p`, `1080p`, `1440p`, `2160p`, `4k`, `best`, `worst`. |
183
+ | `--all` | `-a` | `flag` | `False` | Extract EVERYTHING (Transcript + Metadata + Comments + Thumbnail + Video). |
184
+ | `--stdout` | - | `flag` | `False` | Stream raw transcript directly to console for AI agents. |
185
+ | `--no-sandbox` | - | `flag` | `False` | Disable `<transcript>` XML isolation tags. |
186
+ | `--interactive`| `-i` | `flag` | `False` | Launch interactive wizard. |
187
+
188
+ ---
189
+
190
+ ## 🔒 Security & Defensive Engineering
191
+
192
+ 1. **Path Traversal Protection (`validate_output_dir`)**: User-defined output paths are jail-checked against allowed project boundaries.
193
+ 2. **SSRF Hardening (`validate_youtube_url`)**: Network requests are strictly filtered through domain allowlists (`*.youtube.com`, `*.googlevideo.com`, `youtu.be`).
194
+ 3. **Agent Prompt Injection Defense (XML Sandboxing)**: Captions are enclosed in `<transcript>...</transcript>` tags by default.
195
+
196
+ ---
197
+
198
+ ## 📄 License
199
+ MIT License. Part of the [SocialScrape](../../README.md) toolkit.