| 1 | """TikTok / Instagram keyless-ish fallback: web discovery + yt-dlp extract. |
| 2 | |
| 3 | ScrapeCreators owns keyword search. When that key is missing or 402s, this |
| 4 | module finds public post URLs via the already-configured web backends, then |
| 5 | extracts metadata with yt-dlp (already on PATH for YouTube). |
| 6 | |
| 7 | Discovery never uses Google ``site:`` — Serper's free tier 400s that pattern. |
| 8 | Discovery asks each web backend for recent results (see ``_freshness_on``). |
| 9 | Post dates are decoded from TikTok ids and Instagram shortcodes so stale URLs |
| 10 | are dropped before any yt-dlp call; yt-dlp's own timestamp is the final |
| 11 | filter. Out-of-window posts are never kept: an empty window returns zero. |
| 12 | |
| 13 | ponytail: no hashtag/user listing for IG (yt-dlp extractors are broken); |
| 14 | TikTok ``@user`` listing still works and is used for ``creators=``. |
| 15 | """ |
| 16 | |
| 17 | from __future__ import annotations |
| 18 | |
| 19 | import concurrent.futures |
| 20 | import json |
| 21 | import os |
| 22 | import re |
| 23 | import threading |
| 24 | import time |
| 25 | from datetime import date, datetime, timedelta, timezone |
| 26 | from typing import Any, Dict, List, Optional, Tuple |
| 27 | from urllib.parse import unquote |
| 28 | |
| 29 | from . import dates, http, log, subproc, web_search_keyless, youtube_yt |
| 30 | from .relevance import RELEVANCE_FLOOR |
| 31 | from .relevance import token_overlap_relevance as _compute_relevance |
| 32 | |
| 33 | _TT_RE = re.compile( |
| 34 | r"https?://(?:www\.)?tiktok\.com/@([\w.\-]+)/video/(\d+)", re.I |
| 35 | ) |
| 36 | _IG_RE = re.compile( |
| 37 | r"https?://(?:www\.)?instagram\.com/(?:reel|p|reels)/([\w\-]+)", re.I |
| 38 | ) |
| 39 | _HASHTAG_RE = re.compile(r"#(\w+)") |
| 40 | |
| 41 | _DEPTH_URLS = {"quick": 8, "default": 12, "deep": 20} |
| 42 | _ENRICH_TIMEOUT = 180 |
| 43 | # Extraction runs one yt-dlp per post (this many at a time), so a stalled |
| 44 | # post loses only itself. |
| 45 | _ENRICH_BATCH = 1 |
| 46 | _ENRICH_WORKERS = 4 |
| 47 | |
| 48 | # TikTok creator expansion: (creators listed, videos listed per creator). |
| 49 | _DEPTH_CREATORS = {"quick": (3, 5), "default": (5, 8), "deep": (8, 12)} |
| 50 | # A creator listing reads this many times the kept count, then keeps the most viewed. |
| 51 | _CREATOR_LIST_FACTOR = 3 |
| 52 | |
| 53 | # Discovery freshness. LAST30DAYS_SHORTFORM_FRESHNESS (env or config): |
| 54 | # "on" (default) asks every backend for recent results, |
| 55 | # "off" sends the unfiltered requests, |
| 56 | # a comma list (e.g. "serper,exa") turns it on for those backends only. |
| 57 | # Backends: serper (tbs=qdr:m), brave (freshness=pm), exa (startPublishedDate |
| 58 | # = window start), searxng (time_range=month). Brave cards often lack |
| 59 | # page_age, so each switch exists to A/B the recall cost per backend. |
| 60 | FRESHNESS_ENV = "LAST30DAYS_SHORTFORM_FRESHNESS" |
| 61 | |
| 62 | # TikTok creator expansion. LAST30DAYS_SHORTFORM_CREATOR_EXPANSION (env or |
| 63 | # config): "on" (default) or "off", so the A/B harness can measure its lift. |
| 64 | EXPANSION_ENV = "LAST30DAYS_SHORTFORM_CREATOR_EXPANSION" |
| 65 | |
| 66 | # Instagram media ids carry milliseconds since this epoch in their top bits. |
| 67 | _IG_EPOCH_MS = 1314220021721 |
| 68 | _IG_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" |
| 69 | # Ids that decode before 2016 are not plausible post dates. |
| 70 | _MIN_ID_TS = datetime(2016, 1, 1, tzinfo=timezone.utc).timestamp() |
| 71 | |
| 72 | |
| 73 | def _stopped(deadline: float | None, cancel: threading.Event | None) -> bool: |
| 74 | """True once the run is cancelled or past its shared monotonic deadline.""" |
| 75 | if cancel is not None and cancel.is_set(): |
| 76 | return True |
| 77 | return deadline is not None and time.monotonic() >= deadline |
| 78 | |
| 79 | |
| 80 | def _bounded_timeout(base: float, deadline: float | None) -> float: |
| 81 | """Per-call timeout, never longer than the deadline's remaining time.""" |
| 82 | if deadline is None: |
| 83 | return base |
| 84 | return max(1.0, min(base, deadline - time.monotonic())) |
| 85 | |
| 86 | |
| 87 | # Relative filters ("past month") fit only a window that ends about today |
| 88 | # and spans no more than a month. |
| 89 | _RELATIVE_FRESHNESS_SLACK_DAYS = 2 |
| 90 | _RELATIVE_FRESHNESS_MAX_DAYS = 31 |
| 91 | |
| 92 | |
| 93 | def _window_is_current(from_date: str | None, to_date: str | None) -> bool: |
| 94 | """True when "past month" from today covers the whole window.""" |
| 95 | if not to_date: |
| 96 | return True |
| 97 | today = datetime.now(timezone.utc).date() |
| 98 | try: |
| 99 | end = date.fromisoformat(to_date) |
| 100 | start = date.fromisoformat(from_date) if from_date else end |
| 101 | except ValueError: |
| 102 | return True |
| 103 | if end < today - timedelta(days=_RELATIVE_FRESHNESS_SLACK_DAYS): |
| 104 | return False |
| 105 | return (today - start).days <= _RELATIVE_FRESHNESS_MAX_DAYS |
| 106 | |
| 107 | |
| 108 | def _freshness_on(backend: str, config: Dict[str, Any] | None = None) -> bool: |
| 109 | """True when discovery should ask ``backend`` for recent results.""" |
| 110 | raw = (config or {}).get(FRESHNESS_ENV) or os.environ.get(FRESHNESS_ENV) or "on" |
| 111 | value = str(raw).strip().lower() |
| 112 | if value in ("on", "1", "true", "yes"): |
| 113 | return True |
| 114 | if value in ("off", "0", "false", "no"): |
| 115 | return False |
| 116 | return backend in {part.strip() for part in value.split(",")} |
| 117 | |
| 118 | |
| 119 | def _switch_on(name: str, config: Dict[str, Any] | None = None) -> bool: |
| 120 | raw = (config or {}).get(name) or os.environ.get(name) or "on" |
| 121 | return str(raw).strip().lower() not in ("off", "0", "false", "no") |
| 122 | |
| 123 | |
| 124 | def _expansion_on(config: Dict[str, Any] | None = None) -> bool: |
| 125 | """True unless creator expansion is switched off.""" |
| 126 | return _switch_on(EXPANSION_ENV, config) |
| 127 | |
| 128 | |
| 129 | def post_timestamp_from_url(kind: str, url: str) -> Optional[float]: |
| 130 | """Unix seconds decoded from a post URL's id, or None when undecodable. |
| 131 | |
| 132 | TikTok: the video id's top 32 bits are the upload time in seconds. |
| 133 | Instagram: the shortcode is a base64 media id whose top bits |
| 134 | (``id >> 23``) are milliseconds since ``_IG_EPOCH_MS``. |
| 135 | """ |
| 136 | if kind == "tiktok": |
| 137 | m = _TT_RE.search(url or "") |
| 138 | if not m: |
| 139 | return None |
| 140 | ts = float(int(m.group(2)) >> 32) |
| 141 | elif kind == "instagram": |
| 142 | m = _IG_RE.search(url or "") |
| 143 | code = m.group(1) if m else "" |
| 144 | if not code or len(code) > 11: |
| 145 | return None |
| 146 | media_id = 0 |
| 147 | for ch in code: |
| 148 | idx = _IG_ALPHABET.find(ch) |
| 149 | if idx < 0: |
| 150 | return None |
| 151 | media_id = media_id * 64 + idx |
| 152 | ts = ((media_id >> 23) + _IG_EPOCH_MS) / 1000.0 |
| 153 | else: |
| 154 | return None |
| 155 | if ts < _MIN_ID_TS or ts > time.time() + 2 * 86400: |
| 156 | return None |
| 157 | return ts |
| 158 | |
| 159 | |
| 160 | def post_date_from_url(kind: str, url: str) -> Optional[str]: |
| 161 | """UTC ``YYYY-MM-DD`` decoded from a post URL's id, or None.""" |
| 162 | ts = post_timestamp_from_url(kind, url) |
| 163 | if ts is None: |
| 164 | return None |
| 165 | return datetime.fromtimestamp(ts, timezone.utc).strftime("%Y-%m-%d") |
| 166 | |
| 167 | |
| 168 | def _outside_window(kind: str, url: str, from_date: str, to_date: str) -> bool: |
| 169 | """True only when the id decodes to a date clearly outside the window. |
| 170 | |
| 171 | One day of slack on each side covers timezone and post-vs-upload skew; |
| 172 | yt-dlp's timestamp applies the exact window after hydration. |
| 173 | """ |
| 174 | day = post_date_from_url(kind, url) |
| 175 | if day is None: |
| 176 | return False |
| 177 | d = date.fromisoformat(day) |
| 178 | return (d < date.fromisoformat(from_date) - timedelta(days=1) |
| 179 | or d > date.fromisoformat(to_date) + timedelta(days=1)) |
| 180 | |
| 181 | |
| 182 | def _log(kind: str, msg: str) -> None: |
| 183 | log.source_log("TikTok" if kind == "tiktok" else "Instagram", msg, tty_only=False) |
| 184 | |
| 185 | |
| 186 | def normalize_post_url(kind: str, url: str) -> Optional[str]: |
| 187 | """Canonicalize a TikTok video / IG reel URL, or None if not a post.""" |
| 188 | if not url: |
| 189 | return None |
| 190 | url = unquote(url.split("#")[0].split("?")[0]).replace("%40", "@") |
| 191 | if kind == "tiktok": |
| 192 | m = _TT_RE.search(url) |
| 193 | if not m: |
| 194 | return None |
| 195 | return f"https://www.tiktok.com/@{m.group(1)}/video/{m.group(2)}" |
| 196 | m = _IG_RE.search(url) |
| 197 | if not m: |
| 198 | return None |
| 199 | return f"https://www.instagram.com/reel/{m.group(1)}/" |
| 200 | |
| 201 | |
| 202 | def discovery_query(kind: str, topic: str) -> str: |
| 203 | """Plain-language query. Do not add ``site:`` — Serper free accounts reject it.""" |
| 204 | topic = (topic or "").strip() |
| 205 | if kind == "tiktok": |
| 206 | return f"{topic} tiktok video" |
| 207 | return f"{topic} instagram reel" |
| 208 | |
| 209 | |
| 210 | def _collect(kind: str, raw_urls, dest: List[str], limit: int) -> bool: |
| 211 | for raw in raw_urls: |
| 212 | n = normalize_post_url(kind, raw or "") |
| 213 | if n and n not in dest: |
| 214 | dest.append(n) |
| 215 | if len(dest) >= limit: |
| 216 | return True |
| 217 | return False |
| 218 | |
| 219 | |
| 220 | def _serper_links( |
| 221 | query: str, api_key: str, count: int, deadline: float | None = None, |
| 222 | fresh: bool = False, cancel: threading.Event | None = None, |
| 223 | ) -> List[str]: |
| 224 | body: Dict[str, Any] = {"q": query, "num": min(20, max(count, 10))} |
| 225 | if fresh: |
| 226 | body["tbs"] = "qdr:m" |
| 227 | data = http.request( |
| 228 | "POST", |
| 229 | "https://google.serper.dev/search", |
| 230 | headers={"X-API-KEY": api_key}, |
| 231 | json_data=body, |
| 232 | timeout=_bounded_timeout(15.0, deadline), |
| 233 | deadline_monotonic=deadline, cancel=cancel, |
| 234 | retries=1, |
| 235 | ) |
| 236 | return [r.get("link", "") for r in (data.get("organic") or []) if isinstance(r, dict)] |
| 237 | |
| 238 | |
| 239 | def _exa_links( |
| 240 | query: str, api_key: str, domain: str, count: int, deadline: float | None = None, |
| 241 | start_date: str | None = None, |
| 242 | end_date: str | None = None, |
| 243 | cancel: threading.Event | None = None, |
| 244 | ) -> List[str]: |
| 245 | body: Dict[str, Any] = { |
| 246 | "query": query, |
| 247 | "numResults": count, |
| 248 | "includeDomains": [domain], |
| 249 | "contents": {"text": False}, |
| 250 | } |
| 251 | if start_date: |
| 252 | body["startPublishedDate"] = f"{start_date}T00:00:00.000Z" |
| 253 | if end_date: |
| 254 | body["endPublishedDate"] = f"{end_date}T23:59:59.999Z" |
| 255 | data = http.request( |
| 256 | "POST", |
| 257 | "https://api.exa.ai/search", |
| 258 | headers={"x-api-key": api_key}, |
| 259 | json_data=body, |
| 260 | timeout=_bounded_timeout(20.0, deadline), |
| 261 | deadline_monotonic=deadline, cancel=cancel, |
| 262 | retries=1, |
| 263 | ) |
| 264 | return [r.get("url", "") for r in (data.get("results") or []) if isinstance(r, dict)] |
| 265 | |
| 266 | |
| 267 | def _brave_links( |
| 268 | query: str, api_key: str, count: int, fresh: bool = False, |
| 269 | deadline: float | None = None, cancel: threading.Event | None = None, |
| 270 | ) -> List[str]: |
| 271 | from . import grounding |
| 272 | |
| 273 | # Wide date window for the result filter: social cards often lack |
| 274 | # page_age and would otherwise drop. ``fresh`` only shapes the request. |
| 275 | items, _art = grounding.brave_search( |
| 276 | query, ("1970-01-01", "2099-12-31"), api_key, count=count, |
| 277 | freshness="pm" if fresh else None, |
| 278 | deadline_monotonic=deadline, cancel=cancel, |
| 279 | ) |
| 280 | return [i.get("url", "") for i in items] |
| 281 | |
| 282 | |
| 283 | def discover_urls( |
| 284 | kind: str, |
| 285 | query: str, |
| 286 | config: Dict[str, Any], |
| 287 | count: int, |
| 288 | deadline: float | None = None, |
| 289 | cancel: threading.Event | None = None, |
| 290 | from_date: str | None = None, |
| 291 | to_date: str | None = None, |
| 292 | ) -> Tuple[List[str], str]: |
| 293 | """Return (post_urls, backend_name). Never raises; stops at deadline/cancel. |
| 294 | |
| 295 | ``from_date``/``to_date`` bound Exa's published-date filter. The relative |
| 296 | "past month" filters (SearXNG, Serper, Brave) count back from today, so |
| 297 | they are sent only when the window ends about today and spans at most a |
| 298 | month; a historical (``--as-of``) or longer window relies on the id-date |
| 299 | filter instead. |
| 300 | """ |
| 301 | urls: List[str] = [] |
| 302 | current = _window_is_current(from_date, to_date) |
| 303 | |
| 304 | def relative(backend: str) -> bool: |
| 305 | return current and _freshness_on(backend, config) |
| 306 | |
| 307 | used = "none" |
| 308 | q = discovery_query(kind, query) |
| 309 | |
| 310 | searxng = (config.get("LAST30DAYS_SEARXNG_URL") or "").strip() |
| 311 | if searxng and not _stopped(deadline, cancel): |
| 312 | try: |
| 313 | items = web_search_keyless._search_searxng( |
| 314 | q, count, searxng, |
| 315 | time_range="month" if relative("searxng") else None, |
| 316 | deadline_monotonic=deadline, |
| 317 | ) |
| 318 | if _collect(kind, (i.get("url", "") for i in items), urls, count): |
| 319 | return urls, "searxng" |
| 320 | if urls: |
| 321 | used = "searxng" |
| 322 | except Exception as e: |
| 323 | _log(kind, f"SearXNG discovery error: {e}") |
| 324 | |
| 325 | # Serper/Exa/Brave are paid rungs here, not the first choice: Serper's |
| 326 | # free tier rejects ``site:`` filters, Exa returns 0 Instagram posts, and |
| 327 | # Brave HTML 429s under load. They run only when the rungs above returned |
| 328 | # nothing. |
| 329 | |
| 330 | if not urls and not _stopped(deadline, cancel) and config.get("SERPER_API_KEY"): |
| 331 | try: |
| 332 | if _collect( |
| 333 | kind, |
| 334 | _serper_links( |
| 335 | q, config["SERPER_API_KEY"], count, deadline=deadline, |
| 336 | fresh=relative("serper"), cancel=cancel, |
| 337 | ), |
| 338 | urls, |
| 339 | count, |
| 340 | ): |
| 341 | return urls, "serper" |
| 342 | if urls: |
| 343 | used = "serper" |
| 344 | except Exception as e: |
| 345 | _log(kind, f"Serper discovery error: {e}") |
| 346 | |
| 347 | if not urls and not _stopped(deadline, cancel) and kind == "tiktok" and config.get("EXA_API_KEY"): |
| 348 | try: |
| 349 | if _collect( |
| 350 | kind, |
| 351 | _exa_links( |
| 352 | q, config["EXA_API_KEY"], "tiktok.com", count, deadline=deadline, |
| 353 | start_date=from_date if _freshness_on("exa", config) else None, |
| 354 | end_date=None if current or not _freshness_on("exa", config) else to_date, |
| 355 | cancel=cancel, |
| 356 | ), |
| 357 | urls, |
| 358 | count, |
| 359 | ): |
| 360 | return urls, "exa" |
| 361 | if urls: |
| 362 | used = "exa" |
| 363 | except Exception as e: |
| 364 | _log(kind, f"Exa discovery error: {e}") |
| 365 | |
| 366 | if not urls and not _stopped(deadline, cancel) and config.get("BRAVE_API_KEY"): |
| 367 | try: |
| 368 | if _collect( |
| 369 | kind, |
| 370 | _brave_links( |
| 371 | q, config["BRAVE_API_KEY"], count, |
| 372 | fresh=relative("brave"), deadline=deadline, cancel=cancel, |
| 373 | ), |
| 374 | urls, |
| 375 | count, |
| 376 | ): |
| 377 | return urls, "brave" |
| 378 | if urls: |
| 379 | used = "brave" |
| 380 | except Exception as e: |
| 381 | _log(kind, f"Brave discovery error: {e}") |
| 382 | |
| 383 | # The keyless floor follows the same policy the availability gate used: |
| 384 | # when the host has native search (LAST30DAYS_NATIVE_SEARCH), the floor is |
| 385 | # off, so a failed paid rung must not fall through to it either. A host |
| 386 | # that passed --shortform-urls already searched; the floor (slow, usually |
| 387 | # bot-blocked) would only repeat that search worse. |
| 388 | if not urls and not _stopped(deadline, cancel): |
| 389 | from . import shortform_envelope |
| 390 | from .env import keyless_web_allowed |
| 391 | |
| 392 | if keyless_web_allowed(config) and shortform_envelope.from_config(config) is None: |
| 393 | try: |
| 394 | items, art = web_search_keyless.keyless_search( |
| 395 | q, ("1970-01-01", "2099-12-31"), config, count, |
| 396 | deadline_monotonic=deadline, cancel=cancel, |
| 397 | ) |
| 398 | _collect(kind, (i.get("url", "") for i in items), urls, count) |
| 399 | if urls and used == "none": |
| 400 | used = art.get("keyless_backend") or "keyless" |
| 401 | except Exception as e: |
| 402 | _log(kind, f"Keyless discovery error: {e}") |
| 403 | |
| 404 | return urls[:count], used if urls else "none" |
| 405 | |
| 406 | |
| 407 | def _creator_is_topic(topic: str, handle: str) -> bool: |
| 408 | """True when the account is the topic itself (@sabrinacarpenter for |
| 409 | "Sabrina Carpenter"): its own captions rarely name it, so its posts are |
| 410 | on-topic by authorship.""" |
| 411 | key = re.sub(r"[^a-z0-9]", "", (topic or "").lower()) |
| 412 | name = re.sub(r"[^a-z0-9]", "", (handle or "").lstrip("@").lower()) |
| 413 | return len(key) >= 4 and key in name |
| 414 | |
| 415 | |
| 416 | def creator_urls( |
| 417 | kind: str, |
| 418 | handle: str, |
| 419 | count: int, |
| 420 | deadline: float | None = None, |
| 421 | *, |
| 422 | cancel: threading.Event | None = None, |
| 423 | topic: str | None = None, |
| 424 | from_date: str | None = None, |
| 425 | to_date: str | None = None, |
| 426 | ) -> List[str]: |
| 427 | """Most-viewed recent TikTok posts for ``@handle``. IG user listing is |
| 428 | broken, so Instagram is skipped. |
| 429 | |
| 430 | Lists the newest ``3 * count`` entries (id, title and view count, one JSON |
| 431 | object per line; one listing call). With a window, ids that decode outside |
| 432 | it are dropped; with ``topic``, titles below the shared relevance floor are |
| 433 | dropped. The ``count`` survivors with the most views are returned, so a |
| 434 | creator's month is represented by what people actually watched. All of |
| 435 | this runs before hydration. |
| 436 | """ |
| 437 | if kind != "tiktok" or not handle or _stopped(deadline, cancel): |
| 438 | return [] |
| 439 | handle = handle.lstrip("@").strip() |
| 440 | if not handle: |
| 441 | return [] |
| 442 | cmd = [ |
| 443 | "yt-dlp", |
| 444 | "--ignore-config", |
| 445 | "--no-warnings", |
| 446 | "--flat-playlist", |
| 447 | "--playlist-end", |
| 448 | str(count * _CREATOR_LIST_FACTOR), |
| 449 | "--print", |
| 450 | "%(.{id,title,view_count})j", |
| 451 | f"https://www.tiktok.com/@{handle}", |
| 452 | ] |
| 453 | # Same routing as the YouTube source: local yt-dlp, or the SSH host when |
| 454 | # LAST30DAYS_YOUTUBE_SSH_HOST is set (proxy flag folds in too). |
| 455 | cmd = youtube_yt.wrap_ytdlp_cmd(cmd) |
| 456 | try: |
| 457 | result = subproc.run_with_timeout( |
| 458 | cmd, timeout=_bounded_timeout(60.0, deadline), |
| 459 | deadline_monotonic=deadline, cancel=cancel, |
| 460 | ) |
| 461 | except (subproc.SubprocTimeout, FileNotFoundError, OSError) as e: |
| 462 | _log(kind, f"creator list @{handle} failed: {e}") |
| 463 | return [] |
| 464 | out: List[Tuple[int, str]] = [] |
| 465 | for line in (result.stdout or "").splitlines(): |
| 466 | try: |
| 467 | entry = json.loads(line) |
| 468 | except json.JSONDecodeError: |
| 469 | continue |
| 470 | if not isinstance(entry, dict): |
| 471 | continue |
| 472 | vid = str(entry.get("id") or "") |
| 473 | if not vid.isdigit(): |
| 474 | continue |
| 475 | url = f"https://www.tiktok.com/@{handle}/video/{vid}" |
| 476 | if from_date and to_date and _outside_window(kind, url, from_date, to_date): |
| 477 | continue |
| 478 | title = str(entry.get("title") or "") |
| 479 | if (topic and not _creator_is_topic(topic, handle) |
| 480 | and _compute_relevance(topic, title) < RELEVANCE_FLOOR): |
| 481 | continue |
| 482 | views = entry.get("view_count") |
| 483 | out.append((views if isinstance(views, int) else -1, url)) |
| 484 | # Stable: equal (or unknown) view counts keep the newest-first listing order. |
| 485 | out.sort(key=lambda pair: pair[0], reverse=True) |
| 486 | return [url for _views, url in out[:count]] |
| 487 | |
| 488 | |
| 489 | def _post_id(kind: str, url: str) -> str: |
| 490 | """The platform id in a post URL (TikTok video id, Instagram shortcode).""" |
| 491 | m = (_TT_RE if kind == "tiktok" else _IG_RE).search(url or "") |
| 492 | if not m: |
| 493 | return "" |
| 494 | return m.group(2) if kind == "tiktok" else m.group(1) |
| 495 | |
| 496 | |
| 497 | def _item_from_ytdlp(kind: str, raw: Dict[str, Any], core_topic: str) -> Optional[Dict[str, Any]]: |
| 498 | video_id = str(raw.get("id") or "") |
| 499 | if not video_id: |
| 500 | return None |
| 501 | author = raw.get("uploader") or raw.get("channel") or raw.get("creator") or "" |
| 502 | text = (raw.get("description") or raw.get("title") or "").strip() |
| 503 | ts = raw.get("timestamp") |
| 504 | date_str = dates.timestamp_to_date(ts) if ts else None |
| 505 | hashtags = _HASHTAG_RE.findall(text) |
| 506 | if kind == "tiktok": |
| 507 | url = ( |
| 508 | normalize_post_url(kind, raw.get("webpage_url") or "") |
| 509 | or (f"https://www.tiktok.com/@{author}/video/{video_id}" if author else "") |
| 510 | ) |
| 511 | label = "TikTok" |
| 512 | engagement = { |
| 513 | "views": raw.get("view_count"), |
| 514 | "likes": raw.get("like_count") or 0, |
| 515 | "comments": raw.get("comment_count") or 0, |
| 516 | "shares": raw.get("repost_count") or 0, |
| 517 | } |
| 518 | else: |
| 519 | url = normalize_post_url(kind, raw.get("webpage_url") or "") or ( |
| 520 | f"https://www.instagram.com/reel/{video_id}/" |
| 521 | ) |
| 522 | label = "Instagram" |
| 523 | engagement = { |
| 524 | "views": raw.get("view_count"), |
| 525 | "likes": raw.get("like_count") or 0, |
| 526 | "comments": raw.get("comment_count") or 0, |
| 527 | } |
| 528 | if not url: |
| 529 | return None |
| 530 | snippet = text |
| 531 | words = snippet.split() |
| 532 | if len(words) > 500: |
| 533 | snippet = " ".join(words[:500]) + "..." |
| 534 | return { |
| 535 | "video_id": video_id, |
| 536 | "text": text, |
| 537 | "url": url, |
| 538 | "author_name": author, |
| 539 | "date": date_str, |
| 540 | "engagement": engagement, |
| 541 | "hashtags": hashtags, |
| 542 | "duration": raw.get("duration"), |
| 543 | "relevance": (1.0 if _creator_is_topic(core_topic, author) |
| 544 | else _compute_relevance(core_topic, text, hashtags)), |
| 545 | "why_relevant": f"{label}: {text[:60]}" if text else f"{label}: {core_topic}", |
| 546 | "caption_snippet": snippet, |
| 547 | "_oss_backend": "yt-dlp", |
| 548 | } |
| 549 | |
| 550 | |
| 551 | def _enrich_batch( |
| 552 | kind: str, |
| 553 | urls: List[str], |
| 554 | deadline: float | None, |
| 555 | cancel: threading.Event | None, |
| 556 | ) -> str: |
| 557 | """One yt-dlp --dump-json run over ``urls``; stdout, or "" on failure.""" |
| 558 | if _stopped(deadline, cancel): |
| 559 | return "" |
| 560 | cmd = [ |
| 561 | "yt-dlp", |
| 562 | "--ignore-config", |
| 563 | "--skip-download", |
| 564 | "--ignore-errors", |
| 565 | "--no-warnings", |
| 566 | "--dump-json", |
| 567 | "--socket-timeout", |
| 568 | "25", |
| 569 | "-a", |
| 570 | "-", |
| 571 | ] |
| 572 | # Same routing as the YouTube source (see creator_urls). |
| 573 | cmd = youtube_yt.wrap_ytdlp_cmd(cmd) |
| 574 | budget = _bounded_timeout(_ENRICH_TIMEOUT, deadline) |
| 575 | try: |
| 576 | result = subproc.run_with_timeout( |
| 577 | cmd, timeout=budget, input_text="\n".join(urls) + "\n", |
| 578 | deadline_monotonic=deadline, cancel=cancel, |
| 579 | ) |
| 580 | except subproc.SubprocTimeout: |
| 581 | _log(kind, f"yt-dlp enrich batch of {len(urls)} timed out ({budget:.0f}s)") |
| 582 | return "" |
| 583 | except (FileNotFoundError, OSError) as e: |
| 584 | _log(kind, f"yt-dlp enrich failed: {e}") |
| 585 | return "" |
| 586 | return result.stdout or "" |
| 587 | |
| 588 | |
| 589 | def enrich_urls( |
| 590 | kind: str, |
| 591 | urls: List[str], |
| 592 | core_topic: str, |
| 593 | deadline: float | None = None, |
| 594 | cancel: threading.Event | None = None, |
| 595 | ) -> List[Dict[str, Any]]: |
| 596 | """yt-dlp --dump-json over a URL list. Never raises; stops at deadline/cancel. |
| 597 | |
| 598 | Each URL runs in its own yt-dlp, a few at a time, so a timeout or cancel |
| 599 | loses only the posts still running: posts already read are kept. |
| 600 | """ |
| 601 | if not urls or _stopped(deadline, cancel): |
| 602 | return [] |
| 603 | if not youtube_yt.is_ytdlp_installed(): |
| 604 | _log(kind, "yt-dlp not installed; skip OSS enrich") |
| 605 | return [] |
| 606 | batches = [urls[i:i + _ENRICH_BATCH] for i in range(0, len(urls), _ENRICH_BATCH)] |
| 607 | if len(batches) == 1: |
| 608 | outputs = [_enrich_batch(kind, batches[0], deadline, cancel)] |
| 609 | else: |
| 610 | workers = min(_ENRICH_WORKERS, len(batches)) |
| 611 | with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool: |
| 612 | futures = [ |
| 613 | http.submit_with_context(pool, _enrich_batch, kind, b, deadline, cancel) |
| 614 | for b in batches |
| 615 | ] |
| 616 | outputs = [f.result() for f in futures] |
| 617 | items: List[Dict[str, Any]] = [] |
| 618 | seen: set[str] = set() |
| 619 | for output in outputs: |
| 620 | for line in output.splitlines(): |
| 621 | line = line.strip() |
| 622 | if not line.startswith("{"): |
| 623 | continue |
| 624 | try: |
| 625 | raw = json.loads(line) |
| 626 | except json.JSONDecodeError: |
| 627 | continue |
| 628 | item = _item_from_ytdlp(kind, raw, core_topic) |
| 629 | if not item: |
| 630 | continue |
| 631 | vid = item["video_id"] |
| 632 | if vid in seen: |
| 633 | continue |
| 634 | seen.add(vid) |
| 635 | items.append(item) |
| 636 | _log(kind, f"yt-dlp enriched {len(items)}/{len(urls)} posts") |
| 637 | return items |
| 638 | |
| 639 | |
| 640 | def search( |
| 641 | kind: str, |
| 642 | topic: str, |
| 643 | from_date: str, |
| 644 | to_date: str, |
| 645 | depth: str, |
| 646 | config: Dict[str, Any], |
| 647 | creators: Optional[List[str]] = None, |
| 648 | deadline: float | None = None, |
| 649 | cancel: threading.Event | None = None, |
| 650 | ) -> Dict[str, Any]: |
| 651 | """Discover + enrich. Returns the same ``{items, error}`` shape as SC search. |
| 652 | |
| 653 | Honors the run's shared monotonic deadline and cancellation event: each |
| 654 | phase checks both before starting, and per-call timeouts are bounded by |
| 655 | the remaining time, so a cancelled run does not keep a 180s yt-dlp |
| 656 | extraction alive past exit. |
| 657 | """ |
| 658 | if kind not in ("tiktok", "instagram"): |
| 659 | return {"items": [], "error": f"unsupported kind {kind!r}"} |
| 660 | if not youtube_yt.is_ytdlp_installed(): |
| 661 | return {"items": [], "error": "yt-dlp not installed"} |
| 662 | if _stopped(deadline, cancel): |
| 663 | return {"items": [], "error": "research deadline passed before OSS fallback"} |
| 664 | |
| 665 | cap = _DEPTH_URLS.get(depth, _DEPTH_URLS["default"]) |
| 666 | window = {"from_date": from_date, "to_date": to_date} |
| 667 | urls: List[str] = [] |
| 668 | explicit = [h.lstrip("@").strip().lower() for h in (creators or []) if h] |
| 669 | |
| 670 | # Host-found URLs (--shortform-urls): post URLs lead, held to the same |
| 671 | # id-date filter; they widen the hydration budget by up to one cap. |
| 672 | from . import shortform_envelope |
| 673 | host_env = shortform_envelope.from_config(config) |
| 674 | host_posts = host_env.posts(kind) if host_env else [] |
| 675 | host_creators = host_env.creators(kind) if host_env else [] |
| 676 | host_urls: set[str] = set() |
| 677 | host_stale = [u for u in host_posts if _outside_window(kind, u, from_date, to_date)] |
| 678 | if host_stale: |
| 679 | _log(kind, f"host URLs: dropped {len(host_stale)} dated outside " |
| 680 | f"{from_date}..{to_date} before extraction") |
| 681 | for u in host_posts: |
| 682 | if u not in host_stale and u not in urls: |
| 683 | urls.append(u) |
| 684 | host_urls.add(u) |
| 685 | limit = cap + min(len(urls), cap) |
| 686 | |
| 687 | if kind == "tiktok" and creators: |
| 688 | per = max(3, cap // max(len(creators), 1)) |
| 689 | for handle in creators: |
| 690 | if _stopped(deadline, cancel): |
| 691 | return {"items": [], "error": "research deadline passed before OSS discovery"} |
| 692 | for u in creator_urls(kind, handle, per, deadline=deadline, cancel=cancel, **window): |
| 693 | if u not in urls: |
| 694 | urls.append(u) |
| 695 | |
| 696 | found, backend = discover_urls( |
| 697 | kind, topic, config, cap, deadline=deadline, cancel=cancel, |
| 698 | from_date=from_date, to_date=to_date, |
| 699 | ) |
| 700 | stale = [u for u in found if _outside_window(kind, u, from_date, to_date)] |
| 701 | if stale: |
| 702 | _log(kind, f"OSS dropped {len(stale)} discovered posts dated outside " |
| 703 | f"{from_date}..{to_date} before extraction") |
| 704 | stale += host_stale |
| 705 | for u in found: |
| 706 | if u not in urls and u not in stale: |
| 707 | urls.append(u) |
| 708 | |
| 709 | # Creator expansion (TikTok). Host creator profiles are listed first and |
| 710 | # always (the host named them); with expansion on, every handle seen in |
| 711 | # discovery or in a host post URL, stale videos included, is a lead too. |
| 712 | if kind == "tiktok": |
| 713 | max_creators, per_creator = _DEPTH_CREATORS.get(depth, _DEPTH_CREATORS["default"]) |
| 714 | leads: List[Tuple[str, bool]] = [(h, True) for h in host_creators] |
| 715 | if _expansion_on(config): |
| 716 | for u in [*host_posts, *found]: |
| 717 | m = _TT_RE.search(u) |
| 718 | if m: |
| 719 | leads.append((m.group(1), False)) |
| 720 | handles: List[Tuple[str, bool]] = [] |
| 721 | for h, from_host in leads: |
| 722 | if h.lower() not in explicit and h.lower() not in {x.lower() for x, _ in handles}: |
| 723 | handles.append((h, from_host)) |
| 724 | for handle, from_host in handles[:max_creators]: |
| 725 | if _stopped(deadline, cancel) or len(urls) >= limit: |
| 726 | break |
| 727 | for u in creator_urls( |
| 728 | kind, handle, per_creator, deadline=deadline, cancel=cancel, topic=topic, **window, |
| 729 | ): |
| 730 | if u not in urls: |
| 731 | urls.append(u) |
| 732 | if from_host: |
| 733 | host_urls.add(u) |
| 734 | |
| 735 | urls = urls[:limit] |
| 736 | source = f"{backend}+host" if host_urls and backend != "none" else ("host" if host_urls else backend) |
| 737 | _log(kind, f"OSS discovery via {source}: {len(urls)} urls (depth={depth})") |
| 738 | if not urls: |
| 739 | if stale: |
| 740 | return {"items": [], "error": "oss discovery found only posts outside the date window"} |
| 741 | from .env import keyless_web_allowed |
| 742 | if host_env is None and backend == "none" and not keyless_web_allowed(config): |
| 743 | # Native-search host: its own search is the discovery source. |
| 744 | return {"items": [], "error": "oss discovery empty (the host passed no --shortform-urls)"} |
| 745 | return {"items": [], "error": "oss discovery empty"} |
| 746 | |
| 747 | items = enrich_urls(kind, urls, topic, deadline=deadline, cancel=cancel) |
| 748 | if not items: |
| 749 | return {"items": [], "error": "yt-dlp extracted 0 posts"} |
| 750 | |
| 751 | in_range = [i for i in items if i.get("date") and from_date <= i["date"] <= to_date] |
| 752 | dropped = len(items) - len(in_range) |
| 753 | if dropped: |
| 754 | _log(kind, f"OSS dropped {dropped} posts outside date range or undated") |
| 755 | if not in_range: |
| 756 | return {"items": [], "error": f"no posts in date range ({len(items)} extracted, " |
| 757 | f"none dated {from_date}..{to_date})"} |
| 758 | items = in_range |
| 759 | |
| 760 | if host_urls: |
| 761 | host_ids = {_post_id(kind, u) for u in host_urls} |
| 762 | kept: List[Dict[str, Any]] = [] |
| 763 | off_topic = 0 |
| 764 | for item in items: |
| 765 | if _post_id(kind, item.get("url") or "") in host_ids or str(item.get("video_id")) in host_ids: |
| 766 | # Host input is untrusted: it must clear the topic bar itself. |
| 767 | if (item.get("relevance") or 0) < RELEVANCE_FLOOR: |
| 768 | off_topic += 1 |
| 769 | continue |
| 770 | item["_host_found"] = True |
| 771 | kept.append(item) |
| 772 | _log(kind, f"host URLs: kept {sum(1 for i in kept if i.get('_host_found'))} " |
| 773 | f"after hydration (off-topic {off_topic})") |
| 774 | items = kept |
| 775 | if not items: |
| 776 | return {"items": [], "error": "host URLs and discovery kept 0 on-topic posts"} |
| 777 | |
| 778 | items.sort(key=lambda x: x.get("engagement", {}).get("views") or 0, reverse=True) |
| 779 | return {"items": items, "backend": backend} |
| 780 | |
| 781 | |
| 782 | def credits_exhausted(error: Optional[str]) -> bool: |
| 783 | """True when ScrapeCreators (or similar) refused the call for quota.""" |
| 784 | if not error: |
| 785 | return False |
| 786 | text = str(error).lower() |
| 787 | return "402" in text or "payment required" in text or "out of credits" in text |
| 788 | |
| 789 | |
| 790 | if __name__ == "__main__": |
| 791 | from pathlib import Path |
| 792 | import sys |
| 793 | sys.path.insert(0, str(Path(__file__).resolve().parents[1])) |
| 794 | tt = normalize_post_url( |
| 795 | "tiktok", "https://www.tiktok.com/%40pris.cesa/video/7692631242264595743?foo=1" |
| 796 | ) |
| 797 | assert tt == "https://www.tiktok.com/@pris.cesa/video/7692631242264595743", tt |
| 798 | ig = normalize_post_url("instagram", "https://www.instagram.com/reel/Dem0getP8Js/") |
| 799 | assert ig == "https://www.instagram.com/reel/Dem0getP8Js/", ig |
| 800 | assert normalize_post_url("tiktok", "https://www.tiktok.com/discover/foo") is None |
| 801 | item = _item_from_ytdlp( |
| 802 | "tiktok", |
| 803 | { |
| 804 | "id": "1", |
| 805 | "uploader": "u", |
| 806 | "timestamp": 1728000000, |
| 807 | "view_count": 10, |
| 808 | "like_count": 2, |
| 809 | "comment_count": 1, |
| 810 | "description": "hello #cozy", |
| 811 | "webpage_url": "https://www.tiktok.com/@u/video/1", |
| 812 | }, |
| 813 | "cozy", |
| 814 | ) |
| 815 | assert item and item["engagement"]["likes"] == 2 and item["date"] |
| 816 | assert credits_exhausted("HTTPError: HTTP 402: Payment Required") |
| 817 | assert not credits_exhausted(None) |
| 818 | assert discovery_query("instagram", "cozy game") == "cozy game instagram reel" |
| 819 | print("ok") |
| 820 |