@auscera/socialscrape 0.0.0-stage → 2.0.2

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 +245 -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,77 @@
1
+ """
2
+ Plugins package for SocialScrape.
3
+ Supports PPA-compliant hyphenated plugin directory naming (e.g. plugins/youtube-scrape,
4
+ plugins/instagram-scrape) while dynamically registering standard Python package aliases
5
+ in sys.modules and module attributes.
6
+ """
7
+
8
+ import importlib
9
+ import importlib.util
10
+ import logging
11
+ import sys
12
+ import types
13
+ from pathlib import Path
14
+
15
+ _plugins_dir = Path(__file__).resolve().parent
16
+ _this_mod = sys.modules[__name__]
17
+
18
+ # Automatically register underscore and hyphen aliases for any plugin directories
19
+ for _entry in _plugins_dir.iterdir():
20
+ if _entry.is_dir() and not _entry.name.startswith((".", "_")) and _entry.name != "shared":
21
+ _folder_name = _entry.name
22
+ _under_name = _folder_name.replace("-", "_")
23
+ _init_file = _entry / "__init__.py"
24
+ try:
25
+ for _p_name in [f"plugins.{_folder_name}", f"plugins.{_under_name}"]:
26
+ if _p_name not in sys.modules:
27
+ if _init_file.exists():
28
+ _spec = importlib.util.spec_from_file_location(
29
+ _p_name,
30
+ _init_file,
31
+ submodule_search_locations=[str(_entry)],
32
+ )
33
+ if _spec and _spec.loader:
34
+ _pkg_mod = importlib.util.module_from_spec(_spec)
35
+ _pkg_mod.__path__ = [str(_entry)]
36
+ _pkg_mod.__package__ = _p_name
37
+ sys.modules[_p_name] = _pkg_mod
38
+ _spec.loader.exec_module(_pkg_mod)
39
+ else:
40
+ _pkg_mod = types.ModuleType(_p_name)
41
+ _pkg_mod.__path__ = [str(_entry)]
42
+ _pkg_mod.__package__ = _p_name
43
+ sys.modules[_p_name] = _pkg_mod
44
+ else:
45
+ _pkg_mod = types.ModuleType(_p_name)
46
+ _pkg_mod.__path__ = [str(_entry)]
47
+ _pkg_mod.__package__ = _p_name
48
+ sys.modules[_p_name] = _pkg_mod
49
+
50
+ setattr(_this_mod, _under_name, _pkg_mod)
51
+ setattr(_this_mod, _folder_name, _pkg_mod)
52
+
53
+ for _subfile in _entry.glob("*.py"):
54
+ if not _subfile.name.startswith("__"):
55
+ _stem = _subfile.stem
56
+ for _mod_name in [
57
+ f"plugins.{_folder_name}.{_stem}",
58
+ f"plugins.{_under_name}.{_stem}",
59
+ ]:
60
+ if _mod_name not in sys.modules:
61
+ _sub_spec = importlib.util.spec_from_file_location(_mod_name, _subfile)
62
+ if _sub_spec and _sub_spec.loader:
63
+ _sub_mod = importlib.util.module_from_spec(_sub_spec)
64
+ _sub_mod.__package__ = f"plugins.{_under_name}"
65
+ sys.modules[_mod_name] = _sub_mod
66
+ for _p in [
67
+ sys.modules.get(f"plugins.{_under_name}"),
68
+ sys.modules.get(f"plugins.{_folder_name}"),
69
+ ]:
70
+ if _p:
71
+ setattr(_p, _stem, _sub_mod)
72
+ try:
73
+ _sub_spec.loader.exec_module(_sub_mod)
74
+ except Exception as _sub_exc:
75
+ logging.getLogger(__name__).debug(f"Module exec note for {_mod_name}: {_sub_exc}")
76
+ except Exception as _exc:
77
+ logging.getLogger(__name__).debug(f"Plugin aliasing warning for {_folder_name}: {_exc}")
@@ -0,0 +1,164 @@
1
+ # Instagram Universal Scraper & Downloader Plugin šŸ“ø
2
+
3
+ > **A self-contained, high-speed Python SDK and CLI engine for Instagram profiles, reels, posts, carousel media, and comments.**
4
+
5
+ This plugin extracts structured data and downloads media from **user profiles**, **Instagram Reels**, **single image/video posts**, and **multi-slide carousels** with zero browser overhead.
6
+
7
+ ---
8
+
9
+ ## 🌟 Comprehensive Feature Breakdown & Capabilities
10
+
11
+ ### 1. šŸ‘¤ User Profile Intelligence & Bio Extraction
12
+ - **How it works**: Queries Instagram's public Web GraphQL & profile endpoints with randomized user-agent headers and rate-limit pacing.
13
+ - **Capabilities**:
14
+ - Extracts full `username`, `full_name`, `biography`, `external_url`, `is_verified`, and `is_private`.
15
+ - Scrapes metrics: `follower_count`, `following_count`, and `posts_count`.
16
+ - Automatically exports profile biographies and summaries to `Outputs/text_posts/{username}_bio.txt`.
17
+
18
+ ### 2. šŸŽ¬ Reels & Video Downloader
19
+ - **How it works**: Direct stream extraction via `yt-dlp` format selectors optimized for Instagram CDN delivery.
20
+ - **Download Modes**:
21
+ - **Video (`--download-video`)**: Downloads high-definition `.mp4` video files and reels directly into `Outputs/videos/{id}/`.
22
+ - **Quality Selector (`-q / --quality`)**: Select from `best` (1080p), `720p`, or `480p`.
23
+ - **Thumbnails & Cover Photos (`--download-thumb`)**: Downloads full-resolution cover art and photos into `Outputs/thumbnails/{id}/`.
24
+
25
+ ### 3. šŸ–¼ļø Multi-Slide Carousel & Photo Extraction
26
+ - **How it works**: Parses multi-item post nodes and extracts high-resolution image URLs, saving full carousel images locally.
27
+ - **Data Extracted**:
28
+ - `dimensions`: Width and height pixel dimensions.
29
+ - `display_url`: Direct high-resolution CDN photo link.
30
+ - `accessibility_caption`: Auto-generated visual description text for search and AI analysis.
31
+
32
+ ### 4. šŸ’¬ Comment Threads & Caption Extraction
33
+ - **How it works**: Scrapes top comment threads, author handles, like counts, and timestamp data.
34
+ - **Data Extracted**:
35
+ - `id`: Unique comment identifier.
36
+ - `author`: Instagram username of commenter.
37
+ - `text`: Comment body text.
38
+ - `created_at`: Unix timestamp.
39
+ - `like_count`: Total likes on comment.
40
+ - Saved as structured JSON in `Outputs/comments/{post_id}_comments.json`.
41
+
42
+ ### 5. šŸ“¦ Complete Extraction Bundle (`--all`)
43
+ - **How it works**: Executes profile scraping, post caption extraction, comment threads, cover image, and video download in a single unified execution pipeline.
44
+
45
+ ---
46
+
47
+ ## šŸ“ Standardized `Outputs/` Hierarchy
48
+
49
+ Every extracted asset is organized into its dedicated folder:
50
+
51
+ ```text
52
+ plugins/instagram-scrape/
53
+ ā”œā”€ā”€ core.py # ⚔ Pure Python SDK (Zero prints, returns dicts)
54
+ ā”œā”€ā”€ cli.py # šŸ§™ Interactive CLI & Terminal Runner
55
+ ā”œā”€ā”€ plugin.json # šŸ“‹ Universal plugin manifest
56
+ ā”œā”€ā”€ SKILL.md # 🧠 AI Agent parameter discovery protocol
57
+ ā”œā”€ā”€ README.md # šŸ“– Master documentation (This file)
58
+ ā”œā”€ā”€ requirements.txt # šŸ“¦ Isolated dependencies (yt-dlp, requests)
59
+ └── Outputs/ # šŸ’¾ Standardized Categorized Storage
60
+ ā”œā”€ā”€ videos/<shortcode>/
61
+ │ └── video.mp4 # Downloaded Reel / Post video
62
+ ā”œā”€ā”€ thumbnails/<shortcode>/
63
+ │ └── thumbnail.jpg # High-res cover image or photo
64
+ ā”œā”€ā”€ comments/
65
+ │ └── <shortcode>_comments.json # Comment threads & engagement
66
+ └── text_posts/
67
+ ā”œā”€ā”€ <shortcode>_post.json # Structured post metadata & caption
68
+ └── <username>_bio.txt # Plain text user profile biography
69
+ ```
70
+
71
+ ---
72
+
73
+ ## šŸ’” AI Agent Usage: In-Memory / Zero-Disk Execution
74
+
75
+ When an AI agent (Claude Code, Cursor, Codex, Antigravity) executes this plugin, **it does NOT need to write heavy media artifacts to disk**.
76
+
77
+ ### Zero-Disk Execution Modes for AI Agents:
78
+
79
+ 1. **In-Memory CLI Pipe (`--stdout`)**:
80
+ ```bash
81
+ python plugins/instagram-scrape/cli.py "https://www.instagram.com/reel/C8_123xyz/" --stdout
82
+ ```
83
+ *The structured JSON streams directly into the AI's standard input in RAM.*
84
+
85
+ 2. **Direct Python SDK Import**:
86
+ ```python
87
+ import sys
88
+ from pathlib import Path
89
+ sys.path.insert(0, str(Path("plugins/instagram-scrape").resolve()))
90
+ import core
91
+
92
+ # Returns pure Python dictionary in RAM with zero disk writes!
93
+ profile = core.get_instagram_profile("openai")
94
+ post = core.get_instagram_post("C8_123xyz")
95
+ ```
96
+
97
+ ---
98
+
99
+ ## šŸš€ CLI Commands & Usage Examples
100
+
101
+ ### 1. Interactive Wizard (Easiest for Humans)
102
+ ```bash
103
+ python plugins/instagram-scrape/cli.py -i
104
+ ```
105
+
106
+ ### 2. Single Reel / Post Video Downloads
107
+ ```bash
108
+ # Download MP4 Reel in best quality
109
+ python plugins/instagram-scrape/cli.py "https://www.instagram.com/reel/C8_123xyz/" --download-video
110
+
111
+ # Download Reel at 720p HD with thumbnail
112
+ python plugins/instagram-scrape/cli.py "https://www.instagram.com/reel/C8_123xyz/" --download-video --download-thumb -q 720p
113
+ ```
114
+
115
+ ### 3. User Profile Scraping
116
+ ```bash
117
+ # Scrape profile statistics and bio text
118
+ python plugins/instagram-scrape/cli.py "https://www.instagram.com/openai/" --profile
119
+
120
+ # Scrape profile by handle
121
+ python plugins/instagram-scrape/cli.py "@openai" --profile
122
+ ```
123
+
124
+ ### 4. Post Comments & Captions
125
+ ```bash
126
+ # Extract top 50 comments from a post
127
+ python plugins/instagram-scrape/cli.py "https://www.instagram.com/p/C8_123xyz/" --comments --max-comments 50
128
+ ```
129
+
130
+ ### 5. Full Extraction Suite
131
+ ```bash
132
+ # Extract caption, metadata, comments, thumbnail, and download video in one run
133
+ python plugins/instagram-scrape/cli.py "https://www.instagram.com/reel/C8_123xyz/" --all
134
+ ```
135
+
136
+ ---
137
+
138
+ ## āš™ļø CLI Flag Reference Table
139
+
140
+ | Flag | Shorthand | Type | Default | Description |
141
+ | :--- | :--- | :--- | :--- | :--- |
142
+ | `target` | - | `string` | `None` | Instagram URL, reel link, shortcode, or `@username`. |
143
+ | `--interactive` | `-i` | `flag` | `False` | Launch step-by-step interactive wizard. |
144
+ | `--stdout` | - | `flag` | `False` | Stream structured JSON directly to console. |
145
+ | `--profile` | - | `flag` | `False` | Extract user profile metadata and bio. |
146
+ | `--download-video` | - | `flag` | `False` | Download high-definition `.mp4` video/reel. |
147
+ | `--download-thumb` | - | `flag` | `False` | Download high-res cover photo or thumbnail. |
148
+ | `-q` / `--quality` | - | `string` | `best` | Video quality: `best`, `1080p`, `720p`, `480p`. |
149
+ | `--comments` | - | `flag` | `False` | Extract comment threads from post. |
150
+ | `--max-comments` | - | `int` | `30` | Maximum comments to fetch. |
151
+ | `--all` | `-a` | `flag` | `False` | Extract EVERYTHING (Caption + Metadata + Comments + Thumbnail + Video). |
152
+
153
+ ---
154
+
155
+ ## šŸ”’ Security & Defensive Engineering
156
+
157
+ 1. **Path Traversal Protection**: Output paths are validated against allowed project boundaries.
158
+ 2. **Burner Session Manager**: Supports optional authenticated session injection via `plugins/shared/session_manager.py`.
159
+ 3. **Pacing & Rate Limiting**: Built-in human delay jitter (2s–5s) protects burner sessions from platform rate limits.
160
+
161
+ ---
162
+
163
+ ## šŸ“„ License
164
+ MIT License. Part of the [SocialScrape](../../README.md) toolkit.
@@ -0,0 +1,53 @@
1
+ ---
2
+ name: instagram-scrape
3
+ description: "Self-contained plugin and skill for scraping Instagram profiles, reels, posts, carousel media, and comment threads, with direct media download support."
4
+ triggers:
5
+ - instagram.com
6
+ - instagr.am
7
+ - instagram profile
8
+ - instagram reel
9
+ - instagram post
10
+ - download instagram
11
+ - instagram comments
12
+ ---
13
+
14
+ # Instagram Scrape Plugin & Skill
15
+
16
+ ## Overview
17
+ This plugin executes zero-cost, high-speed extraction and media downloading for Instagram:
18
+ - **Profiles**: Bio, follower/following counts, profile picture URL, verified status, external links.
19
+ - **Posts & Reels**: Captions, likes, comment counts, video duration, and timestamps.
20
+ - **Comments**: Top comments, reply counts, authors, and like metrics.
21
+ - **Media Downloader**: Direct download of MP4 Reels/videos and high-res JPEG/PNG carousel photos.
22
+
23
+ All disk outputs are organized into structured directories inside `plugins/instagram-scrape/Outputs/`:
24
+ - `Outputs/videos/`
25
+ - `Outputs/thumbnails/`
26
+ - `Outputs/comments/`
27
+ - `Outputs/text_posts/`
28
+
29
+ ---
30
+
31
+ ## ⚔ Execution Modes & Commands
32
+
33
+ ### 1. In-Memory / Zero-Disk Execution (Preferred for Agent Analysis)
34
+ ```bash
35
+ python plugins/instagram-scrape/cli.py "<URL_OR_USERNAME>" --stdout
36
+ ```
37
+
38
+ ### 2. Single Post or Profile Scrape (Saved to `Outputs/`)
39
+ ```bash
40
+ # Full bundle (Profile/Post Data + Comments + Media)
41
+ python plugins/instagram-scrape/cli.py "<URL_OR_USERNAME>" --all
42
+
43
+ # Download video / reel only
44
+ python plugins/instagram-scrape/cli.py "<URL>" --download-video
45
+
46
+ # Extract comments only
47
+ python plugins/instagram-scrape/cli.py "<URL>" --comments --max-comments 50
48
+ ```
49
+
50
+ ### 3. Interactive Wizard Mode
51
+ ```bash
52
+ python plugins/instagram-scrape/cli.py -i
53
+ ```
@@ -0,0 +1,176 @@
1
+ """
2
+ Instagram Universal Scraper CLI (`cli.py`)
3
+ Interactive CLI and presentation layer for instagram-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_instagram_id_or_user,
28
+ download_instagram_media,
29
+ get_instagram_profile,
30
+ get_instagram_post,
31
+ get_instagram_comments,
32
+ scrape_instagram_bundle,
33
+ )
34
+ except ImportError:
35
+ sys.path.insert(0, str(PLUGIN_DIR))
36
+ from core import (
37
+ extract_instagram_id_or_user,
38
+ download_instagram_media,
39
+ get_instagram_profile,
40
+ get_instagram_post,
41
+ get_instagram_comments,
42
+ scrape_instagram_bundle,
43
+ )
44
+
45
+
46
+ def run_interactive_wizard():
47
+ print("=" * 65)
48
+ print(" šŸ“ø Instagram Universal Scraper & Downloader Wizard")
49
+ print("=" * 65)
50
+ print("\nSelect Option:")
51
+ print(" [1] Download Reel / Video / Photo (MP4/JPG)")
52
+ print(" [2] Scrape User Profile Data & Bio")
53
+ print(" [3] Scrape Post Comments & Captions")
54
+ print(" [4] Full Extraction Suite (--all)")
55
+
56
+ choice = input("\nEnter choice [1-4] (default: 1): ").strip() or "1"
57
+ target = input("\nEnter Instagram URL or @username: ").strip()
58
+ if not target:
59
+ print("[!] No target specified. Exiting.")
60
+ return
61
+
62
+ if choice == "1":
63
+ print("\nSelect Media Quality:")
64
+ print(" [1] Best Available (1080p/High)")
65
+ print(" [2] 720p HD")
66
+ print(" [3] 480p SD")
67
+ q_choice = input("Enter quality [1-3] (default: 1): ").strip() or "1"
68
+ quality_map = {"1": "best", "2": "720p", "3": "480p"}
69
+ quality = quality_map.get(q_choice, "best")
70
+
71
+ print(f"\n[+] Downloading media from {target} ({quality})...")
72
+ res = download_instagram_media(target, quality=quality)
73
+ if res.get("status") == "success":
74
+ print(f"\nāœ… Download complete!")
75
+ if res.get("video_path"):
76
+ print(f" šŸŽ¬ Video saved: {res['video_path']}")
77
+ if res.get("thumbnail_path"):
78
+ print(f" šŸ–¼ļø Thumbnail saved: {res['thumbnail_path']}")
79
+ else:
80
+ print(f"[!] Download notice: {res.get('error')}")
81
+
82
+ elif choice == "2":
83
+ print(f"\n[+] Fetching Instagram Profile: {target}...")
84
+ parsed = extract_instagram_id_or_user(target)
85
+ res = get_instagram_profile(parsed["id"])
86
+ print(f"\nāœ… Profile Scraped:")
87
+ print(f" šŸ‘¤ Username: @{res.get('username')}")
88
+ print(f" šŸ“ Full Name: {res.get('full_name')}")
89
+ print(f" šŸ‘„ Followers: {res.get('followers'):,}")
90
+ print(f" šŸ¤ Following: {res.get('following'):,}")
91
+ print(f" šŸ“ø Posts: {res.get('posts_count'):,}")
92
+ print(f" šŸ“„ Bio: {res.get('biography')}")
93
+ if res.get("saved_text_path"):
94
+ print(f" šŸ’¾ Saved to: {res['saved_text_path']}")
95
+
96
+ elif choice == "3":
97
+ print(f"\n[+] Fetching Instagram Comments: {target}...")
98
+ parsed = extract_instagram_id_or_user(target)
99
+ res = get_instagram_comments(parsed["id"])
100
+ print(f"\nāœ… Comments Scraped: {res.get('count', 0)} comments fetched.")
101
+ if res.get("saved_file"):
102
+ print(f" šŸ’¾ Saved to: {res['saved_file']}")
103
+
104
+ elif choice == "4":
105
+ print(f"\n[+] Running Full Instagram Suite on {target}...")
106
+ res = scrape_instagram_bundle(target, fetch_media=True, fetch_comments=True)
107
+ print(f"\nāœ… Full Extraction Bundle Completed:")
108
+ print(json.dumps({k: v for k, v in res.items() if v is not None}, indent=2, default=str))
109
+
110
+
111
+ def main():
112
+ parser = argparse.ArgumentParser(description="Instagram Scraper & Media Downloader CLI")
113
+ parser.add_argument("target", nargs="?", help="Instagram post/reel URL or @username")
114
+ parser.add_argument("-i", "--interactive", action="store_true", help="Launch interactive wizard")
115
+ parser.add_argument("--stdout", action="store_true", help="Print structured data directly to stdout")
116
+ parser.add_argument("--profile", action="store_true", help="Scrape user profile metadata")
117
+ parser.add_argument("--download-video", action="store_true", help="Download MP4 video/reel")
118
+ parser.add_argument("--download-thumb", action="store_true", help="Download cover photo/thumbnail")
119
+ parser.add_argument("-q", "--quality", default="best", choices=["best", "1080p", "720p", "480p"], help="Video quality")
120
+ parser.add_argument("--comments", action="store_true", help="Extract comment threads")
121
+ parser.add_argument("--max-comments", type=int, default=30, help="Max comments to fetch")
122
+ parser.add_argument("--all", action="store_true", help="Extract all metadata, comments, and media")
123
+ parser.add_argument("--output-dir", "-o", type=str, default=str(DEFAULT_OUTPUTS_DIR), help="Output base directory.")
124
+
125
+ args = parser.parse_args()
126
+ if args.output_dir:
127
+ os.environ["SOCIALSCRAPE_OUTPUT_DIR"] = str(Path(args.output_dir).expanduser().resolve())
128
+ if args.interactive or not args.target:
129
+ run_interactive_wizard()
130
+ return
131
+
132
+ parsed = extract_instagram_id_or_user(args.target)
133
+
134
+ if args.stdout:
135
+ if parsed["type"] == "profile" or args.profile:
136
+ data = get_instagram_profile(parsed["id"])
137
+ else:
138
+ data = get_instagram_post(parsed["id"])
139
+ print(json.dumps(data, indent=2, ensure_ascii=False))
140
+ return
141
+
142
+ if args.all:
143
+ bundle = scrape_instagram_bundle(args.target, fetch_media=True, fetch_comments=True, max_comments=args.max_comments)
144
+ print(f"[+] Full Instagram extraction complete: {args.target}")
145
+ return
146
+
147
+ if args.profile or parsed["type"] == "profile":
148
+ res = get_instagram_profile(parsed["id"])
149
+ print(f"[+] Instagram Profile scraped: @{res.get('username')}")
150
+ return
151
+
152
+ if args.comments:
153
+ res = get_instagram_comments(parsed["id"], max_comments=args.max_comments)
154
+ print(f"[+] Comments fetched: {res.get('count', 0)}")
155
+ return
156
+
157
+ if args.download_video or args.download_thumb:
158
+ res = download_instagram_media(
159
+ args.target,
160
+ download_video=args.download_video,
161
+ download_thumbnail=args.download_thumb,
162
+ quality=args.quality
163
+ )
164
+ print(f"[+] Media Download result: {res.get('status')}")
165
+ return
166
+
167
+ # Default action: scrape post or profile
168
+ if parsed["type"] == "profile":
169
+ res = get_instagram_profile(parsed["id"])
170
+ else:
171
+ res = get_instagram_post(parsed["id"])
172
+ print(f"[+] Scraped {args.target}: {res.get('status')}")
173
+
174
+
175
+ if __name__ == "__main__":
176
+ main()