@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.
- package/README.md +111 -2
- package/bin/socialscrape.mjs +115 -0
- package/engine/README.md +245 -0
- package/engine/SKILL.md +194 -0
- package/engine/agent.py +665 -0
- package/engine/batch_manager.py +622 -0
- package/engine/cli.py +23 -0
- package/engine/handlers.py +1109 -0
- package/engine/plugins/__init__.py +77 -0
- package/engine/plugins/instagram-scrape/README.md +164 -0
- package/engine/plugins/instagram-scrape/SKILL.md +53 -0
- package/engine/plugins/instagram-scrape/cli.py +176 -0
- package/engine/plugins/instagram-scrape/core.py +408 -0
- package/engine/plugins/instagram-scrape/plugin.json +42 -0
- package/engine/plugins/linkedin-scrape/README.md +143 -0
- package/engine/plugins/linkedin-scrape/SKILL.md +47 -0
- package/engine/plugins/linkedin-scrape/cli.py +126 -0
- package/engine/plugins/linkedin-scrape/core.py +188 -0
- package/engine/plugins/linkedin-scrape/plugin.json +36 -0
- package/engine/plugins/meta-ad-library-scraper/README.md +127 -0
- package/engine/plugins/meta-ad-library-scraper/SKILL.md +44 -0
- package/engine/plugins/meta-ad-library-scraper/cli.py +161 -0
- package/engine/plugins/meta-ad-library-scraper/core.py +348 -0
- package/engine/plugins/meta-ad-library-scraper/plugin.json +44 -0
- package/engine/plugins/pinterest-scraper/README.md +150 -0
- package/engine/plugins/pinterest-scraper/SKILL.md +45 -0
- package/engine/plugins/pinterest-scraper/cli.py +193 -0
- package/engine/plugins/pinterest-scraper/core.py +420 -0
- package/engine/plugins/pinterest-scraper/plugin.json +40 -0
- package/engine/plugins/reddit-discussion-scraper/README.md +162 -0
- package/engine/plugins/reddit-discussion-scraper/SKILL.md +52 -0
- package/engine/plugins/reddit-discussion-scraper/cli.py +218 -0
- package/engine/plugins/reddit-discussion-scraper/core.py +546 -0
- package/engine/plugins/reddit-discussion-scraper/plugin.json +46 -0
- package/engine/plugins/shared/__init__.py +15 -0
- package/engine/plugins/shared/paths.py +90 -0
- package/engine/plugins/shared/process_runner.py +169 -0
- package/engine/plugins/shared/session_manager.py +287 -0
- package/engine/plugins/threads-scraper/README.md +139 -0
- package/engine/plugins/threads-scraper/SKILL.md +43 -0
- package/engine/plugins/threads-scraper/cli.py +178 -0
- package/engine/plugins/threads-scraper/core.py +460 -0
- package/engine/plugins/threads-scraper/plugin.json +40 -0
- package/engine/plugins/tiktok-scrape/README.md +158 -0
- package/engine/plugins/tiktok-scrape/SKILL.md +51 -0
- package/engine/plugins/tiktok-scrape/cli.py +163 -0
- package/engine/plugins/tiktok-scrape/core.py +313 -0
- package/engine/plugins/tiktok-scrape/plugin.json +40 -0
- package/engine/plugins/twitter-scrape/README.md +158 -0
- package/engine/plugins/twitter-scrape/SKILL.md +50 -0
- package/engine/plugins/twitter-scrape/cli.py +153 -0
- package/engine/plugins/twitter-scrape/core.py +254 -0
- package/engine/plugins/twitter-scrape/plugin.json +40 -0
- package/engine/plugins/youtube-scrape/README.md +199 -0
- package/engine/plugins/youtube-scrape/SKILL.md +115 -0
- package/engine/plugins/youtube-scrape/cli.py +340 -0
- package/engine/plugins/youtube-scrape/core.py +829 -0
- package/engine/plugins/youtube-scrape/plugin.json +48 -0
- package/engine/requirements.txt +8 -0
- package/engine/socialscrape_cli.py +500 -0
- package/engine/storage.py +570 -0
- package/engine/ui.py +690 -0
- package/package.json +27 -3
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Pinterest Scraper Pure SDK (`core.py`)
|
|
3
|
+
Pure zero-side-effect Python SDK for Pinterest data extraction and media downloading.
|
|
4
|
+
Utilizes Pinterest's unauthenticated Resource API endpoints and anonymous session cookies.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
import json
|
|
10
|
+
import re
|
|
11
|
+
import time
|
|
12
|
+
import random
|
|
13
|
+
import urllib.parse
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Dict, List, Any, Optional, Union
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
import requests
|
|
19
|
+
HAS_REQUESTS = True
|
|
20
|
+
except ImportError:
|
|
21
|
+
HAS_REQUESTS = False
|
|
22
|
+
|
|
23
|
+
try:
|
|
24
|
+
import yt_dlp
|
|
25
|
+
HAS_YT_DLP = True
|
|
26
|
+
except ImportError:
|
|
27
|
+
HAS_YT_DLP = False
|
|
28
|
+
|
|
29
|
+
# Import shared SessionManager & Path Helpers
|
|
30
|
+
try:
|
|
31
|
+
from plugins.shared.session_manager import SessionManager, RateLimiter
|
|
32
|
+
from plugins.shared.paths import get_plugin_outputs_dir
|
|
33
|
+
HAS_SESSION_MANAGER = True
|
|
34
|
+
except ImportError:
|
|
35
|
+
_shared_parent = str(Path(__file__).parent.parent.resolve())
|
|
36
|
+
if _shared_parent not in sys.path:
|
|
37
|
+
sys.path.insert(0, _shared_parent)
|
|
38
|
+
from shared.paths import get_plugin_outputs_dir
|
|
39
|
+
try:
|
|
40
|
+
from shared.session_manager import SessionManager, RateLimiter
|
|
41
|
+
HAS_SESSION_MANAGER = True
|
|
42
|
+
except ImportError:
|
|
43
|
+
HAS_SESSION_MANAGER = False
|
|
44
|
+
|
|
45
|
+
PLUGIN_DIR = Path(__file__).parent.resolve()
|
|
46
|
+
DEFAULT_OUTPUTS_DIR = get_plugin_outputs_dir(PLUGIN_DIR)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _outputs_dir() -> Path:
|
|
50
|
+
return get_plugin_outputs_dir(PLUGIN_DIR)
|
|
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 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
|
|
55
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0",
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def get_random_headers(sess_cookie: Optional[str] = None) -> Dict[str, str]:
|
|
60
|
+
"""Generates headers for Pinterest Resource API requests."""
|
|
61
|
+
headers = {
|
|
62
|
+
"User-Agent": random.choice(USER_AGENTS),
|
|
63
|
+
"Accept": "application/json, text/javascript, */*, q=0.01",
|
|
64
|
+
"Accept-Language": "en-US,en;q=0.9",
|
|
65
|
+
"X-Requested-With": "XMLHttpRequest",
|
|
66
|
+
"X-Pinterest-AppState": "active",
|
|
67
|
+
"Origin": "https://www.pinterest.com",
|
|
68
|
+
"Referer": "https://www.pinterest.com/",
|
|
69
|
+
}
|
|
70
|
+
if sess_cookie:
|
|
71
|
+
headers["Cookie"] = f"_pinterest_sess={sess_cookie}"
|
|
72
|
+
return headers
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def extract_pinterest_target(target: str) -> Dict[str, str]:
|
|
76
|
+
"""
|
|
77
|
+
Parses a raw Pinterest URL or identifier into type and ID.
|
|
78
|
+
Supported:
|
|
79
|
+
- Pin: https://www.pinterest.com/pin/1234567890/ or pin ID
|
|
80
|
+
- User: https://www.pinterest.com/username/ or username
|
|
81
|
+
- Board: https://www.pinterest.com/username/boardname/
|
|
82
|
+
"""
|
|
83
|
+
t = target.strip()
|
|
84
|
+
if "/pin/" in t:
|
|
85
|
+
match = re.search(r"/pin/([0-9]+)", t)
|
|
86
|
+
pin_id = match.group(1) if match else t
|
|
87
|
+
return {"type": "pin", "id": pin_id, "url": t}
|
|
88
|
+
elif "pinterest.com/" in t:
|
|
89
|
+
parts = [p for p in urllib.parse.urlparse(t).path.split("/") if p]
|
|
90
|
+
if len(parts) >= 2:
|
|
91
|
+
return {"type": "board", "user": parts[0], "board": parts[1], "id": f"{parts[0]}/{parts[1]}", "url": t}
|
|
92
|
+
elif len(parts) == 1:
|
|
93
|
+
return {"type": "user", "id": parts[0], "url": t}
|
|
94
|
+
elif t.isdigit():
|
|
95
|
+
return {"type": "pin", "id": t, "url": f"https://www.pinterest.com/pin/{t}/"}
|
|
96
|
+
|
|
97
|
+
return {"type": "user", "id": t.lstrip("@"), "url": f"https://www.pinterest.com/{t.lstrip('@')}/"}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _safe_resource_get(resource_name: str, options: Dict[str, Any], max_retries: int = 3) -> Optional[Dict[str, Any]]:
|
|
101
|
+
"""Executes a GET request against Pinterest's internal Resource API."""
|
|
102
|
+
if not HAS_REQUESTS:
|
|
103
|
+
return None
|
|
104
|
+
|
|
105
|
+
# Enforce RateLimiter
|
|
106
|
+
if HAS_SESSION_MANAGER:
|
|
107
|
+
try:
|
|
108
|
+
limiter = RateLimiter()
|
|
109
|
+
limiter.check_and_pace("pinterest")
|
|
110
|
+
except Exception:
|
|
111
|
+
pass
|
|
112
|
+
|
|
113
|
+
encoded_data = urllib.parse.quote(json.dumps({"options": options, "context": {}}))
|
|
114
|
+
url = f"https://www.pinterest.com/resource/{resource_name}/get/?data={encoded_data}"
|
|
115
|
+
|
|
116
|
+
for attempt in range(1, max_retries + 1):
|
|
117
|
+
try:
|
|
118
|
+
resp = requests.get(url, headers=get_random_headers(), timeout=12)
|
|
119
|
+
if resp.status_code == 200:
|
|
120
|
+
return resp.json()
|
|
121
|
+
elif resp.status_code in (429, 500, 502, 503):
|
|
122
|
+
time.sleep(min(2 ** attempt, 3))
|
|
123
|
+
continue
|
|
124
|
+
elif resp.status_code == 404:
|
|
125
|
+
return None
|
|
126
|
+
except Exception:
|
|
127
|
+
if attempt < max_retries:
|
|
128
|
+
time.sleep(min(2 ** attempt, 3))
|
|
129
|
+
continue
|
|
130
|
+
return None
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def get_pin_details(
|
|
134
|
+
pin_url_or_id: str,
|
|
135
|
+
output_dir: Optional[Union[Path, str]] = None
|
|
136
|
+
) -> Dict[str, Any]:
|
|
137
|
+
"""
|
|
138
|
+
Extracts deep metadata for a single Pin (description, high-res image, video stream, outbound link, saves count).
|
|
139
|
+
"""
|
|
140
|
+
parsed = extract_pinterest_target(pin_url_or_id)
|
|
141
|
+
pin_id = parsed["id"]
|
|
142
|
+
|
|
143
|
+
data = _safe_resource_get("PinResource", {"id": pin_id, "field_set_key": "detailed"})
|
|
144
|
+
if not data or not isinstance(data, dict):
|
|
145
|
+
return {
|
|
146
|
+
"status": "error",
|
|
147
|
+
"pin_id": pin_id,
|
|
148
|
+
"error": f"Failed to retrieve pin data for ID {pin_id}."
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
pin_info = data.get("resource_response", {}).get("data", {})
|
|
152
|
+
if not pin_info:
|
|
153
|
+
return {"status": "error", "pin_id": pin_id, "error": "Pin not found."}
|
|
154
|
+
|
|
155
|
+
images = pin_info.get("images", {})
|
|
156
|
+
orig_img = images.get("orig", {}).get("url") or images.get("736x", {}).get("url")
|
|
157
|
+
|
|
158
|
+
# Check for video stream
|
|
159
|
+
videos = pin_info.get("videos", {})
|
|
160
|
+
video_url = None
|
|
161
|
+
if videos and isinstance(videos, dict):
|
|
162
|
+
video_list = videos.get("video_list", {})
|
|
163
|
+
if isinstance(video_list, dict):
|
|
164
|
+
for v_key in ["V_720P", "V_EXP7", "V_HLSV4", "V_480P"]:
|
|
165
|
+
if v_key in video_list and video_list[v_key].get("url"):
|
|
166
|
+
video_url = video_list[v_key]["url"]
|
|
167
|
+
break
|
|
168
|
+
|
|
169
|
+
result = {
|
|
170
|
+
"status": "success",
|
|
171
|
+
"pin_id": pin_id,
|
|
172
|
+
"title": pin_info.get("title") or pin_info.get("grid_title"),
|
|
173
|
+
"description": pin_info.get("description"),
|
|
174
|
+
"created_at": pin_info.get("created_at"),
|
|
175
|
+
"repin_count": pin_info.get("repin_count", 0),
|
|
176
|
+
"comment_count": pin_info.get("comment_count", 0),
|
|
177
|
+
"link": pin_info.get("link"),
|
|
178
|
+
"image_url": orig_img,
|
|
179
|
+
"video_url": video_url,
|
|
180
|
+
"pinner": {
|
|
181
|
+
"username": pin_info.get("pinner", {}).get("username"),
|
|
182
|
+
"full_name": pin_info.get("pinner", {}).get("full_name"),
|
|
183
|
+
"id": pin_info.get("pinner", {}).get("id"),
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
base_out = Path(output_dir) if output_dir else (_outputs_dir() / "text_posts" / f"pin_{pin_id}")
|
|
188
|
+
base_out.mkdir(parents=True, exist_ok=True)
|
|
189
|
+
save_path = base_out / "pin_metadata.json"
|
|
190
|
+
|
|
191
|
+
with open(save_path, "w", encoding="utf-8") as f:
|
|
192
|
+
json.dump(result, f, indent=2)
|
|
193
|
+
|
|
194
|
+
result["saved_path"] = str(save_path)
|
|
195
|
+
return result
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def get_pinterest_user_profile(
|
|
199
|
+
username: str,
|
|
200
|
+
output_dir: Optional[Union[Path, str]] = None
|
|
201
|
+
) -> Dict[str, Any]:
|
|
202
|
+
"""
|
|
203
|
+
Scrapes user profile stats (bio, follower count, following count, pin count, avatar).
|
|
204
|
+
"""
|
|
205
|
+
clean_user = username.lstrip("@").strip()
|
|
206
|
+
data = _safe_resource_get("UserResource", {"username": clean_user})
|
|
207
|
+
|
|
208
|
+
if not data or not isinstance(data, dict):
|
|
209
|
+
return {
|
|
210
|
+
"status": "error",
|
|
211
|
+
"username": clean_user,
|
|
212
|
+
"error": f"Failed to retrieve profile for {clean_user}."
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
u = data.get("resource_response", {}).get("data", {})
|
|
216
|
+
if not u:
|
|
217
|
+
return {"status": "error", "username": clean_user, "error": "User not found."}
|
|
218
|
+
|
|
219
|
+
profile = {
|
|
220
|
+
"username": u.get("username"),
|
|
221
|
+
"full_name": u.get("full_name"),
|
|
222
|
+
"about": u.get("about"),
|
|
223
|
+
"follower_count": u.get("follower_count", 0),
|
|
224
|
+
"following_count": u.get("following_count", 0),
|
|
225
|
+
"pin_count": u.get("pin_count", 0),
|
|
226
|
+
"board_count": u.get("board_count", 0),
|
|
227
|
+
"website_url": u.get("website_url"),
|
|
228
|
+
"image_large_url": u.get("image_xlarge_url") or u.get("image_large_url"),
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
base_out = Path(output_dir) if output_dir else (_outputs_dir() / "text_posts" / f"user_{clean_user}")
|
|
232
|
+
base_out.mkdir(parents=True, exist_ok=True)
|
|
233
|
+
save_path = base_out / "profile.json"
|
|
234
|
+
|
|
235
|
+
with open(save_path, "w", encoding="utf-8") as f:
|
|
236
|
+
json.dump(profile, f, indent=2)
|
|
237
|
+
|
|
238
|
+
return {
|
|
239
|
+
"status": "success",
|
|
240
|
+
"username": clean_user,
|
|
241
|
+
"saved_path": str(save_path),
|
|
242
|
+
"profile": profile
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def get_pinterest_user_pins(
|
|
247
|
+
username: str,
|
|
248
|
+
limit: int = 25,
|
|
249
|
+
output_dir: Optional[Union[Path, str]] = None
|
|
250
|
+
) -> Dict[str, Any]:
|
|
251
|
+
"""
|
|
252
|
+
Fetches latest pins created or saved by a user.
|
|
253
|
+
"""
|
|
254
|
+
clean_user = username.lstrip("@").strip()
|
|
255
|
+
data = _safe_resource_get("UserPinsResource", {"username": clean_user, "page_size": min(limit, 50)})
|
|
256
|
+
|
|
257
|
+
if not data or not isinstance(data, dict):
|
|
258
|
+
return {
|
|
259
|
+
"status": "error",
|
|
260
|
+
"username": clean_user,
|
|
261
|
+
"error": f"Failed to fetch user pins for {clean_user}."
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
pins_raw = data.get("resource_response", {}).get("data", [])
|
|
265
|
+
pins = []
|
|
266
|
+
for p in pins_raw:
|
|
267
|
+
images = p.get("images", {})
|
|
268
|
+
img_url = images.get("orig", {}).get("url") or images.get("736x", {}).get("url")
|
|
269
|
+
pins.append({
|
|
270
|
+
"id": p.get("id"),
|
|
271
|
+
"title": p.get("title") or p.get("grid_title"),
|
|
272
|
+
"description": p.get("description"),
|
|
273
|
+
"link": p.get("link"),
|
|
274
|
+
"image_url": img_url,
|
|
275
|
+
"repin_count": p.get("repin_count", 0),
|
|
276
|
+
})
|
|
277
|
+
|
|
278
|
+
base_out = Path(output_dir) if output_dir else (_outputs_dir() / "text_posts" / f"user_{clean_user}")
|
|
279
|
+
base_out.mkdir(parents=True, exist_ok=True)
|
|
280
|
+
save_path = base_out / "pins.json"
|
|
281
|
+
|
|
282
|
+
with open(save_path, "w", encoding="utf-8") as f:
|
|
283
|
+
json.dump({"username": clean_user, "count": len(pins), "pins": pins}, f, indent=2)
|
|
284
|
+
|
|
285
|
+
return {
|
|
286
|
+
"status": "success",
|
|
287
|
+
"username": clean_user,
|
|
288
|
+
"count": len(pins),
|
|
289
|
+
"saved_path": str(save_path),
|
|
290
|
+
"pins": pins
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def search_pinterest_pins(
|
|
295
|
+
query: str,
|
|
296
|
+
limit: int = 25,
|
|
297
|
+
output_dir: Optional[Union[Path, str]] = None
|
|
298
|
+
) -> Dict[str, Any]:
|
|
299
|
+
"""
|
|
300
|
+
Performs a keyword search on Pinterest.
|
|
301
|
+
"""
|
|
302
|
+
data = _safe_resource_get("BaseSearchResource", {"query": query, "scope": "pins", "page_size": min(limit, 50)})
|
|
303
|
+
|
|
304
|
+
if not data or not isinstance(data, dict):
|
|
305
|
+
return {
|
|
306
|
+
"status": "error",
|
|
307
|
+
"query": query,
|
|
308
|
+
"error": f"Failed to execute Pinterest search for '{query}'."
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
results_raw = data.get("resource_response", {}).get("data", {}).get("results", [])
|
|
312
|
+
results = []
|
|
313
|
+
for p in results_raw:
|
|
314
|
+
images = p.get("images", {})
|
|
315
|
+
img_url = images.get("orig", {}).get("url") or images.get("736x", {}).get("url")
|
|
316
|
+
results.append({
|
|
317
|
+
"id": p.get("id"),
|
|
318
|
+
"title": p.get("title") or p.get("grid_title"),
|
|
319
|
+
"description": p.get("description"),
|
|
320
|
+
"link": p.get("link"),
|
|
321
|
+
"image_url": img_url,
|
|
322
|
+
"pinner": p.get("pinner", {}).get("username")
|
|
323
|
+
})
|
|
324
|
+
|
|
325
|
+
slug = re.sub(r"[^a-zA-Z0-9_-]", "_", query)[:30]
|
|
326
|
+
base_out = Path(output_dir) if output_dir else (_outputs_dir() / "text_posts" / "searches")
|
|
327
|
+
base_out.mkdir(parents=True, exist_ok=True)
|
|
328
|
+
save_path = base_out / f"search_{slug}.json"
|
|
329
|
+
|
|
330
|
+
with open(save_path, "w", encoding="utf-8") as f:
|
|
331
|
+
json.dump({"query": query, "count": len(results), "results": results}, f, indent=2)
|
|
332
|
+
|
|
333
|
+
return {
|
|
334
|
+
"status": "success",
|
|
335
|
+
"query": query,
|
|
336
|
+
"count": len(results),
|
|
337
|
+
"saved_path": str(save_path),
|
|
338
|
+
"results": results
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def download_pinterest_media(
|
|
343
|
+
pin_url_or_id: str,
|
|
344
|
+
output_dir: Optional[Union[Path, str]] = None,
|
|
345
|
+
download_video: bool = True,
|
|
346
|
+
download_thumbnail: bool = True
|
|
347
|
+
) -> Dict[str, Any]:
|
|
348
|
+
"""
|
|
349
|
+
Downloads high-resolution image and/or video pin directly into standardized Outputs/.
|
|
350
|
+
"""
|
|
351
|
+
pin_data = get_pin_details(pin_url_or_id)
|
|
352
|
+
if pin_data.get("status") != "success":
|
|
353
|
+
return {
|
|
354
|
+
"status": "error",
|
|
355
|
+
"error": pin_data.get("error", "Failed to retrieve pin media details."),
|
|
356
|
+
"thumbnail_path": None,
|
|
357
|
+
"video_path": None
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
pin_id = pin_data["pin_id"]
|
|
361
|
+
base_out = Path(output_dir) if output_dir else (_outputs_dir() / "videos" / f"pin_{pin_id}")
|
|
362
|
+
base_out.mkdir(parents=True, exist_ok=True)
|
|
363
|
+
thumb_out = _outputs_dir() / "thumbnails" / f"pin_{pin_id}"
|
|
364
|
+
thumb_out.mkdir(parents=True, exist_ok=True)
|
|
365
|
+
|
|
366
|
+
result: Dict[str, Any] = {
|
|
367
|
+
"status": "success",
|
|
368
|
+
"pin_id": pin_id,
|
|
369
|
+
"thumbnail_path": None,
|
|
370
|
+
"video_path": None,
|
|
371
|
+
"error": None
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
# Download high-res thumbnail
|
|
375
|
+
if download_thumbnail and pin_data.get("image_url") and HAS_REQUESTS:
|
|
376
|
+
try:
|
|
377
|
+
r = requests.get(pin_data["image_url"], headers=get_random_headers(), timeout=15)
|
|
378
|
+
if r.status_code == 200:
|
|
379
|
+
ext = pin_data["image_url"].split(".")[-1].split("?")[0]
|
|
380
|
+
if ext not in ["jpg", "png", "webp"]:
|
|
381
|
+
ext = "jpg"
|
|
382
|
+
save_thumb = thumb_out / f"pin.{ext}"
|
|
383
|
+
with open(save_thumb, "wb") as f:
|
|
384
|
+
f.write(r.content)
|
|
385
|
+
result["thumbnail_path"] = str(save_thumb)
|
|
386
|
+
except Exception as e:
|
|
387
|
+
result["error"] = str(e)
|
|
388
|
+
|
|
389
|
+
# Download video pin if present
|
|
390
|
+
if download_video and pin_data.get("video_url") and HAS_REQUESTS:
|
|
391
|
+
try:
|
|
392
|
+
r = requests.get(pin_data["video_url"], headers=get_random_headers(), timeout=20)
|
|
393
|
+
if r.status_code == 200:
|
|
394
|
+
save_vid = base_out / "video.mp4"
|
|
395
|
+
with open(save_vid, "wb") as f:
|
|
396
|
+
f.write(r.content)
|
|
397
|
+
result["video_path"] = str(save_vid)
|
|
398
|
+
except Exception as e:
|
|
399
|
+
result["error"] = str(e)
|
|
400
|
+
|
|
401
|
+
# Fallback to yt-dlp if direct video was not available
|
|
402
|
+
if download_video and not result["video_path"] and HAS_YT_DLP:
|
|
403
|
+
try:
|
|
404
|
+
url = f"https://www.pinterest.com/pin/{pin_id}/"
|
|
405
|
+
ydl_opts = {
|
|
406
|
+
"outtmpl": str(base_out / "video.%(ext)s"),
|
|
407
|
+
"quiet": True,
|
|
408
|
+
"no_warnings": True,
|
|
409
|
+
}
|
|
410
|
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
|
411
|
+
ydl.extract_info(url, download=True)
|
|
412
|
+
for ext in ["mp4", "webm", "mkv"]:
|
|
413
|
+
p = base_out / f"video.{ext}"
|
|
414
|
+
if p.exists():
|
|
415
|
+
result["video_path"] = str(p)
|
|
416
|
+
break
|
|
417
|
+
except Exception:
|
|
418
|
+
pass
|
|
419
|
+
|
|
420
|
+
return result
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "pinterest-scraper",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Zero-cost Pinterest scraper for pins, high-res images, user profiles, board feeds, keyword searches, and media downloads via internal Resource APIs.",
|
|
5
|
+
"author": "SocialScrape",
|
|
6
|
+
"main": "cli.py",
|
|
7
|
+
"display_name": "Pinterest Scraper",
|
|
8
|
+
"command": "/pinterest",
|
|
9
|
+
"command_description": "pins, creator boards & visual searches",
|
|
10
|
+
"aliases": ["/pinterest"],
|
|
11
|
+
"cli_aliases": ["pinterest"],
|
|
12
|
+
"url_patterns": ["pinterest.com", "pin.it"],
|
|
13
|
+
"tool_schema": {
|
|
14
|
+
"name": "pinterest_scrape",
|
|
15
|
+
"description": "Scrapes Pinterest pin details, high-res images, user profiles, board feeds, and visual keyword searches.",
|
|
16
|
+
"parameters": {
|
|
17
|
+
"type": "object",
|
|
18
|
+
"properties": {
|
|
19
|
+
"target": {"type": "string", "description": "Pin URL/ID, username, or board."},
|
|
20
|
+
"input_file": {"type": "string", "description": "Path to .txt or .csv file for bulk Pinterest scraping."},
|
|
21
|
+
"profile": {"type": "boolean", "description": "Extract creator profile and stats."},
|
|
22
|
+
"pins": {"type": "boolean", "description": "Extract user pins feed."},
|
|
23
|
+
"search": {"type": "string", "description": "Search pins by keyword."},
|
|
24
|
+
"download_media": {"type": "boolean", "description": "Download original high-res image or video."},
|
|
25
|
+
"limit": {"type": "integer"}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"flag_mapping": {
|
|
30
|
+
"positional": ["target"],
|
|
31
|
+
"flags": {
|
|
32
|
+
"input_file": "--input-file",
|
|
33
|
+
"profile": "--profile",
|
|
34
|
+
"pins": "--pins",
|
|
35
|
+
"search": "--search",
|
|
36
|
+
"limit": "-l",
|
|
37
|
+
"download_media": "--download-media"
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
# Reddit Discussion Scraper & Media Downloader Plugin 🤖
|
|
2
|
+
|
|
3
|
+
> **A self-contained, high-speed, zero-cost Python SDK and CLI engine for Reddit community discussions, deep nested comment trees, user submission histories, keyword searches, and v.redd.it media downloads.**
|
|
4
|
+
|
|
5
|
+
This plugin extracts structured discussion data, sentiment trees, and media from **subreddits**, **single discussion threads**, **user profiles**, and **sitewide searches** with zero API keys and zero cost.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 🌟 Comprehensive Feature Breakdown & Capabilities
|
|
10
|
+
|
|
11
|
+
### 1. 📋 Subreddit Discussion Feeds
|
|
12
|
+
- **How it works**: Queries Reddit's unauthenticated `.json` feed endpoints routed through `old.reddit.com` with randomized desktop User-Agents and automated pagination.
|
|
13
|
+
- **Capabilities**:
|
|
14
|
+
- Scrape feeds sorted by `hot`, `new`, `top`, or `rising`.
|
|
15
|
+
- Apply time windows for top posts: `hour`, `day`, `week`, `month`, `year`, `all`.
|
|
16
|
+
- Extracts post title, author, self-text / markdown body, karma score, upvote ratio, comment counts, permalink, and creation timestamp.
|
|
17
|
+
- Automatically exports structured JSON to `Outputs/text_posts/r_{subreddit}/{sort}_feed.json`.
|
|
18
|
+
|
|
19
|
+
### 2. 💬 Deep Nested Comment Trees & Sentiment Analysis
|
|
20
|
+
- **How it works**: Recursively unrolls Reddit's multi-level `t1` comment trees (`_parse_comment_tree`) with depth protection (`max_depth=10`), preserving the full hierarchical discussion flow.
|
|
21
|
+
- **Data Extracted**:
|
|
22
|
+
- `id`: Unique comment ID
|
|
23
|
+
- `author`: Reddit username (or `[deleted]`)
|
|
24
|
+
- `body`: Raw comment text
|
|
25
|
+
- `score`: Upvote / karma score
|
|
26
|
+
- `created_utc`: Unix epoch timestamp
|
|
27
|
+
- `depth`: Indentation level (0 for top-level, 1+ for nested replies)
|
|
28
|
+
- `permalink`: Direct comment URL
|
|
29
|
+
- `replies_count`: Number of direct child replies
|
|
30
|
+
- `replies`: Nested list of child comment objects.
|
|
31
|
+
- Saved into `Outputs/comments/{post_id}/comment_tree.json`.
|
|
32
|
+
|
|
33
|
+
### 3. 👤 User Posting & Comment History
|
|
34
|
+
- **How it works**: Fetches complete historical activity for any user account across all public subreddits.
|
|
35
|
+
- **Data Extracted**:
|
|
36
|
+
- Submissions (posts) and comments differentiated by `type: 'post'` vs `type: 'comment'`.
|
|
37
|
+
- Subreddit origin, title, body text, upvote score, and permalink.
|
|
38
|
+
- Saved into `Outputs/text_posts/u_{username}/user_history.json`.
|
|
39
|
+
|
|
40
|
+
### 4. 🔍 Keyword Search & Buying Intent Mining
|
|
41
|
+
- **How it works**: Queries Reddit's search endpoint across all of Reddit or restricted strictly to a target subreddit (`restrict_sr=1`).
|
|
42
|
+
- **Capabilities**:
|
|
43
|
+
- Uncover product recommendations, customer pain points, and buyer objections.
|
|
44
|
+
- Filter by sort (`relevance`, `hot`, `top`, `new`, `comments`) and time window.
|
|
45
|
+
- Saved into `Outputs/text_posts/searches/search_{query}.json`.
|
|
46
|
+
|
|
47
|
+
### 5. 🎬 Media & Video Downloader (`v.redd.it`)
|
|
48
|
+
- **How it works**: Direct stream extraction via `yt-dlp` to download Reddit-hosted videos, audio tracks, and preview thumbnails into `Outputs/`.
|
|
49
|
+
- **Download Modes**:
|
|
50
|
+
- **Video (`--download-video`)**: Merges Reddit video and audio streams into `.mp4` files inside `Outputs/videos/{post_id}/`.
|
|
51
|
+
- **Thumbnails (`--download-thumb`)**: Downloads full-resolution post preview images into `Outputs/thumbnails/{post_id}/`.
|
|
52
|
+
- **Quality Selector (`-q / --quality`)**: Select from `best`, `1080p`, `720p`, or `480p`.
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
## 📁 Standardized `Outputs/` Hierarchy
|
|
57
|
+
|
|
58
|
+
Every extracted discussion, comment tree, and media file is organized into dedicated folders:
|
|
59
|
+
|
|
60
|
+
```text
|
|
61
|
+
plugins/reddit-discussion-scraper/
|
|
62
|
+
├── core.py # ⚡ Pure Python SDK (Zero prints, returns dicts)
|
|
63
|
+
├── cli.py # 🧙 Interactive CLI & Terminal Runner
|
|
64
|
+
├── plugin.json # 📋 Universal plugin manifest
|
|
65
|
+
├── SKILL.md # 🧠 AI Agent parameter discovery protocol
|
|
66
|
+
├── README.md # 📖 Master documentation (This file)
|
|
67
|
+
└── Outputs/ # 💾 Standardized Categorized Storage
|
|
68
|
+
├── videos/<post_id>/
|
|
69
|
+
│ └── video.mp4 # Downloaded Reddit video
|
|
70
|
+
├── thumbnails/<post_id>/
|
|
71
|
+
│ └── thumbnail.jpg # High-res preview image
|
|
72
|
+
├── comments/<post_id>/
|
|
73
|
+
│ └── comment_tree.json # Complete nested comment hierarchy
|
|
74
|
+
└── text_posts/
|
|
75
|
+
├── r_<subreddit>/
|
|
76
|
+
│ └── hot_feed.json # Subreddit discussion feeds
|
|
77
|
+
├── u_<username>/
|
|
78
|
+
│ └── user_history.json # User submission and comment history
|
|
79
|
+
└── searches/
|
|
80
|
+
└── search_<query>.json # Keyword search results
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
## 💡 AI Agent Usage: In-Memory / Zero-Disk Execution
|
|
86
|
+
|
|
87
|
+
When an AI agent (Claude Code, Cursor, Codex, Antigravity) executes this plugin, **it does NOT need to write heavy media artifacts to disk**.
|
|
88
|
+
|
|
89
|
+
### Zero-Disk Execution Modes for AI Agents:
|
|
90
|
+
|
|
91
|
+
1. **In-Memory CLI Pipe (`--stdout`)**:
|
|
92
|
+
```bash
|
|
93
|
+
python plugins/reddit-discussion-scraper/cli.py r/sales --sort hot --limit 5 --stdout
|
|
94
|
+
```
|
|
95
|
+
*The structured JSON streams directly into the AI's standard input in RAM.*
|
|
96
|
+
|
|
97
|
+
2. **Direct Python SDK Import**:
|
|
98
|
+
```python
|
|
99
|
+
import sys
|
|
100
|
+
from pathlib import Path
|
|
101
|
+
sys.path.insert(0, str(Path("plugins/reddit-discussion-scraper").resolve()))
|
|
102
|
+
import core
|
|
103
|
+
|
|
104
|
+
# Returns pure Python dictionary in RAM with zero disk writes!
|
|
105
|
+
feed = core.get_subreddit_posts("sales", sort="top", time_filter="month", limit=10)
|
|
106
|
+
tree = core.get_reddit_post_and_comments("1abc23")
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
---
|
|
110
|
+
|
|
111
|
+
## 🚀 CLI Commands & Usage Examples
|
|
112
|
+
|
|
113
|
+
### 1. Interactive Wizard (Easiest for Humans)
|
|
114
|
+
```bash
|
|
115
|
+
python plugins/reddit-discussion-scraper/cli.py -i
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
### 2. Subreddit Feed Scraping
|
|
119
|
+
```bash
|
|
120
|
+
# Scrape top 25 hot posts from r/sales
|
|
121
|
+
python plugins/reddit-discussion-scraper/cli.py r/sales --sort hot --limit 25
|
|
122
|
+
|
|
123
|
+
# Scrape top posts of the past month from r/electricians
|
|
124
|
+
python plugins/reddit-discussion-scraper/cli.py r/electricians --sort top --time month --limit 50
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
### 3. Post & Nested Comment Tree Extraction
|
|
128
|
+
```bash
|
|
129
|
+
# Extract full discussion and nested comment tree from a post URL
|
|
130
|
+
python plugins/reddit-discussion-scraper/cli.py "https://www.reddit.com/r/sales/comments/1abc23/how_i_book_10_meetings/" --comments
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### 4. User Activity History
|
|
134
|
+
```bash
|
|
135
|
+
# Extract submission and comment history for a user
|
|
136
|
+
python plugins/reddit-discussion-scraper/cli.py u/spez --user --limit 50
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### 5. Keyword Search
|
|
140
|
+
```bash
|
|
141
|
+
# Search sitewide for buying intent
|
|
142
|
+
python plugins/reddit-discussion-scraper/cli.py --search "best CRM for small business" --limit 20
|
|
143
|
+
|
|
144
|
+
# Search within a specific subreddit
|
|
145
|
+
python plugins/reddit-discussion-scraper/cli.py r/SaaS --search "cold email deliverability"
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### 6. Media & Video Downloads
|
|
149
|
+
```bash
|
|
150
|
+
# Download attached MP4 video from a Reddit post
|
|
151
|
+
python plugins/reddit-discussion-scraper/cli.py "https://www.reddit.com/r/videos/comments/xyz123/clip/" --download-video
|
|
152
|
+
|
|
153
|
+
# Download video in 720p HD with preview thumbnail
|
|
154
|
+
python plugins/reddit-discussion-scraper/cli.py "https://www.reddit.com/r/funny/comments/xyz123/clip/" --download-video --download-thumb -q 720p
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
---
|
|
158
|
+
|
|
159
|
+
## 🔒 Rate Limiting & Safety Rails
|
|
160
|
+
|
|
161
|
+
- **RateLimiter**: Integrated with `plugins/shared/session_manager.py` enforcing a default pacing of 1.0–3.0 seconds between requests and a 100 requests/hour ceiling.
|
|
162
|
+
- **Burner Session Resilience**: If Cloudflare / network firewall blocks an IP (HTTP 403), users can configure a burner `reddit_session` cookie in `session_manager.py` which is injected automatically without modifying source code.
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: reddit-discussion-scraper
|
|
3
|
+
description: "Self-contained plugin and skill for scraping Reddit discussions, complete nested comment trees, user submission histories, keyword searches, and downloading v.redd.it media."
|
|
4
|
+
triggers:
|
|
5
|
+
- reddit.com
|
|
6
|
+
- redd.it
|
|
7
|
+
- r/
|
|
8
|
+
- u/
|
|
9
|
+
- reddit comments
|
|
10
|
+
- reddit discussion
|
|
11
|
+
- reddit scrape
|
|
12
|
+
- download reddit video
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
# Reddit Discussion Scraper & Media Downloader Skill
|
|
16
|
+
|
|
17
|
+
## Overview
|
|
18
|
+
This plugin executes zero-cost, zero-auth extraction of Reddit discussions, feeds, nested comments, and media using Reddit's public `.json` endpoints.
|
|
19
|
+
|
|
20
|
+
### Capabilities:
|
|
21
|
+
- **Subreddit Feeds**: Scrape `hot`, `new`, `top`, and `rising` posts from any subreddit with upvote ratios and comment counts.
|
|
22
|
+
- **Nested Comment Trees**: Full recursive comment trees with scores, authors, depth hierarchy, and timestamps.
|
|
23
|
+
- **User Activity History**: Complete history of submissions and comments for any Reddit user.
|
|
24
|
+
- **Cross-Reddit & Subreddit Search**: Keyword search across all of Reddit or confined to a specific community.
|
|
25
|
+
- **Media Downloader**: Extracts Reddit-hosted (`v.redd.it`) videos and thumbnails into `Outputs/`.
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## ⚡ CLI Usage Examples
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
# 1. Interactive Wizard
|
|
33
|
+
python plugins/reddit-discussion-scraper/cli.py -i
|
|
34
|
+
|
|
35
|
+
# 2. Scrape Subreddit Hot Posts
|
|
36
|
+
python plugins/reddit-discussion-scraper/cli.py r/sales --sort hot --limit 25
|
|
37
|
+
|
|
38
|
+
# 3. Scrape Top Posts of the Month
|
|
39
|
+
python plugins/reddit-discussion-scraper/cli.py r/electricians --sort top --time month --limit 50
|
|
40
|
+
|
|
41
|
+
# 4. Extract Full Post & Comment Tree
|
|
42
|
+
python plugins/reddit-discussion-scraper/cli.py "https://www.reddit.com/r/sales/comments/1abc23/sample_post/" --comments
|
|
43
|
+
|
|
44
|
+
# 5. Search Subreddit for Buying Intent
|
|
45
|
+
python plugins/reddit-discussion-scraper/cli.py r/smallbusiness --search "need CRM recommendation"
|
|
46
|
+
|
|
47
|
+
# 6. Download Video & Thumbnail from Reddit Post
|
|
48
|
+
python plugins/reddit-discussion-scraper/cli.py "https://www.reddit.com/r/funny/comments/1xyz89/video_post/" --download-video --download-thumb
|
|
49
|
+
|
|
50
|
+
# 7. Output directly to stdout for LLMs
|
|
51
|
+
python plugins/reddit-discussion-scraper/cli.py r/sales --limit 5 --stdout
|
|
52
|
+
```
|