返回 last30days-skill
reddit_enrich.py
根目录 / skills / last30days / scripts / lib / reddit_enrich.py
1 """Reddit thread enrichment with real engagement metrics.
2
3 Supports two backends:
4 1. ScrapeCreators API (preferred) - no rate limits, 1 credit/call
5 2. reddit.com/.json (fallback) - free but 429-prone
6 """
7
8 import math
9 import re
10 from datetime import datetime, timezone
11 from typing import Any, Dict, List, Optional
12 from urllib.parse import unquote, urlsplit
13
14 from . import http, dates, reddit_refs, snippet
15
16 _SAFE_SLUG_SEG = re.compile(r"^[A-Za-z0-9_.~%-]{1,200}\Z")
17
18
19 def _is_finite_int(value: int) -> bool:
20 try:
21 return math.isfinite(float(value))
22 except OverflowError:
23 return False
24
25
26 def _coerce_int_or_none(value: Any) -> Optional[int]:
27 if value is None or isinstance(value, bool):
28 return None
29 if isinstance(value, int):
30 return value if _is_finite_int(value) else None
31 if isinstance(value, float):
32 return int(value) if math.isfinite(value) else None
33 if isinstance(value, str):
34 text = value.strip()
35 if not text:
36 return None
37 try:
38 parsed = int(text)
39 except ValueError:
40 return None
41 return parsed if _is_finite_int(parsed) else None
42 return None
43
44
45 def _coerce_int(value: Any, default: Optional[int] = 0) -> Optional[int]:
46 coerced = _coerce_int_or_none(value)
47 return default if coerced is None else coerced
48
49
50 def _first_int(*values: Any, default: int = 0) -> int:
51 for v in values:
52 coerced = _coerce_int_or_none(v)
53 if coerced is not None:
54 return coerced
55 return default
56
57
58 def _coerce_float(value: Any) -> Optional[float]:
59 if value is None or isinstance(value, bool):
60 return None
61 if isinstance(value, (int, float)):
62 try:
63 num = float(value)
64 except (TypeError, ValueError, OverflowError):
65 return None
66 return num if math.isfinite(num) else None
67 if isinstance(value, str):
68 text = value.strip()
69 if not text:
70 return None
71 try:
72 num = float(text)
73 except (ValueError, OverflowError):
74 return None
75 return num if math.isfinite(num) else None
76 return None
77
78
79 def _coerce_timestamp(value: Any) -> Optional[float | int]:
80 if value is None or isinstance(value, bool):
81 return None
82 if isinstance(value, (int, float)):
83 if isinstance(value, float) and not math.isfinite(value):
84 return None
85 ts: float | int = value
86 elif isinstance(value, str):
87 text = value.strip()
88 if not text:
89 return None
90 try:
91 ts = float(text)
92 except ValueError:
93 return None
94 if not math.isfinite(ts):
95 return None
96 else:
97 return None
98 try:
99 datetime.fromtimestamp(ts, tz=timezone.utc)
100 except (ValueError, TypeError, OSError, OverflowError):
101 return None
102 return ts
103
104
105 def _safe_timestamp_to_date(value: Any) -> Optional[str]:
106 ts = _coerce_timestamp(value)
107 if ts is None:
108 return None
109 return dates.timestamp_to_date(ts)
110
111
112 def _coerce_text(value: Any) -> str:
113 if value is None or isinstance(value, bool):
114 return ""
115 return value if isinstance(value, str) else str(value)
116
117
118 def _coerce_author(value: Any, default: str = "[deleted]") -> str:
119 text = _coerce_text(value)
120 return text or default
121
122
123 def extract_reddit_path(url: str) -> Optional[str]:
124 """Extract a validated thread path from a Reddit URL.
125
126 Args:
127 url: Reddit thread URL
128
129 Returns:
130 Path component or None
131 """
132 if not isinstance(url, str):
133 return None
134 text = url.strip()
135 if not text or "://" not in text:
136 return None
137 try:
138 parsed = urlsplit(text)
139 port = parsed.port
140 except (ValueError, AttributeError):
141 return None
142 if parsed.scheme not in ("http", "https"):
143 return None
144 if parsed.username is not None or parsed.password is not None or "@" in parsed.netloc:
145 return None
146 default_port = 443 if parsed.scheme == "https" else 80
147 if port is not None and port != default_port:
148 return None
149 host = (parsed.hostname or "").lower()
150 if host not in reddit_refs._HOSTS:
151 return None
152 ref = reddit_refs.canonical_thread_url(text)
153 if ref is None:
154 return None
155 raw_path = parsed.path or ""
156 if not raw_path.startswith("/") or raw_path.startswith("//") or "\\" in raw_path:
157 return None
158 if any(ord(ch) <= 0x20 or ord(ch) == 0x7F for ch in raw_path):
159 return None
160 segments = [seg for seg in raw_path.split("/") if seg]
161 if not segments:
162 return None
163 for seg in segments:
164 if not _SAFE_SLUG_SEG.match(seg):
165 return None
166 if seg in (".", ".."):
167 return None
168 decoded = unquote(seg)
169 decoded_twice = unquote(decoded)
170 for candidate in (decoded, decoded_twice):
171 if (
172 candidate in (".", "..")
173 or any(ch in candidate for ch in ("/", "\\", "?", "#"))
174 or any(ord(ch) <= 0x20 or ord(ch) == 0x7F for ch in candidate)
175 ):
176 return None
177 # Tail segments after /r/<sub>/comments/<id> or /comments/<id> are at most slug + comment_id.
178 tail_start = 4 if ref.subreddit else 2
179 if len(segments) < tail_start or len(segments) > tail_start + 2:
180 return None
181 return raw_path
182
183
184 class RedditRateLimitError(Exception):
185 """Raised when Reddit returns HTTP 429 (rate limited)."""
186 pass
187
188
189 def fetch_thread_data(
190 url: str,
191 mock_data: Optional[Dict] = None,
192 timeout: int = 30,
193 retries: int = 3,
194 ) -> Optional[Dict[str, Any]]:
195 """Fetch Reddit thread JSON data.
196
197 Args:
198 url: Reddit thread URL
199 mock_data: Mock data for testing
200 timeout: HTTP timeout per attempt in seconds
201 retries: Number of retries on failure
202
203 Returns:
204 Thread data dict or None on failure
205
206 Raises:
207 RedditRateLimitError: When Reddit returns 429 (caller should bail)
208 """
209 if mock_data is not None:
210 return mock_data
211
212 path = extract_reddit_path(url)
213 if not path:
214 return None
215
216 try:
217 data = http.get_reddit_json(path, timeout=timeout, retries=retries)
218 return data
219 except http.HTTPError as e:
220 if e.status_code == 429:
221 raise RedditRateLimitError(f"Reddit rate limited (429) fetching {url}") from e
222 return None
223
224
225 def parse_thread_data(data: Any) -> Dict[str, Any]:
226 """Parse Reddit thread JSON into structured data.
227
228 Args:
229 data: Raw Reddit JSON response
230
231 Returns:
232 Dict with submission and comments data
233 """
234 result = {
235 "submission": None,
236 "comments": [],
237 }
238
239 if not isinstance(data, list) or len(data) < 1:
240 return result
241
242 # First element is submission listing
243 submission_listing = data[0]
244 if isinstance(submission_listing, dict):
245 listing_data = submission_listing.get("data")
246 children = listing_data.get("children") if isinstance(listing_data, dict) else None
247 if isinstance(children, list) and children:
248 first_child = children[0]
249 sub_data = first_child.get("data") if isinstance(first_child, dict) else None
250 if isinstance(sub_data, dict):
251 raw_permalink = sub_data.get("permalink")
252 raw_title = sub_data.get("title")
253 title = (
254 raw_title
255 if isinstance(raw_title, str)
256 else (None if raw_title is None or isinstance(raw_title, bool) else str(raw_title))
257 )
258 result["submission"] = {
259 "score": _coerce_int(sub_data.get("score"), default=None),
260 "num_comments": _coerce_int(sub_data.get("num_comments"), default=None),
261 "upvote_ratio": _coerce_float(sub_data.get("upvote_ratio")),
262 "created_utc": _coerce_timestamp(sub_data.get("created_utc")),
263 "permalink": raw_permalink if isinstance(raw_permalink, str) else None,
264 "title": title,
265 "selftext": _coerce_text(sub_data.get("selftext"))[:500], # Truncate
266 }
267
268 # Second element is comments listing
269 if len(data) >= 2:
270 comments_listing = data[1]
271 if isinstance(comments_listing, dict):
272 comments_data = comments_listing.get("data")
273 children = comments_data.get("children") if isinstance(comments_data, dict) else None
274 if isinstance(children, list):
275 for child in children:
276 if not isinstance(child, dict) or child.get("kind") != "t1": # t1 = comment
277 continue
278 c_data = child.get("data")
279 if not isinstance(c_data, dict):
280 continue
281 body = _coerce_text(c_data.get("body"))
282 if not body:
283 continue
284
285 raw_permalink = c_data.get("permalink")
286 comment = {
287 "score": _coerce_int(c_data.get("score"), default=0),
288 "created_utc": _coerce_timestamp(c_data.get("created_utc")),
289 "author": _coerce_author(c_data.get("author")),
290 "body": body[:600], # Truncate; the stored excerpt is cut cleanly from this
291 "permalink": raw_permalink if isinstance(raw_permalink, str) else None,
292 }
293 # Reddit says whether the thread's own poster wrote this.
294 if isinstance(c_data.get("is_submitter"), bool):
295 comment["is_submitter"] = c_data["is_submitter"]
296 result["comments"].append(comment)
297
298 return result
299
300
301 def stored_top_comments(comments: List[Dict]) -> List[Dict[str, Any]]:
302 """Parsed comments in the shape an item stores them. ``is_uploader`` is
303 Reddit's ``is_submitter`` (the thread's own poster wrote the comment), and
304 is left out when the thread data did not say."""
305 if not isinstance(comments, list):
306 return []
307 stored = []
308 for c in comments:
309 if not isinstance(c, dict):
310 continue
311 raw_permalink = c.get("permalink")
312 permalink = raw_permalink if isinstance(raw_permalink, str) else ""
313 entry = {
314 "score": _coerce_int(c.get("score"), default=0),
315 "date": _safe_timestamp_to_date(c.get("created_utc")),
316 "author": _coerce_text(c.get("author")),
317 "excerpt": snippet.cut_quote(_coerce_text(c.get("body"))),
318 "url": f"https://reddit.com{permalink}" if permalink else "",
319 }
320 if isinstance(c.get("is_submitter"), bool):
321 entry["is_uploader"] = c["is_submitter"]
322 stored.append(entry)
323 return stored
324
325
326 def get_top_comments(comments: List[Dict], limit: int = 10) -> List[Dict[str, Any]]:
327 """Get top comments sorted by score.
328
329 Args:
330 comments: List of comment dicts
331 limit: Maximum number to return
332
333 Returns:
334 Top comments sorted by score
335 """
336 if not isinstance(comments, list):
337 return []
338
339 # Filter out non-dicts and deleted/removed
340 valid = [
341 c for c in comments
342 if isinstance(c, dict) and c.get("author") not in ("[deleted]", "[removed]")
343 ]
344
345 # Sort by score descending
346 sorted_comments = sorted(
347 valid,
348 key=lambda c: _coerce_int(c.get("score"), default=0),
349 reverse=True,
350 )
351
352 return sorted_comments[:limit]
353
354
355 def extract_comment_insights(comments: List[Dict], limit: int = 7) -> List[str]:
356 """Extract key insights from top comments.
357
358 Uses simple heuristics to identify valuable comments:
359 - Has substantive text
360 - Contains actionable information
361 - Not just agreement/disagreement
362
363 Args:
364 comments: Top comments
365 limit: Max insights to extract
366
367 Returns:
368 List of insight strings
369 """
370 if not isinstance(comments, list):
371 return []
372 insights = []
373
374 for comment in comments[:limit * 2]: # Look at more comments than we need
375 if not isinstance(comment, dict):
376 continue
377 body = _coerce_text(comment.get("body")).strip()
378 if not body or len(body) < 30:
379 continue
380
381 # Skip low-value patterns
382 skip_patterns = [
383 r'^(this|same|agreed|exactly|yep|nope|yes|no|thanks|thank you)\.?$',
384 r'^lol|lmao|haha',
385 r'^\[deleted\]',
386 r'^\[removed\]',
387 ]
388 if any(re.match(p, body.lower()) for p in skip_patterns):
389 continue
390
391 # Truncate to first meaningful sentence or ~150 chars
392 insight = body[:150]
393 if len(body) > 150:
394 # Try to find a sentence boundary
395 for i, char in enumerate(insight):
396 if char in '.!?' and i > 50:
397 insight = insight[:i+1]
398 break
399 else:
400 insight = insight.rstrip() + "..."
401
402 insights.append(insight)
403 if len(insights) >= limit:
404 break
405
406 return insights
407
408
409 def enrich_reddit_item(
410 item: Dict[str, Any],
411 mock_thread_data: Optional[Dict] = None,
412 timeout: int = 10,
413 retries: int = 1,
414 ) -> Dict[str, Any]:
415 """Enrich a Reddit item with real engagement data.
416
417 Args:
418 item: Reddit item dict
419 mock_thread_data: Mock data for testing
420 timeout: HTTP timeout per attempt (default 10s for enrichment)
421 retries: Number of retries (default 1 — fail fast for enrichment)
422
423 Returns:
424 Enriched item dict
425
426 Raises:
427 RedditRateLimitError: Propagated so caller can bail on remaining items
428 """
429 url = item.get("url", "")
430
431 # Fetch thread data (RedditRateLimitError propagates to caller)
432 thread_data = fetch_thread_data(url, mock_thread_data, timeout=timeout, retries=retries)
433 if not thread_data:
434 return item
435
436 parsed = parse_thread_data(thread_data)
437 submission = parsed.get("submission")
438 comments = parsed.get("comments", [])
439
440 # Update engagement metrics
441 if submission:
442 item["engagement"] = {
443 "score": submission.get("score"),
444 "num_comments": submission.get("num_comments"),
445 "upvote_ratio": submission.get("upvote_ratio"),
446 }
447
448 # Update date from actual data
449 created_utc = submission.get("created_utc")
450 if created_utc:
451 item["date"] = _safe_timestamp_to_date(created_utc)
452
453 # Get top comments
454 top_comments = get_top_comments(comments)
455 item["top_comments"] = stored_top_comments(top_comments)
456
457 # Extract insights
458 item["comment_insights"] = extract_comment_insights(top_comments)
459
460 return item
461
462
463 def enrich_reddit_item_sc(
464 item: Dict[str, Any],
465 token: str,
466 timeout: int = 30,
467 ) -> Dict[str, Any]:
468 """Enrich a Reddit item using ScrapeCreators comment API.
469
470 No rate limit risk. Uses 1 credit per call.
471
472 Args:
473 item: Reddit item dict (already has engagement from search)
474 token: ScrapeCreators API key
475 timeout: HTTP timeout
476
477 Returns:
478 Enriched item with top_comments and comment_insights
479 """
480 from . import reddit as reddit_mod
481
482 url = item.get("url", "")
483 if not url:
484 return item
485
486 raw_comments = reddit_mod.fetch_post_comments(url, token)
487 if not isinstance(raw_comments, list) or not raw_comments:
488 return item
489
490 dict_comments = [c for c in raw_comments if isinstance(c, dict)]
491 if not dict_comments:
492 return item
493
494 top_comments = []
495 for c in dict_comments[:10]:
496 body = _coerce_text(c.get("body"))
497 if not body or body in ("[deleted]", "[removed]"):
498 continue
499
500 score = _first_int(c.get("ups"), c.get("score"), default=0)
501 author = _coerce_author(c.get("author"))
502 raw_permalink = c.get("permalink")
503 permalink = raw_permalink if isinstance(raw_permalink, str) else ""
504 comment_url = f"https://reddit.com{permalink}" if permalink else ""
505
506 top_comments.append({
507 "score": score,
508 "date": _safe_timestamp_to_date(c.get("created_utc")) if c.get("created_utc") else None,
509 "author": author,
510 "body": body[:300],
511 "excerpt": snippet.cut_quote(body),
512 "url": comment_url,
513 })
514
515 top_comments.sort(key=lambda c: _coerce_int(c.get("score"), default=0), reverse=True)
516
517 item["top_comments"] = []
518 for c in top_comments:
519 item["top_comments"].append({
520 "score": c.get("score", 0),
521 "date": c.get("date"),
522 "author": c.get("author", ""),
523 "excerpt": c.get("excerpt", ""),
524 "url": c.get("url", ""),
525 })
526
527 item["comment_insights"] = extract_comment_insights(top_comments)
528
529 return item
530
530 lines PYTHON