| 1 | """Reddit search via ScrapeCreators API for the v3 pipeline. |
| 2 | |
| 3 | Uses ScrapeCreators REST API to search Reddit globally, discover relevant |
| 4 | subreddits, run targeted subreddit searches, and fetch comment trees. |
| 5 | |
| 6 | Requires SCRAPECREATORS_API_KEY in config (same key as TikTok + Instagram). |
| 7 | API docs: https://scrapecreators.com/docs |
| 8 | """ |
| 9 | |
| 10 | import contextlib |
| 11 | import contextvars |
| 12 | import copy |
| 13 | import math |
| 14 | import re |
| 15 | import sys |
| 16 | import threading |
| 17 | import time |
| 18 | from collections import Counter |
| 19 | from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, as_completed, wait as futures_wait |
| 20 | from contextlib import ExitStack |
| 21 | from dataclasses import dataclass |
| 22 | from datetime import date, datetime, timezone |
| 23 | from typing import Any, Dict, Iterator, List, Optional, Set |
| 24 | |
| 25 | def _first_of(*values, default=None): |
| 26 | """Return first value that is not None.""" |
| 27 | for v in values: |
| 28 | if v is not None: |
| 29 | return v |
| 30 | return default |
| 31 | |
| 32 | |
| 33 | def _as_dict_list(value: Any) -> List[Dict[str, Any]]: |
| 34 | if not isinstance(value, list): |
| 35 | return [] |
| 36 | return [item for item in value if isinstance(item, dict)] |
| 37 | |
| 38 | |
| 39 | def _extract_dict_list( |
| 40 | data: Any, |
| 41 | primary_key: str, |
| 42 | *, |
| 43 | context: str = "", |
| 44 | ) -> List[Dict[str, Any]]: |
| 45 | label = f"ScrapeCreators Reddit {context}" if context else "ScrapeCreators Reddit" |
| 46 | if not isinstance(data, dict): |
| 47 | http._record_failure(http.HTTPError( |
| 48 | f"{label} returned non-object JSON ({type(data).__name__}) (schema drift)", |
| 49 | outcome_state=health.SCHEMA_DRIFT, |
| 50 | )) |
| 51 | return [] |
| 52 | primary = data.get(primary_key) |
| 53 | raw: Any = None |
| 54 | drift_reason: Optional[str] = None |
| 55 | if isinstance(primary, list): |
| 56 | raw = primary |
| 57 | else: |
| 58 | fallback = data.get("data") |
| 59 | if isinstance(fallback, list): |
| 60 | raw = fallback |
| 61 | if primary is not None: |
| 62 | drift_reason = ( |
| 63 | f"{label} returned non-list '{primary_key}' ({type(primary).__name__}) " |
| 64 | "(schema drift)" |
| 65 | ) |
| 66 | else: |
| 67 | if primary_key in data: |
| 68 | drift_reason = ( |
| 69 | f"{label} returned non-list '{primary_key}' ({type(primary).__name__}) " |
| 70 | "without usable 'data' list (schema drift)" |
| 71 | ) |
| 72 | elif "data" in data: |
| 73 | drift_reason = ( |
| 74 | f"{label} returned non-list 'data' ({type(fallback).__name__}) (schema drift)" |
| 75 | ) |
| 76 | else: |
| 77 | drift_reason = ( |
| 78 | f"{label} response missing '{primary_key}'/'data' list (schema drift)" |
| 79 | ) |
| 80 | if raw is None: |
| 81 | http._record_failure(http.HTTPError( |
| 82 | drift_reason or f"{label} returned unexpected payload shape (schema drift)", |
| 83 | outcome_state=health.SCHEMA_DRIFT, |
| 84 | )) |
| 85 | return [] |
| 86 | valid = [item for item in raw if isinstance(item, dict)] |
| 87 | if drift_reason is not None: |
| 88 | http._record_failure(http.HTTPError( |
| 89 | drift_reason, |
| 90 | outcome_state=health.SCHEMA_DRIFT, |
| 91 | )) |
| 92 | elif len(valid) < len(raw): |
| 93 | dropped = len(raw) - len(valid) |
| 94 | http._record_failure(http.HTTPError( |
| 95 | f"{label} dropped {dropped} non-object entries in '{primary_key}' (schema drift)", |
| 96 | outcome_state=health.SCHEMA_DRIFT, |
| 97 | )) |
| 98 | return valid |
| 99 | |
| 100 | |
| 101 | def _is_finite_int(value: int) -> bool: |
| 102 | try: |
| 103 | return math.isfinite(float(value)) |
| 104 | except OverflowError: |
| 105 | return False |
| 106 | |
| 107 | |
| 108 | def _coerce_int_or_none(value: Any) -> Optional[int]: |
| 109 | if value is None or isinstance(value, bool): |
| 110 | return None |
| 111 | if isinstance(value, int): |
| 112 | return value if _is_finite_int(value) else None |
| 113 | if isinstance(value, float): |
| 114 | return int(value) if math.isfinite(value) else None |
| 115 | if isinstance(value, str): |
| 116 | text = value.strip() |
| 117 | if not text: |
| 118 | return None |
| 119 | try: |
| 120 | parsed = int(text) |
| 121 | except ValueError: |
| 122 | return None |
| 123 | return parsed if _is_finite_int(parsed) else None |
| 124 | return None |
| 125 | |
| 126 | |
| 127 | def _coerce_int(value: Any, default: int = 0) -> int: |
| 128 | coerced = _coerce_int_or_none(value) |
| 129 | return default if coerced is None else coerced |
| 130 | |
| 131 | |
| 132 | def _first_int(*values: Any, default: int = 0) -> int: |
| 133 | for v in values: |
| 134 | coerced = _coerce_int_or_none(v) |
| 135 | if coerced is not None: |
| 136 | return coerced |
| 137 | return default |
| 138 | |
| 139 | |
| 140 | def _coerce_float(value: Any) -> Optional[float]: |
| 141 | if value is None or isinstance(value, bool): |
| 142 | return None |
| 143 | if isinstance(value, (int, float)): |
| 144 | try: |
| 145 | num = float(value) |
| 146 | except (TypeError, ValueError, OverflowError): |
| 147 | return None |
| 148 | return num if math.isfinite(num) else None |
| 149 | if isinstance(value, str): |
| 150 | text = value.strip() |
| 151 | if not text: |
| 152 | return None |
| 153 | try: |
| 154 | num = float(text) |
| 155 | except (ValueError, OverflowError): |
| 156 | return None |
| 157 | return num if math.isfinite(num) else None |
| 158 | return None |
| 159 | |
| 160 | |
| 161 | def _coerce_text(value: Any) -> str: |
| 162 | if value is None or isinstance(value, bool): |
| 163 | return "" |
| 164 | return value if isinstance(value, str) else str(value) |
| 165 | |
| 166 | from . import dates, health, http, log, snippet |
| 167 | |
| 168 | SCRAPECREATORS_BASE = "https://api.scrapecreators.com/v1/reddit" |
| 169 | |
| 170 | |
| 171 | def _sc_base() -> str: |
| 172 | if SCRAPECREATORS_BASE != "https://api.scrapecreators.com/v1/reddit": |
| 173 | return SCRAPECREATORS_BASE |
| 174 | from . import env |
| 175 | return f"{env.get_scrapecreators_base_url()}/v1/reddit" |
| 176 | |
| 177 | # Reddit's highest-upvote content (relationship drama, AITA, viral news) often |
| 178 | # has near-zero topic overlap. Engagement-only ranking floats it above on-topic |
| 179 | # posts, especially on bare global searches where no subreddits were resolved |
| 180 | # upstream. A relevance floor + relevance-first ranking (see _relevance_rank_key |
| 181 | # below and RELEVANCE_FLOOR / MIN_ON_TOPIC in relevance.py) keeps an off-topic |
| 182 | # viral post from ever outranking an on-topic one. |
| 183 | |
| 184 | # Depth configurations: how many API calls per phase |
| 185 | DEPTH_CONFIG = { |
| 186 | "quick": { |
| 187 | "global_searches": 1, |
| 188 | "subreddit_searches": 2, |
| 189 | "comment_enrichments": 3, |
| 190 | }, |
| 191 | "default": { |
| 192 | "global_searches": 2, |
| 193 | "subreddit_searches": 3, |
| 194 | "comment_enrichments": 5, |
| 195 | }, |
| 196 | "deep": { |
| 197 | "global_searches": 3, |
| 198 | "subreddit_searches": 5, |
| 199 | "comment_enrichments": 8, |
| 200 | }, |
| 201 | } |
| 202 | |
| 203 | from .query import extract_core_subject as _query_extract, infer_query_intent |
| 204 | from .relevance import token_overlap_relevance, RELEVANCE_FLOOR, MIN_ON_TOPIC |
| 205 | |
| 206 | |
| 207 | # Reddit-specific noise words (preserves original smaller set) |
| 208 | NOISE_WORDS = frozenset({ |
| 209 | 'best', 'top', 'good', 'great', 'awesome', 'killer', |
| 210 | 'latest', 'new', 'news', 'update', 'updates', |
| 211 | 'trending', 'hottest', 'popular', |
| 212 | 'practices', 'features', 'tips', |
| 213 | 'recommendations', 'advice', |
| 214 | 'prompt', 'prompts', 'prompting', |
| 215 | 'methods', 'strategies', 'approaches', |
| 216 | 'how', 'to', 'the', 'a', 'an', 'for', 'with', |
| 217 | 'of', 'in', 'on', 'is', 'are', 'what', 'which', |
| 218 | 'guide', 'tutorial', 'using', |
| 219 | }) |
| 220 | |
| 221 | |
| 222 | def _log(msg: str): |
| 223 | log.source_log("Reddit", msg, tty_only=False) |
| 224 | |
| 225 | |
| 226 | # Run-scoped spend bound for ScrapeCreators Reddit calls. Pool workers inherit |
| 227 | # it via http.submit_with_context so an abandoned backfill thread stops before |
| 228 | # starting additional paid subreddit/global searches or comment fetches. |
| 229 | @dataclass(frozen=True) |
| 230 | class _SCSpendLimit: |
| 231 | deadline: Optional[float] = None |
| 232 | cancels: tuple[threading.Event, ...] = () |
| 233 | |
| 234 | |
| 235 | _sc_spend_limit: contextvars.ContextVar[Optional[_SCSpendLimit]] = ( |
| 236 | contextvars.ContextVar("reddit_sc_spend_limit", default=None) |
| 237 | ) |
| 238 | |
| 239 | # Shared mutable [bool] flag owned by search_and_enrich_memo and inherited by |
| 240 | # pool workers via http.submit_with_context. Flipped to True right before any |
| 241 | # paid ScrapeCreators HTTP request so mid-spend timeouts are cached and never |
| 242 | # paid for twice, while pre-spend cancellations stay uncached. |
| 243 | _sc_paid_started: contextvars.ContextVar[Optional[list[bool]]] = ( |
| 244 | contextvars.ContextVar("reddit_sc_paid_started", default=None) |
| 245 | ) |
| 246 | |
| 247 | _SC_STOPPED_MSG = "ScrapeCreators Reddit backfill cancelled or timed out" |
| 248 | _SC_COMMENTS_INCOMPLETE_NOTE = "Reddit comments incomplete (deadline reached)" |
| 249 | _SC_SEARCH_INCOMPLETE_NOTE = "Reddit subreddit drill-down incomplete (deadline reached)" |
| 250 | |
| 251 | |
| 252 | def _mark_sc_paid_started() -> None: |
| 253 | flag = _sc_paid_started.get() |
| 254 | if flag is not None: |
| 255 | flag[0] = True |
| 256 | |
| 257 | |
| 258 | @contextlib.contextmanager |
| 259 | def sc_spend_until( |
| 260 | *, |
| 261 | deadline: Optional[float] = None, |
| 262 | cancel: Optional[threading.Event] = None, |
| 263 | ) -> Iterator[None]: |
| 264 | """Refuse ScrapeCreators Reddit HTTP calls once ``cancel`` or ``deadline`` fires. |
| 265 | |
| 266 | Nested contexts tighten the deadline and accumulate cancel events so both |
| 267 | external run cancellation and backfill-local abandonment stop paid spend. |
| 268 | """ |
| 269 | outer = _sc_spend_limit.get() |
| 270 | merged_deadline = deadline |
| 271 | cancels: list[threading.Event] = [] |
| 272 | if outer is not None: |
| 273 | if outer.deadline is not None: |
| 274 | merged_deadline = ( |
| 275 | outer.deadline |
| 276 | if merged_deadline is None |
| 277 | else min(outer.deadline, merged_deadline) |
| 278 | ) |
| 279 | cancels.extend(outer.cancels) |
| 280 | if cancel is not None and cancel not in cancels: |
| 281 | cancels.append(cancel) |
| 282 | token = _sc_spend_limit.set(_SCSpendLimit(deadline=merged_deadline, cancels=tuple(cancels))) |
| 283 | try: |
| 284 | yield |
| 285 | finally: |
| 286 | _sc_spend_limit.reset(token) |
| 287 | |
| 288 | |
| 289 | def _effective_spend_limit( |
| 290 | deadline_monotonic: float | None = None, |
| 291 | cancel: threading.Event | None = None, |
| 292 | ) -> tuple[float | None, tuple[threading.Event, ...]]: |
| 293 | limit = _sc_spend_limit.get() |
| 294 | eff_deadline = deadline_monotonic |
| 295 | cancels: list[threading.Event] = [] |
| 296 | if limit is not None: |
| 297 | if limit.deadline is not None: |
| 298 | eff_deadline = ( |
| 299 | limit.deadline |
| 300 | if eff_deadline is None |
| 301 | else min(eff_deadline, limit.deadline) |
| 302 | ) |
| 303 | cancels.extend(limit.cancels) |
| 304 | if cancel is not None and cancel not in cancels: |
| 305 | cancels.append(cancel) |
| 306 | return eff_deadline, tuple(cancels) |
| 307 | |
| 308 | |
| 309 | def _sc_cancelled(cancel: threading.Event | None = None) -> bool: |
| 310 | _, cancels = _effective_spend_limit(None, cancel) |
| 311 | return any(ev.is_set() for ev in cancels) |
| 312 | |
| 313 | |
| 314 | def _sc_spend_stopped( |
| 315 | deadline_monotonic: float | None = None, |
| 316 | cancel: threading.Event | None = None, |
| 317 | ) -> bool: |
| 318 | eff_deadline, cancels = _effective_spend_limit(deadline_monotonic, cancel) |
| 319 | if any(ev.is_set() for ev in cancels): |
| 320 | return True |
| 321 | return eff_deadline is not None and time.monotonic() >= eff_deadline |
| 322 | |
| 323 | |
| 324 | def _check_sc_spend( |
| 325 | deadline_monotonic: float | None = None, |
| 326 | cancel: threading.Event | None = None, |
| 327 | ) -> tuple[float | None, threading.Event | None]: |
| 328 | if _sc_spend_stopped(deadline_monotonic, cancel): |
| 329 | raise TimeoutError(_SC_STOPPED_MSG) |
| 330 | eff_deadline, cancels = _effective_spend_limit(deadline_monotonic, cancel) |
| 331 | eff_cancel = cancel if cancel is not None else (cancels[0] if cancels else None) |
| 332 | return eff_deadline, eff_cancel |
| 333 | |
| 334 | |
| 335 | def _search_batch_deadline(eff_deadline: float | None) -> float | None: |
| 336 | """Reserve a short return margin before ``eff_deadline`` for batch collection.""" |
| 337 | if eff_deadline is None: |
| 338 | return None |
| 339 | rem = max(0.0, eff_deadline - time.monotonic()) |
| 340 | return eff_deadline - min(1.5, rem * 0.1) |
| 341 | |
| 342 | |
| 343 | def _collect_bounded( |
| 344 | executor: ThreadPoolExecutor, |
| 345 | futures: dict, |
| 346 | *, |
| 347 | deadline_monotonic: float | None = None, |
| 348 | cancel: threading.Event | None = None, |
| 349 | ) -> tuple[list[tuple[Any, Any]], bool]: |
| 350 | """Collect finished ``(tag, value)`` pairs and whether any sibling timed out. |
| 351 | |
| 352 | Fatal auth/payment HTTP errors still propagate immediately. |
| 353 | """ |
| 354 | eff_deadline, cancels = _effective_spend_limit(deadline_monotonic, cancel) |
| 355 | if eff_deadline is None and not cancels: |
| 356 | results: list[tuple[Any, Any]] = [] |
| 357 | incomplete = False |
| 358 | for future in as_completed(futures): |
| 359 | try: |
| 360 | results.append((futures[future], future.result())) |
| 361 | except TimeoutError: |
| 362 | incomplete = True |
| 363 | return results, incomplete |
| 364 | pending = set(futures) |
| 365 | results = [] |
| 366 | incomplete = False |
| 367 | try: |
| 368 | while pending: |
| 369 | # Always harvest already-finished futures before checking the |
| 370 | # cutoff so sibling posts that arrived in time are never discarded. |
| 371 | finished = {f for f in pending if f.done() and not f.cancelled()} |
| 372 | if finished: |
| 373 | pending -= finished |
| 374 | for future in finished: |
| 375 | try: |
| 376 | results.append((futures[future], future.result(timeout=0))) |
| 377 | except TimeoutError: |
| 378 | incomplete = True |
| 379 | continue |
| 380 | if any(ev.is_set() for ev in cancels) or ( |
| 381 | eff_deadline is not None and time.monotonic() >= eff_deadline |
| 382 | ): |
| 383 | incomplete = True |
| 384 | for future in pending: |
| 385 | future.cancel() |
| 386 | executor.shutdown(wait=False, cancel_futures=True) |
| 387 | break |
| 388 | timeout = 0.1 |
| 389 | if eff_deadline is not None: |
| 390 | timeout = max(0.0, min(0.1, eff_deadline - time.monotonic())) |
| 391 | done, pending = futures_wait(pending, timeout=timeout, return_when=FIRST_COMPLETED) |
| 392 | for future in done: |
| 393 | try: |
| 394 | results.append((futures[future], future.result(timeout=0))) |
| 395 | except TimeoutError: |
| 396 | incomplete = True |
| 397 | return results, incomplete |
| 398 | except BaseException: |
| 399 | for future in pending: |
| 400 | future.cancel() |
| 401 | executor.shutdown(wait=False, cancel_futures=True) |
| 402 | raise |
| 403 | |
| 404 | |
| 405 | def classify_run_failure(detail: str) -> str: |
| 406 | """Map Reddit auth and anti-bot responses that do not carry HTTP status.""" |
| 407 | text = detail.lower() |
| 408 | if any(marker in text for marker in ("interstitial", "blocked by reddit", "too many requests")): |
| 409 | return health.RATE_LIMITED |
| 410 | if any(marker in text for marker in ("login required", "invalid token", "expired token")): |
| 411 | return health.AUTH_FAILED |
| 412 | return http.classify_failure(message=detail) |
| 413 | |
| 414 | |
| 415 | def _extract_core_subject(topic: str) -> str: |
| 416 | """Extract core subject from verbose query. |
| 417 | |
| 418 | Strips meta/research words to keep only the core product/concept name. |
| 419 | """ |
| 420 | return _query_extract(topic, noise=NOISE_WORDS) |
| 421 | |
| 422 | |
| 423 | def expand_reddit_queries(topic: str, depth: str) -> List[str]: |
| 424 | """Generate multiple Reddit search queries from a topic. |
| 425 | |
| 426 | Uses local logic (no LLM call needed): |
| 427 | 1. Extract core subject (strip noise words) |
| 428 | 2. Include original topic if different from core |
| 429 | 3. For default/deep: add casual/review variant |
| 430 | 4. For deep: add problem/issues variant |
| 431 | |
| 432 | Returns 1-4 query strings depending on depth. |
| 433 | """ |
| 434 | core = _extract_core_subject(topic) |
| 435 | queries = [core] |
| 436 | |
| 437 | # Broader variant: include more context from original topic |
| 438 | original_clean = topic.strip().rstrip('?!.') |
| 439 | if core.lower() != original_clean.lower() and len(original_clean.split()) <= 8: |
| 440 | queries.append(original_clean) |
| 441 | |
| 442 | qtype = infer_query_intent(topic) |
| 443 | |
| 444 | # Product queries: always include review-oriented variant to bias toward |
| 445 | # review communities instead of keyword-matching unrelated subreddits. |
| 446 | if qtype == "product": |
| 447 | queries.append(f"{core} review OR recommendation OR best") |
| 448 | |
| 449 | # Comparison queries: include head-to-head discussion variant. |
| 450 | if qtype == "comparison": |
| 451 | queries.append(f"{core} worth it OR vs OR compared") |
| 452 | |
| 453 | # Opinion/review variants for default/deep depth. |
| 454 | if depth in ("default", "deep") and qtype in ("product", "opinion"): |
| 455 | queries.append(f"{core} worth it OR thoughts OR review") |
| 456 | |
| 457 | # Problem/bug variants are useful for tool workflows, not generic news. |
| 458 | if depth == "deep" and qtype in ("product", "opinion", "how_to"): |
| 459 | queries.append(f"{core} issues OR problems OR bug OR broken") |
| 460 | |
| 461 | return queries |
| 462 | |
| 463 | |
| 464 | # Known utility/meta subreddits that match queries but aren't discussion subs. |
| 465 | # These get a 0.3x penalty (not banned) in subreddit discovery scoring. |
| 466 | UTILITY_SUBS = frozenset({ |
| 467 | 'namethatsong', 'findthatsong', 'tipofmytongue', |
| 468 | 'whatisthissong', 'helpmefind', 'whatisthisthing', |
| 469 | 'whatsthissong', 'findareddit', 'subredditdrama', |
| 470 | }) |
| 471 | |
| 472 | |
| 473 | def discover_subreddits( |
| 474 | results: List[Dict[str, Any]], |
| 475 | topic: str = "", |
| 476 | max_subs: int = 5, |
| 477 | ) -> List[str]: |
| 478 | """Extract top subreddits from global search results with relevance weighting. |
| 479 | |
| 480 | Uses frequency + topic-word matching + utility-sub penalties + engagement |
| 481 | bonus to find discussion subs rather than utility/meta subs. |
| 482 | |
| 483 | Args: |
| 484 | results: List of post dicts from global search |
| 485 | topic: Original search topic (for relevance matching) |
| 486 | max_subs: Maximum subreddits to return |
| 487 | |
| 488 | Returns: |
| 489 | Top subreddit names sorted by weighted score |
| 490 | """ |
| 491 | core = _extract_core_subject(topic) if topic else "" |
| 492 | core_words = set(core.lower().split()) if core else set() |
| 493 | |
| 494 | scores = Counter() |
| 495 | for post in results: |
| 496 | if not isinstance(post, dict): |
| 497 | continue |
| 498 | sub = _extract_subreddit_name(post.get("subreddit", "")) |
| 499 | if not sub: |
| 500 | continue |
| 501 | |
| 502 | # Base: frequency count |
| 503 | base = 1.0 |
| 504 | |
| 505 | # Bonus: subreddit name contains a core topic word |
| 506 | sub_lower = sub.lower() |
| 507 | if core_words and any(w in sub_lower for w in core_words if len(w) > 2): |
| 508 | base += 2.0 |
| 509 | |
| 510 | # Penalty: known utility/meta subreddits |
| 511 | if sub_lower in UTILITY_SUBS: |
| 512 | base *= 0.3 |
| 513 | |
| 514 | # Bonus: post engagement (high-engagement posts = better sub) |
| 515 | ups = _first_int(post.get("ups"), post.get("score"), post.get("votes"), default=0) |
| 516 | if ups > 100: |
| 517 | base += 0.5 |
| 518 | |
| 519 | scores[sub] += base |
| 520 | |
| 521 | return [sub for sub, _ in scores.most_common(max_subs)] |
| 522 | |
| 523 | |
| 524 | def _parse_date(value) -> Optional[str]: |
| 525 | """Convert Unix timestamp or ISO-8601 string to YYYY-MM-DD. |
| 526 | |
| 527 | Global search returns ``created_at`` as an ISO string |
| 528 | (e.g. "2018-05-03T01:09:17.620000+0000"); subreddit search returns |
| 529 | ``created_utc`` as a Unix timestamp. dates.parse_date() handles both, |
| 530 | plus edge cases like Z suffix and +0000 (no colon) offset. |
| 531 | |
| 532 | Falsy inputs (None, "", 0) return None, matching the original behavior |
| 533 | where a Unix timestamp of 0 meant "no date" rather than epoch 0. |
| 534 | """ |
| 535 | if not value or isinstance(value, bool): |
| 536 | return None |
| 537 | if isinstance(value, float) and not math.isfinite(value): |
| 538 | return None |
| 539 | try: |
| 540 | dt = dates.parse_date(str(value)) |
| 541 | except (ValueError, TypeError, OSError, OverflowError): |
| 542 | return None |
| 543 | return dt.strftime("%Y-%m-%d") if dt else None |
| 544 | |
| 545 | |
| 546 | def _extract_subreddit_name(value: Any) -> str: |
| 547 | """Extract subreddit name from string or API object dict.""" |
| 548 | if isinstance(value, dict): |
| 549 | for key in ("name", "display_name"): |
| 550 | text = _coerce_text(value.get(key)).strip() |
| 551 | if text: |
| 552 | return text |
| 553 | return "" |
| 554 | return _coerce_text(value).strip() |
| 555 | |
| 556 | |
| 557 | def _extract_score(post: Dict[str, Any]) -> int: |
| 558 | """Extract post score from either API schema. |
| 559 | |
| 560 | Global search uses ``votes``; subreddit search uses ``ups``/``score``. |
| 561 | """ |
| 562 | return _first_int(post.get("ups"), post.get("score"), post.get("votes"), default=0) |
| 563 | |
| 564 | |
| 565 | def _extract_date(post: Dict[str, Any]) -> Optional[str]: |
| 566 | """Extract date from either API schema. |
| 567 | |
| 568 | Global search uses ``created_at`` (ISO); subreddit search uses ``created_utc`` (Unix). |
| 569 | """ |
| 570 | for key in ("created_utc", "created_at", "created_at_iso"): |
| 571 | parsed = _parse_date(post.get(key)) |
| 572 | if parsed is not None: |
| 573 | return parsed |
| 574 | return None |
| 575 | |
| 576 | |
| 577 | def _normalize_reddit_id(raw_id: str) -> str: |
| 578 | """Strip Reddit fullname prefix (t3_) for consistent dedup.""" |
| 579 | s = _coerce_text(raw_id) |
| 580 | return s[3:] if s.startswith("t3_") else s |
| 581 | |
| 582 | |
| 583 | def _total_engagement(item: Dict[str, Any]) -> int: |
| 584 | """Combined engagement score: upvotes + comment count. |
| 585 | |
| 586 | Used for selecting which threads to enrich with comments. |
| 587 | Threads with lots of comments are high-value even if upvote score is low. |
| 588 | """ |
| 589 | eng = item.get("engagement") |
| 590 | if not isinstance(eng, dict): |
| 591 | return 0 |
| 592 | score = _coerce_int(eng.get("score"), default=0) |
| 593 | num_comments = _coerce_int(eng.get("num_comments"), default=0) |
| 594 | return score + num_comments |
| 595 | |
| 596 | |
| 597 | def _relevance_rank_key(item: Dict[str, Any]) -> float: |
| 598 | """Rank by relevance first, with a bounded engagement bonus as tiebreaker. |
| 599 | |
| 600 | The log-scaled bonus is capped at 0.25 so it orders similarly-relevant posts |
| 601 | by discussion volume but is too small to lift an off-topic post (relevance |
| 602 | ~0) above an on-topic one (relevance >= RELEVANCE_FLOOR). |
| 603 | """ |
| 604 | rel = item.get("relevance") or 0.0 |
| 605 | eng_bonus = min(0.25, math.log10(max(0, _total_engagement(item)) + 1) / 20.0) |
| 606 | return rel + eng_bonus |
| 607 | |
| 608 | |
| 609 | def _normalize_post(post: Dict[str, Any], idx: int, source_label: str = "global", query: str = "") -> Dict[str, Any]: |
| 610 | """Normalize a ScrapeCreators Reddit post to our internal format. |
| 611 | |
| 612 | Handles both the global-search schema (``votes``, ``created_at``, |
| 613 | ``subreddit`` as dict) and the subreddit-search schema (``ups``/``score``, |
| 614 | ``created_utc``, ``subreddit`` as string). |
| 615 | """ |
| 616 | raw_permalink = post.get("permalink") |
| 617 | permalink = raw_permalink if isinstance(raw_permalink, str) else "" |
| 618 | raw_url = post.get("url") |
| 619 | url = f"https://www.reddit.com{permalink}" if permalink else (raw_url if isinstance(raw_url, str) else "") |
| 620 | |
| 621 | # Ensure URL looks like a Reddit thread |
| 622 | if url and "reddit.com" not in url: |
| 623 | url = "" |
| 624 | |
| 625 | title = _coerce_text(post.get("title")).strip() |
| 626 | selftext = _coerce_text(post.get("selftext")) |
| 627 | |
| 628 | # Score the title first, then let the body provide limited support. |
| 629 | # This keeps long selftexts from overpowering the visible topic signal. |
| 630 | relevance = _compute_post_relevance(query, title, selftext) if query else 0.7 |
| 631 | |
| 632 | return { |
| 633 | "id": f"R{idx}", |
| 634 | "reddit_id": _normalize_reddit_id(post.get("id", "")), |
| 635 | "title": title, |
| 636 | "url": url, |
| 637 | "subreddit": _extract_subreddit_name(post.get("subreddit", "")), |
| 638 | "date": _extract_date(post), |
| 639 | "engagement": { |
| 640 | "score": _extract_score(post), |
| 641 | "num_comments": _coerce_int(post.get("num_comments"), default=0), |
| 642 | "upvote_ratio": _coerce_float(post.get("upvote_ratio")), |
| 643 | }, |
| 644 | "relevance": relevance, |
| 645 | "why_relevant": f"Reddit {source_label} search", |
| 646 | "selftext": selftext[:500], |
| 647 | } |
| 648 | |
| 649 | |
| 650 | def _compute_post_relevance(query: str, title: str, selftext: str) -> float: |
| 651 | """Compute Reddit relevance with title-first weighting. |
| 652 | |
| 653 | Title should carry most of the weight because it is the visible summary the |
| 654 | user sees. Selftext can lift a marginal match, but it should not rescue a |
| 655 | weak or ambiguous title into the top ranks. |
| 656 | """ |
| 657 | title_score = token_overlap_relevance(query, title) |
| 658 | if not selftext.strip(): |
| 659 | return title_score |
| 660 | |
| 661 | body_score = token_overlap_relevance(query, selftext) |
| 662 | support_score = max(title_score, body_score) |
| 663 | return round(0.75 * title_score + 0.25 * support_score, 2) |
| 664 | |
| 665 | |
| 666 | def _global_search( |
| 667 | query: str, |
| 668 | token: str, |
| 669 | sort: str = "relevance", |
| 670 | timeframe: str = "month", |
| 671 | *, |
| 672 | deadline_monotonic: float | None = None, |
| 673 | cancel: threading.Event | None = None, |
| 674 | ) -> List[Dict[str, Any]]: |
| 675 | """Search across all of Reddit via ScrapeCreators global search. |
| 676 | |
| 677 | Args: |
| 678 | query: Search query |
| 679 | token: ScrapeCreators API key |
| 680 | sort: Sort order (relevance, hot, top, new) |
| 681 | timeframe: Time filter (hour, day, week, month, year, all) |
| 682 | |
| 683 | Returns: |
| 684 | List of post dicts |
| 685 | """ |
| 686 | eff_deadline, eff_cancel = _check_sc_spend(deadline_monotonic, cancel) |
| 687 | extra: Dict[str, Any] = {} |
| 688 | if eff_deadline is not None: |
| 689 | extra["deadline_monotonic"] = eff_deadline |
| 690 | extra["owned_get"] = True |
| 691 | if eff_cancel is not None: |
| 692 | extra["cancel"] = eff_cancel |
| 693 | try: |
| 694 | with http.observe_dispatch(_mark_sc_paid_started): |
| 695 | data = http.get( |
| 696 | f"{_sc_base()}/search", |
| 697 | headers=http.scrapecreators_headers(token), |
| 698 | params={"query": query, "sort": sort, "timeframe": timeframe}, |
| 699 | timeout=30, |
| 700 | retries=2, |
| 701 | **extra, |
| 702 | ) |
| 703 | _mark_sc_paid_started() |
| 704 | return _extract_dict_list(data, "posts", context="global search") |
| 705 | except http.DeadlineExceeded as e: |
| 706 | if getattr(e, "dispatched", False): |
| 707 | _mark_sc_paid_started() |
| 708 | raise TimeoutError(_SC_STOPPED_MSG) from None |
| 709 | except http.HTTPError as e: |
| 710 | _mark_sc_paid_started() |
| 711 | if e.status_code in (401, 402, 403): |
| 712 | raise |
| 713 | _log(f"Global search error: {e}") |
| 714 | return [] |
| 715 | except Exception as e: |
| 716 | _mark_sc_paid_started() |
| 717 | if _sc_spend_stopped(deadline_monotonic, cancel): |
| 718 | raise TimeoutError(_SC_STOPPED_MSG) from None |
| 719 | _log(f"Global search error: {e}") |
| 720 | return [] |
| 721 | |
| 722 | |
| 723 | def _subreddit_search( |
| 724 | subreddit: str, |
| 725 | query: str, |
| 726 | token: str, |
| 727 | sort: str = "relevance", |
| 728 | timeframe: str = "month", |
| 729 | *, |
| 730 | deadline_monotonic: float | None = None, |
| 731 | cancel: threading.Event | None = None, |
| 732 | ) -> List[Dict[str, Any]]: |
| 733 | """Search within a specific subreddit via ScrapeCreators. |
| 734 | |
| 735 | Args: |
| 736 | subreddit: Subreddit name (without r/) |
| 737 | query: Search query |
| 738 | token: ScrapeCreators API key |
| 739 | sort: Sort order |
| 740 | timeframe: Time filter |
| 741 | |
| 742 | Returns: |
| 743 | List of post dicts |
| 744 | """ |
| 745 | eff_deadline, eff_cancel = _check_sc_spend(deadline_monotonic, cancel) |
| 746 | extra: Dict[str, Any] = {} |
| 747 | if eff_deadline is not None: |
| 748 | extra["deadline_monotonic"] = eff_deadline |
| 749 | extra["owned_get"] = True |
| 750 | if eff_cancel is not None: |
| 751 | extra["cancel"] = eff_cancel |
| 752 | try: |
| 753 | with http.observe_dispatch(_mark_sc_paid_started): |
| 754 | data = http.get( |
| 755 | f"{_sc_base()}/subreddit/search", |
| 756 | headers=http.scrapecreators_headers(token), |
| 757 | params={ |
| 758 | "subreddit": subreddit, |
| 759 | "query": query, |
| 760 | "sort": sort, |
| 761 | "timeframe": timeframe, |
| 762 | }, |
| 763 | timeout=30, |
| 764 | retries=2, |
| 765 | **extra, |
| 766 | ) |
| 767 | _mark_sc_paid_started() |
| 768 | return _extract_dict_list(data, "posts", context=f"subreddit search r/{subreddit}") |
| 769 | except http.DeadlineExceeded as e: |
| 770 | if getattr(e, "dispatched", False): |
| 771 | _mark_sc_paid_started() |
| 772 | raise TimeoutError(_SC_STOPPED_MSG) from None |
| 773 | except http.HTTPError as e: |
| 774 | _mark_sc_paid_started() |
| 775 | if e.status_code in (401, 402, 403): |
| 776 | raise |
| 777 | _log(f"Subreddit search error for r/{subreddit}: {e}") |
| 778 | return [] |
| 779 | except Exception as e: |
| 780 | _mark_sc_paid_started() |
| 781 | if _sc_spend_stopped(deadline_monotonic, cancel): |
| 782 | raise TimeoutError(_SC_STOPPED_MSG) from None |
| 783 | _log(f"Subreddit search error for r/{subreddit}: {e}") |
| 784 | return [] |
| 785 | |
| 786 | |
| 787 | def fetch_post_comments( |
| 788 | url: str, |
| 789 | token: str, |
| 790 | *, |
| 791 | deadline_monotonic: float | None = None, |
| 792 | cancel: threading.Event | None = None, |
| 793 | ) -> List[Dict[str, Any]]: |
| 794 | """Fetch comments for a Reddit post via ScrapeCreators. |
| 795 | |
| 796 | Args: |
| 797 | url: Reddit post URL or permalink |
| 798 | token: ScrapeCreators API key |
| 799 | |
| 800 | Returns: |
| 801 | List of comment dicts with score, author, body, etc. |
| 802 | """ |
| 803 | eff_deadline, eff_cancel = _check_sc_spend(deadline_monotonic, cancel) |
| 804 | try: |
| 805 | with http.observe_dispatch(_mark_sc_paid_started): |
| 806 | data = http.get( |
| 807 | f"{_sc_base()}/post/comments", |
| 808 | headers=http.scrapecreators_headers(token), |
| 809 | params={"url": url}, |
| 810 | timeout=30, |
| 811 | retries=2, |
| 812 | deadline_monotonic=eff_deadline, |
| 813 | cancel=eff_cancel, |
| 814 | owned_get=eff_deadline is not None, |
| 815 | ) |
| 816 | _mark_sc_paid_started() |
| 817 | return _extract_dict_list(data, "comments", context="comment fetch") |
| 818 | except http.DeadlineExceeded as e: |
| 819 | if getattr(e, "dispatched", False): |
| 820 | _mark_sc_paid_started() |
| 821 | raise TimeoutError(_SC_STOPPED_MSG) from None |
| 822 | except http.HTTPError as e: |
| 823 | _mark_sc_paid_started() |
| 824 | if e.status_code in (401, 402, 403): |
| 825 | raise |
| 826 | _log(f"Comment fetch error: {e}") |
| 827 | return [] |
| 828 | except Exception as e: |
| 829 | _mark_sc_paid_started() |
| 830 | if _sc_spend_stopped(deadline_monotonic, cancel): |
| 831 | raise TimeoutError(_SC_STOPPED_MSG) from None |
| 832 | _log(f"Comment fetch error: {e}") |
| 833 | return [] |
| 834 | |
| 835 | |
| 836 | def _dedupe_posts(posts: List[Dict[str, Any]]) -> List[Dict[str, Any]]: |
| 837 | """Deduplicate posts by reddit_id, keeping first occurrence.""" |
| 838 | seen_ids = set() |
| 839 | seen_urls = set() |
| 840 | unique = [] |
| 841 | for post in posts: |
| 842 | rid = post.get("reddit_id", "") |
| 843 | url = post.get("url", "") |
| 844 | if rid and rid in seen_ids: |
| 845 | continue |
| 846 | if url and url in seen_urls: |
| 847 | continue |
| 848 | if rid: |
| 849 | seen_ids.add(rid) |
| 850 | if url: |
| 851 | seen_urls.add(url) |
| 852 | unique.append(post) |
| 853 | return unique |
| 854 | |
| 855 | |
| 856 | def _days_to_reddit_bucket(days: float) -> str: |
| 857 | """Map a day count onto the smallest Reddit rolling bucket that covers it. |
| 858 | |
| 859 | Adds one day of slack so calendar windows that cross a day boundary still |
| 860 | fit inside Reddit's rolling ``t=`` buckets (a yesterday→today request needs |
| 861 | ``week``, not ``day``). |
| 862 | """ |
| 863 | covered = days + 1 |
| 864 | if covered <= 1: |
| 865 | return "day" |
| 866 | if covered <= 7: |
| 867 | return "week" |
| 868 | if covered <= 31: |
| 869 | return "month" |
| 870 | if covered <= 366: |
| 871 | return "year" |
| 872 | return "all" |
| 873 | |
| 874 | |
| 875 | def _window_to_time_filter(from_date: str, to_date: str) -> str: |
| 876 | """Map a requested YYYY-MM-DD window onto Reddit's coarse `t` param. |
| 877 | |
| 878 | Reddit's ``t=day|week|month`` buckets are rolling windows ending *now*, not |
| 879 | calendar spans and not anchored to ``to_date``. Coverage therefore needs: |
| 880 | |
| 881 | 1. Span — a yesterday→today request needs more than rolling ``t=day``. |
| 882 | 2. Historical reach — a one-day request ending two weeks ago still needs a |
| 883 | bucket that reaches ``from_date``; span-alone would pick ``week`` and |
| 884 | the API would omit the entire requested range. |
| 885 | |
| 886 | Take the wider of the two, independently of retrieval depth. |
| 887 | Phase 5 still trims to ``from_date``/``to_date``. Falls back to ``month`` |
| 888 | if the dates don't parse. |
| 889 | """ |
| 890 | try: |
| 891 | start = date.fromisoformat(from_date) |
| 892 | end = date.fromisoformat(to_date) |
| 893 | except (ValueError, TypeError): |
| 894 | return "month" |
| 895 | span_days = max(0, (end - start).days) |
| 896 | # Age of from_date relative to "today" — Reddit always anchors to now. |
| 897 | age_days = max(0, (datetime.now(timezone.utc).date() - start).days) |
| 898 | return _days_to_reddit_bucket(max(span_days, age_days)) |
| 899 | |
| 900 | |
| 901 | def search_reddit( |
| 902 | topic: str, |
| 903 | from_date: str, |
| 904 | to_date: str, |
| 905 | depth: str = "default", |
| 906 | token: str = None, |
| 907 | subreddits: List[str] | None = None, |
| 908 | *, |
| 909 | deadline_monotonic: float | None = None, |
| 910 | cancel: threading.Event | None = None, |
| 911 | ) -> Dict[str, Any]: |
| 912 | """Full Reddit search: multi-query global discovery + subreddit drill-down. |
| 913 | |
| 914 | This is the main v3 Reddit entry point. |
| 915 | |
| 916 | Args: |
| 917 | topic: Search topic |
| 918 | from_date: Start date (YYYY-MM-DD) |
| 919 | to_date: End date (YYYY-MM-DD) |
| 920 | depth: 'quick', 'default', or 'deep' |
| 921 | token: ScrapeCreators API key |
| 922 | subreddits: Optional list of subreddit names to search first (pre-resolved) |
| 923 | |
| 924 | Returns: |
| 925 | Dict with 'items' list and optional 'error'. |
| 926 | """ |
| 927 | if not token: |
| 928 | return {"items": [], "error": "No SCRAPECREATORS_API_KEY configured"} |
| 929 | |
| 930 | spend_ctx = ( |
| 931 | sc_spend_until(deadline=deadline_monotonic, cancel=cancel) |
| 932 | if (deadline_monotonic is not None or cancel is not None) |
| 933 | else contextlib.nullcontext() |
| 934 | ) |
| 935 | with spend_ctx: |
| 936 | _check_sc_spend() |
| 937 | config = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"]) |
| 938 | timeframe = _window_to_time_filter(from_date, to_date) |
| 939 | intent = infer_query_intent(topic) |
| 940 | |
| 941 | # === Phase 1: Query Expansion === |
| 942 | queries = expand_reddit_queries(topic, depth) |
| 943 | _log(f"Expanded '{topic}' into {len(queries)} queries: {queries}") |
| 944 | |
| 945 | core = _extract_core_subject(topic) |
| 946 | |
| 947 | outer_deadline, _ = _effective_spend_limit() |
| 948 | |
| 949 | # === Phase 1.5: Pre-resolved subreddit search (high-signal) === |
| 950 | all_raw_posts: List[Dict[str, Any]] = [] |
| 951 | all_items: List[Dict[str, Any]] = [] |
| 952 | search_incomplete = False |
| 953 | collected_any = False |
| 954 | if subreddits: |
| 955 | _check_sc_spend() |
| 956 | _log(f"Searching pre-resolved subreddits: {subreddits}") |
| 957 | batch_deadline = _search_batch_deadline(outer_deadline) |
| 958 | batch_ctx = ( |
| 959 | sc_spend_until(deadline=batch_deadline) |
| 960 | if batch_deadline is not None |
| 961 | else contextlib.nullcontext() |
| 962 | ) |
| 963 | with batch_ctx: |
| 964 | executor = ThreadPoolExecutor(max_workers=min(5, len(subreddits))) |
| 965 | completed_cleanly = False |
| 966 | try: |
| 967 | futures = {} |
| 968 | for sub in subreddits: |
| 969 | if _sc_spend_stopped(): |
| 970 | search_incomplete = True |
| 971 | break |
| 972 | futures[http.submit_with_context( |
| 973 | executor, _subreddit_search, sub, core, token, "relevance", timeframe, |
| 974 | )] = sub |
| 975 | batch_results, batch_incomplete = _collect_bounded(executor, futures) |
| 976 | for sub, sub_posts in batch_results: |
| 977 | sub_posts = _as_dict_list(sub_posts) |
| 978 | _log(f" -> {len(sub_posts)} results from pre-resolved r/{sub}") |
| 979 | for j, post in enumerate(sub_posts): |
| 980 | item = _normalize_post(post, len(all_items) + j + 1, f"r/{sub}", query=core) |
| 981 | all_items.append(item) |
| 982 | collected_any = True |
| 983 | if batch_incomplete: |
| 984 | search_incomplete = True |
| 985 | completed_cleanly = not search_incomplete |
| 986 | finally: |
| 987 | executor.shutdown(wait=completed_cleanly, cancel_futures=not completed_cleanly) |
| 988 | |
| 989 | if _sc_cancelled(): |
| 990 | raise TimeoutError(_SC_STOPPED_MSG) |
| 991 | |
| 992 | # === Phase 2: Global Discovery === |
| 993 | if not search_incomplete and _sc_spend_stopped(): |
| 994 | search_incomplete = True |
| 995 | if not search_incomplete: |
| 996 | max_global = config["global_searches"] |
| 997 | batch_deadline = _search_batch_deadline(outer_deadline) |
| 998 | batch_ctx = ( |
| 999 | sc_spend_until(deadline=batch_deadline) |
| 1000 | if batch_deadline is not None |
| 1001 | else contextlib.nullcontext() |
| 1002 | ) |
| 1003 | with batch_ctx: |
| 1004 | executor = ThreadPoolExecutor(max_workers=max_global or 1) |
| 1005 | completed_cleanly = False |
| 1006 | try: |
| 1007 | futures = {} |
| 1008 | for i, query in enumerate(queries[:max_global]): |
| 1009 | if _sc_spend_stopped(): |
| 1010 | search_incomplete = True |
| 1011 | break |
| 1012 | # Product/comparison queries: sort=top surfaces high-engagement posts |
| 1013 | # from relevant communities instead of keyword-matched noise. |
| 1014 | sort = "top" if intent in ("product", "comparison") else ("relevance" if i == 0 else "top") |
| 1015 | _log(f"Global search {i+1}/{max_global}: '{query}' (sort={sort})") |
| 1016 | futures[http.submit_with_context( |
| 1017 | executor, _global_search, query, token, sort, timeframe, |
| 1018 | )] = query |
| 1019 | batch_results, batch_incomplete = _collect_bounded(executor, futures) |
| 1020 | for query, posts in batch_results: |
| 1021 | posts = _as_dict_list(posts) |
| 1022 | _log(f" -> {len(posts)} results for '{query}'") |
| 1023 | all_raw_posts.extend(posts) |
| 1024 | if posts: |
| 1025 | collected_any = True |
| 1026 | if batch_incomplete: |
| 1027 | search_incomplete = True |
| 1028 | completed_cleanly = not search_incomplete |
| 1029 | finally: |
| 1030 | executor.shutdown(wait=completed_cleanly, cancel_futures=not completed_cleanly) |
| 1031 | |
| 1032 | # Normalize all posts (with query for relevance scoring) |
| 1033 | for i, post in enumerate(all_raw_posts): |
| 1034 | item = _normalize_post(post, i + 1, "global", query=core) |
| 1035 | all_items.append(item) |
| 1036 | |
| 1037 | if _sc_cancelled(): |
| 1038 | raise TimeoutError(_SC_STOPPED_MSG) |
| 1039 | |
| 1040 | # === Phase 3: Subreddit Discovery + Targeted Search === |
| 1041 | subreddit_budget = 0 if intent == "how_to" else config["subreddit_searches"] |
| 1042 | discovered_subs = discover_subreddits(all_raw_posts, topic=topic, max_subs=subreddit_budget) |
| 1043 | _log(f"Discovered subreddits: {discovered_subs}") |
| 1044 | |
| 1045 | subreddit_limit = subreddit_budget |
| 1046 | if subreddit_limit > 0 and discovered_subs: |
| 1047 | if search_incomplete or _sc_spend_stopped(): |
| 1048 | search_incomplete = True |
| 1049 | _log("Subreddit drill-down skipped at deadline; keeping already-fetched posts") |
| 1050 | else: |
| 1051 | batch_deadline = _search_batch_deadline(outer_deadline) |
| 1052 | batch_ctx = ( |
| 1053 | sc_spend_until(deadline=batch_deadline) |
| 1054 | if batch_deadline is not None |
| 1055 | else contextlib.nullcontext() |
| 1056 | ) |
| 1057 | with batch_ctx: |
| 1058 | executor = ThreadPoolExecutor(max_workers=subreddit_limit) |
| 1059 | completed_cleanly = False |
| 1060 | try: |
| 1061 | futures = {} |
| 1062 | for sub in discovered_subs[:subreddit_limit]: |
| 1063 | if _sc_spend_stopped(): |
| 1064 | search_incomplete = True |
| 1065 | break |
| 1066 | _log(f"Subreddit search: r/{sub} for '{core}'") |
| 1067 | futures[http.submit_with_context( |
| 1068 | executor, _subreddit_search, sub, core, token, "relevance", timeframe, |
| 1069 | )] = sub |
| 1070 | batch_results, batch_incomplete = _collect_bounded(executor, futures) |
| 1071 | for sub, sub_posts in batch_results: |
| 1072 | sub_posts = _as_dict_list(sub_posts) |
| 1073 | _log(f" -> {len(sub_posts)} results from r/{sub}") |
| 1074 | for j, post in enumerate(sub_posts): |
| 1075 | item = _normalize_post(post, len(all_items) + j + 1, f"r/{sub}", query=core) |
| 1076 | all_items.append(item) |
| 1077 | collected_any = True |
| 1078 | if batch_incomplete: |
| 1079 | search_incomplete = True |
| 1080 | completed_cleanly = not search_incomplete |
| 1081 | finally: |
| 1082 | executor.shutdown(wait=completed_cleanly, cancel_futures=not completed_cleanly) |
| 1083 | |
| 1084 | if _sc_cancelled(): |
| 1085 | raise TimeoutError(_SC_STOPPED_MSG) |
| 1086 | if search_incomplete and not collected_any: |
| 1087 | raise TimeoutError(_SC_STOPPED_MSG) |
| 1088 | |
| 1089 | # === Phase 4: Deduplicate === |
| 1090 | all_items = _dedupe_posts(all_items) |
| 1091 | _log(f"After dedup: {len(all_items)} unique posts") |
| 1092 | |
| 1093 | # === Phase 5: Date filter === |
| 1094 | in_range = [] |
| 1095 | out_of_range = 0 |
| 1096 | for item in all_items: |
| 1097 | if item["date"] and from_date <= item["date"] <= to_date: |
| 1098 | in_range.append(item) |
| 1099 | elif item["date"] is None: |
| 1100 | in_range.append(item) # Keep unknown dates |
| 1101 | else: |
| 1102 | out_of_range += 1 |
| 1103 | |
| 1104 | all_items = in_range |
| 1105 | if out_of_range: |
| 1106 | _log(f"Filtered {out_of_range} posts outside date range") |
| 1107 | |
| 1108 | # === Phase 6: Relevance floor + relevance-weighted ranking === |
| 1109 | # Drop the off-topic tail when enough on-topic posts remain. When too few clear |
| 1110 | # the soft floor, still strip zero-overlap posts (relevance exactly 0 = no |
| 1111 | # title/body token match at all, never on-topic) whenever anything relevant |
| 1112 | # remains, so viral high-upvote junk can't fill the section. Then rank by |
| 1113 | # relevance with a bounded engagement bonus (see RELEVANCE_FLOOR note above). |
| 1114 | before = len(all_items) |
| 1115 | on_topic = [it for it in all_items if (it.get("relevance") or 0) >= RELEVANCE_FLOOR] |
| 1116 | if len(on_topic) >= MIN_ON_TOPIC: |
| 1117 | all_items = on_topic |
| 1118 | else: |
| 1119 | nonzero = [it for it in all_items if (it.get("relevance") or 0) > 0] |
| 1120 | if nonzero: |
| 1121 | all_items = nonzero |
| 1122 | if len(all_items) < before: |
| 1123 | _log(f"Relevance floor dropped {before - len(all_items)} off-topic posts") |
| 1124 | all_items.sort(key=_relevance_rank_key, reverse=True) |
| 1125 | |
| 1126 | # Re-index IDs |
| 1127 | for i, item in enumerate(all_items): |
| 1128 | item["id"] = f"R{i+1}" |
| 1129 | |
| 1130 | _log(f"Final: {len(all_items)} Reddit posts") |
| 1131 | out: Dict[str, Any] = {"items": all_items} |
| 1132 | if search_incomplete: |
| 1133 | out["incomplete"] = True |
| 1134 | out["incomplete_note"] = _SC_SEARCH_INCOMPLETE_NOTE |
| 1135 | return out |
| 1136 | |
| 1137 | |
| 1138 | def enrich_with_comments( |
| 1139 | items: List[Dict[str, Any]], |
| 1140 | token: str, |
| 1141 | depth: str = "default", |
| 1142 | budget_seconds: int = 60, |
| 1143 | *, |
| 1144 | deadline_monotonic: float | None = None, |
| 1145 | cancel: threading.Event | None = None, |
| 1146 | _incomplete_out: Optional[List[bool]] = None, |
| 1147 | ) -> List[Dict[str, Any]]: |
| 1148 | """Enrich top items with comment data from ScrapeCreators. |
| 1149 | |
| 1150 | Args: |
| 1151 | items: Reddit items from search_reddit() |
| 1152 | token: ScrapeCreators API key |
| 1153 | depth: Depth for comment limit |
| 1154 | budget_seconds: Maximum total time for enrichment. If exceeded, |
| 1155 | returns items with whatever enrichment completed. Never discards items. |
| 1156 | |
| 1157 | Returns: |
| 1158 | Items with top_comments and comment_insights added. |
| 1159 | """ |
| 1160 | config = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"]) |
| 1161 | max_comments = config["comment_enrichments"] |
| 1162 | |
| 1163 | if not items or not token or max_comments <= 0 or budget_seconds <= 0: |
| 1164 | return items |
| 1165 | |
| 1166 | spend_ctx = ( |
| 1167 | sc_spend_until(deadline=deadline_monotonic, cancel=cancel) |
| 1168 | if (deadline_monotonic is not None or cancel is not None) |
| 1169 | else contextlib.nullcontext() |
| 1170 | ) |
| 1171 | with spend_ctx: |
| 1172 | outer_deadline, outer_cancels = _effective_spend_limit() |
| 1173 | if _sc_spend_stopped(): |
| 1174 | if _incomplete_out is not None: |
| 1175 | _incomplete_out.append(True) |
| 1176 | _log("Comment enrichment skipped: deadline reached or cancelled") |
| 1177 | return items |
| 1178 | |
| 1179 | # Select the top threads by total engagement (upvotes + comment count), |
| 1180 | # not by list position. This ensures high-comment threads like [FRESH ALBUM] |
| 1181 | # always get enriched even if their upvote score is low. |
| 1182 | ranked = sorted(items, key=_total_engagement, reverse=True) |
| 1183 | top_items = ranked[:max_comments] |
| 1184 | _log(f"Enriching comments for {len(top_items)} posts (by total engagement)") |
| 1185 | |
| 1186 | start = time.monotonic() |
| 1187 | deadline = start + budget_seconds |
| 1188 | if outer_deadline is not None: |
| 1189 | deadline = min(deadline, outer_deadline) |
| 1190 | local_cancel = threading.Event() |
| 1191 | |
| 1192 | def fetch(item): |
| 1193 | if local_cancel.is_set() or _sc_spend_stopped(deadline, local_cancel): |
| 1194 | return None |
| 1195 | comments = fetch_post_comments( |
| 1196 | item.get("url", ""), token, |
| 1197 | deadline_monotonic=deadline, cancel=local_cancel, |
| 1198 | ) |
| 1199 | return comments if not local_cancel.is_set() and time.monotonic() < deadline else None |
| 1200 | |
| 1201 | executor = ThreadPoolExecutor(max_workers=min(4, len(top_items))) |
| 1202 | abandoned = False |
| 1203 | not_done: set = set() |
| 1204 | try: |
| 1205 | with ExitStack() as cleanup: |
| 1206 | cleanup.callback(local_cancel.set) |
| 1207 | futures = {} |
| 1208 | for item in top_items: |
| 1209 | if not item.get("url"): |
| 1210 | continue |
| 1211 | if local_cancel.is_set() or _sc_spend_stopped(deadline, local_cancel): |
| 1212 | abandoned = True |
| 1213 | break |
| 1214 | futures[http.submit_with_context(executor, fetch, item)] = item |
| 1215 | |
| 1216 | done = set() |
| 1217 | not_done = set(futures) |
| 1218 | if not abandoned: |
| 1219 | if outer_deadline is None and not outer_cancels: |
| 1220 | remaining = max(0, budget_seconds - (time.monotonic() - start)) |
| 1221 | done, not_done = futures_wait(futures, timeout=remaining) |
| 1222 | else: |
| 1223 | while not_done: |
| 1224 | if _sc_spend_stopped(): |
| 1225 | abandoned = True |
| 1226 | break |
| 1227 | rem = deadline - time.monotonic() |
| 1228 | if rem <= 0: |
| 1229 | if outer_deadline is not None and time.monotonic() >= outer_deadline: |
| 1230 | abandoned = True |
| 1231 | break |
| 1232 | completed, not_done = futures_wait( |
| 1233 | not_done, timeout=min(0.1, rem), return_when=FIRST_COMPLETED, |
| 1234 | ) |
| 1235 | done.update(completed) |
| 1236 | |
| 1237 | if not_done or abandoned: |
| 1238 | local_cancel.set() |
| 1239 | for future in not_done: |
| 1240 | future.cancel() |
| 1241 | if _incomplete_out is not None: |
| 1242 | _incomplete_out.append(True) |
| 1243 | |
| 1244 | enriched_count = 0 |
| 1245 | for future in done: |
| 1246 | item = futures[future] |
| 1247 | try: |
| 1248 | raw_comments = future.result(timeout=0) |
| 1249 | except Exception: |
| 1250 | continue |
| 1251 | raw_comments = _as_dict_list(raw_comments) |
| 1252 | if not raw_comments: |
| 1253 | continue |
| 1254 | |
| 1255 | top_comments = [] |
| 1256 | insights = [] |
| 1257 | |
| 1258 | for ci, c in enumerate(raw_comments[:10]): |
| 1259 | body = _coerce_text(c.get("body")) |
| 1260 | if not body or body in ("[deleted]", "[removed]"): |
| 1261 | continue |
| 1262 | |
| 1263 | score = _first_int(c.get("ups"), c.get("score"), default=0) |
| 1264 | author = _coerce_text(c.get("author")) or "[deleted]" |
| 1265 | raw_permalink = c.get("permalink") |
| 1266 | permalink = raw_permalink if isinstance(raw_permalink, str) else "" |
| 1267 | comment_url = f"https://reddit.com{permalink}" if permalink else "" |
| 1268 | |
| 1269 | top_comments.append({ |
| 1270 | "score": score, |
| 1271 | "date": _parse_date(c.get("created_utc")), |
| 1272 | "author": author, |
| 1273 | "excerpt": snippet.cut_quote(body), |
| 1274 | "url": comment_url, |
| 1275 | # The thread's own poster, when the payload says so. |
| 1276 | **( |
| 1277 | {"is_uploader": c["is_submitter"]} |
| 1278 | if isinstance(c.get("is_submitter"), bool) |
| 1279 | else {} |
| 1280 | ), |
| 1281 | }) |
| 1282 | |
| 1283 | if len(body) >= 30 and author not in ("[deleted]", "[removed]", "AutoModerator"): |
| 1284 | insight = body[:150] |
| 1285 | if len(body) > 150: |
| 1286 | for i, char in enumerate(insight): |
| 1287 | if char in '.!?' and i > 50: |
| 1288 | insight = insight[:i+1] |
| 1289 | break |
| 1290 | else: |
| 1291 | insight = insight.rstrip() + "..." |
| 1292 | insights.append(insight) |
| 1293 | |
| 1294 | top_comments.sort(key=lambda c: _coerce_int(c.get("score"), default=0), reverse=True) |
| 1295 | item["top_comments"] = top_comments[:10] |
| 1296 | item["comment_insights"] = insights[:10] |
| 1297 | enriched_count += 1 |
| 1298 | |
| 1299 | if not_done or abandoned: |
| 1300 | _log(f"Enrichment budget hit ({budget_seconds}s): {enriched_count}/{len(futures)} posts enriched, {len(not_done)} skipped") |
| 1301 | else: |
| 1302 | elapsed = time.monotonic() - start |
| 1303 | _log(f"Enriched {enriched_count}/{len(futures)} posts in {elapsed:.1f}s") |
| 1304 | finally: |
| 1305 | executor.shutdown(wait=not abandoned and not bool(not_done), cancel_futures=abandoned or bool(not_done)) |
| 1306 | |
| 1307 | return items |
| 1308 | |
| 1309 | |
| 1310 | def search_and_enrich( |
| 1311 | topic: str, |
| 1312 | from_date: str, |
| 1313 | to_date: str, |
| 1314 | depth: str = "default", |
| 1315 | token: str = None, |
| 1316 | subreddits: List[str] | None = None, |
| 1317 | *, |
| 1318 | deadline_monotonic: float | None = None, |
| 1319 | cancel: threading.Event | None = None, |
| 1320 | ) -> Dict[str, Any]: |
| 1321 | """Full Reddit pipeline: search + comment enrichment. |
| 1322 | |
| 1323 | This is the convenience function that does everything. |
| 1324 | |
| 1325 | Args: |
| 1326 | topic: Search topic |
| 1327 | from_date: Start date (YYYY-MM-DD) |
| 1328 | to_date: End date (YYYY-MM-DD) |
| 1329 | depth: 'quick', 'default', or 'deep' |
| 1330 | token: ScrapeCreators API key |
| 1331 | subreddits: Optional list of subreddit names to search first (pre-resolved) |
| 1332 | |
| 1333 | Returns: |
| 1334 | Dict with 'items' list. Items include top_comments and comment_insights. |
| 1335 | """ |
| 1336 | spend_ctx = ( |
| 1337 | sc_spend_until(deadline=deadline_monotonic, cancel=cancel) |
| 1338 | if (deadline_monotonic is not None or cancel is not None) |
| 1339 | else contextlib.nullcontext() |
| 1340 | ) |
| 1341 | with spend_ctx: |
| 1342 | _check_sc_spend() |
| 1343 | result = search_reddit(topic, from_date, to_date, depth, token, subreddits=subreddits) |
| 1344 | items = result.get("items", []) |
| 1345 | |
| 1346 | if items and token: |
| 1347 | eff_deadline, cancels = _effective_spend_limit() |
| 1348 | comment_deadline: float | None = None |
| 1349 | skip_comments = bool(result.get("incomplete")) or _sc_spend_stopped() |
| 1350 | if not skip_comments and eff_deadline is not None: |
| 1351 | # Reserve a return margin so already-paid posts make it back |
| 1352 | # before the outer backfill wait gives up on the worker. |
| 1353 | rem = eff_deadline - time.monotonic() |
| 1354 | reserve = min(2.0, max(0.0, rem * 0.2)) |
| 1355 | comment_deadline = eff_deadline - reserve |
| 1356 | if comment_deadline <= time.monotonic(): |
| 1357 | skip_comments = True |
| 1358 | if skip_comments: |
| 1359 | result["comments_incomplete"] = True |
| 1360 | result["comments_note"] = _SC_COMMENTS_INCOMPLETE_NOTE |
| 1361 | else: |
| 1362 | incomplete_flag: list[bool] = [] |
| 1363 | try: |
| 1364 | if eff_deadline is not None or cancels: |
| 1365 | items = enrich_with_comments( |
| 1366 | items, |
| 1367 | token, |
| 1368 | depth, |
| 1369 | deadline_monotonic=comment_deadline, |
| 1370 | _incomplete_out=incomplete_flag, |
| 1371 | ) |
| 1372 | else: |
| 1373 | items = enrich_with_comments(items, token, depth) |
| 1374 | result["items"] = items |
| 1375 | if incomplete_flag: |
| 1376 | result["comments_incomplete"] = True |
| 1377 | result["comments_note"] = _SC_COMMENTS_INCOMPLETE_NOTE |
| 1378 | except TimeoutError: |
| 1379 | result["items"] = items |
| 1380 | result["comments_incomplete"] = True |
| 1381 | result["comments_note"] = _SC_COMMENTS_INCOMPLETE_NOTE |
| 1382 | |
| 1383 | return result |
| 1384 | |
| 1385 | |
| 1386 | # Run-scoped memo for the paid ScrapeCreators Reddit call (R9). All subquery |
| 1387 | # streams share the raw topic, and the thin-source retry repeats it, so without |
| 1388 | # this one run could pay for the same query five times. Concurrent callers for |
| 1389 | # one key wait on the first call; results AND failures are kept until the |
| 1390 | # per-command reset, so a failed backfill is never retried within the run. |
| 1391 | _SC_MEMO: Dict[tuple, tuple] = {} |
| 1392 | _SC_INFLIGHT: Dict[tuple, threading.Event] = {} |
| 1393 | _SC_MEMO_LOCK = threading.Lock() |
| 1394 | |
| 1395 | |
| 1396 | def reset_scrapecreators_memo() -> None: |
| 1397 | """Forget memoized ScrapeCreators Reddit calls. Called once per command, and by tests.""" |
| 1398 | with _SC_MEMO_LOCK: |
| 1399 | _SC_MEMO.clear() |
| 1400 | _SC_INFLIGHT.clear() |
| 1401 | |
| 1402 | |
| 1403 | def _sc_memo_outcome(entry: tuple, replay_failures: bool = True) -> Dict[str, Any]: |
| 1404 | ok, value, failures = entry |
| 1405 | if replay_failures: |
| 1406 | # search_and_enrich swallows ScrapeCreators HTTP errors into the |
| 1407 | # caller's failure sink; a later caller must see them too, or an |
| 1408 | # empty cached result reads as a clean no-results. |
| 1409 | for failure in failures: |
| 1410 | http._record_failure(failure) |
| 1411 | if not ok: |
| 1412 | raise value |
| 1413 | # Each caller gets its own copy so one stream cannot mutate another's items. |
| 1414 | return copy.deepcopy(value) |
| 1415 | |
| 1416 | |
| 1417 | def search_and_enrich_memo( |
| 1418 | topic: str, |
| 1419 | from_date: str, |
| 1420 | to_date: str, |
| 1421 | depth: str = "default", |
| 1422 | token: str = None, |
| 1423 | subreddits: List[str] | None = None, |
| 1424 | *, |
| 1425 | deadline_monotonic: float | None = None, |
| 1426 | cancel: threading.Event | None = None, |
| 1427 | ) -> Dict[str, Any]: |
| 1428 | """:func:`search_and_enrich`, at most once per key per command. |
| 1429 | |
| 1430 | Keyed by query, date window, depth, and sorted subreddits. |
| 1431 | """ |
| 1432 | spend_ctx = ( |
| 1433 | sc_spend_until(deadline=deadline_monotonic, cancel=cancel) |
| 1434 | if (deadline_monotonic is not None or cancel is not None) |
| 1435 | else contextlib.nullcontext() |
| 1436 | ) |
| 1437 | with spend_ctx: |
| 1438 | eff_deadline, cancels = _effective_spend_limit() |
| 1439 | key = (topic, from_date, to_date, depth, tuple(sorted(subreddits or ()))) |
| 1440 | while True: |
| 1441 | with _SC_MEMO_LOCK: |
| 1442 | entry = _SC_MEMO.get(key) |
| 1443 | if entry is None: |
| 1444 | if _sc_spend_stopped(): |
| 1445 | raise TimeoutError(_SC_STOPPED_MSG) |
| 1446 | gate = _SC_INFLIGHT.get(key) |
| 1447 | owner = gate is None |
| 1448 | if owner: |
| 1449 | gate = threading.Event() |
| 1450 | _SC_INFLIGHT[key] = gate |
| 1451 | if entry is not None: |
| 1452 | return _sc_memo_outcome(entry) |
| 1453 | if owner: |
| 1454 | break |
| 1455 | if eff_deadline is None and not cancels: |
| 1456 | gate.wait() |
| 1457 | else: |
| 1458 | while not gate.wait(timeout=0.1): |
| 1459 | _check_sc_spend() |
| 1460 | # Loop: read the owner's cached outcome, or re-elect if it was |
| 1461 | # interrupted before caching one (e.g. KeyboardInterrupt or cancel). |
| 1462 | paid_flag = [False] |
| 1463 | paid_token = _sc_paid_started.set(paid_flag) |
| 1464 | cancelled_before_spend = False |
| 1465 | try: |
| 1466 | with http.tee_failures() as recorded: |
| 1467 | try: |
| 1468 | result = search_and_enrich( |
| 1469 | topic, from_date, to_date, depth=depth, token=token, |
| 1470 | subreddits=subreddits, |
| 1471 | ) |
| 1472 | outcome = (True, result) |
| 1473 | except TimeoutError as exc: |
| 1474 | if not paid_flag[0]: |
| 1475 | cancelled_before_spend = True |
| 1476 | outcome = (False, exc) |
| 1477 | except Exception as exc: |
| 1478 | if _sc_spend_stopped() and not paid_flag[0]: |
| 1479 | cancelled_before_spend = True |
| 1480 | outcome = (False, exc) |
| 1481 | entry = (*outcome, list(recorded)) |
| 1482 | if not cancelled_before_spend: |
| 1483 | with _SC_MEMO_LOCK: |
| 1484 | _SC_MEMO[key] = entry |
| 1485 | finally: |
| 1486 | _sc_paid_started.reset(paid_token) |
| 1487 | with _SC_MEMO_LOCK: |
| 1488 | _SC_INFLIGHT.pop(key, None) |
| 1489 | gate.set() |
| 1490 | # The owner's failures already reached its own sink through tee_failures. |
| 1491 | return _sc_memo_outcome(entry, replay_failures=False) |
| 1492 | |
| 1493 | |
| 1494 | def parse_reddit_response(response: Dict[str, Any]) -> List[Dict[str, Any]]: |
| 1495 | """Parse ScrapeCreators response to item list. |
| 1496 | |
| 1497 | Parse raw Reddit search output into the generic item shape. |
| 1498 | """ |
| 1499 | if not isinstance(response, dict): |
| 1500 | return [] |
| 1501 | return _as_dict_list(response.get("items")) |
| 1502 |