返回 last30days-skill
instagram.py
根目录 / skills / last30days / scripts / lib / instagram.py
1 """Instagram Reels search via ScrapeCreators API for /last30days.
2
3 Uses ScrapeCreators REST API to search Instagram Reels by keyword, extract
4 engagement metrics (views, likes, comments), and fetch video transcripts.
5
6 Requires SCRAPECREATORS_API_KEY in config. 100 free API calls, then PAYG.
7 API docs: https://scrapecreators.com/docs
8
9 When the key is missing or ScrapeCreators returns 402, search_and_enrich
10 falls back to web discovery + yt-dlp (lib.shortform_oss).
11 """
12
13 import json
14 import os
15 import re
16 import sys
17 import threading
18 import time
19 from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
20 from datetime import datetime, timedelta
21 from typing import Any, Dict, List, Optional, Set
22 from urllib.parse import urlsplit
23
24 from . import dates, health, http, log
25 from .query import infer_query_intent
26 from .relevance import token_overlap_relevance as _compute_relevance
27
28 SCRAPECREATORS_BASE = "https://api.scrapecreators.com"
29
30
31 def _sc_base() -> str:
32 if SCRAPECREATORS_BASE != "https://api.scrapecreators.com":
33 return SCRAPECREATORS_BASE
34 from . import env
35 return env.get_scrapecreators_base_url()
36
37 # Depth configurations: how many results to fetch / captions to extract
38 DEPTH_CONFIG = {
39 "quick": {"results_per_page": 10, "max_captions": 3},
40 "default": {"results_per_page": 20, "max_captions": 5},
41 "deep": {"results_per_page": 40, "max_captions": 8},
42 }
43
44 # Keep the Google discovery fallback bounded because each post detail request
45 # costs one credit. The page/post totals match the fallback's observed depth
46 # budgets: 1 + 9, 2 + 16, and 3 + 27 requests.
47 GOOGLE_FALLBACK_BUDGETS = {
48 "quick": (1, 9),
49 "default": (2, 16),
50 "deep": (3, 27),
51 }
52
53 # Max words to keep from each caption
54 CAPTION_MAX_WORDS = 500
55 RESEARCH_TIMEOUT = "Instagram research timed out or was cancelled; returning collected reels"
56
57 # Default transcript fetch timeout (seconds). SC's
58 # /v2/instagram/media/transcript regularly takes >15s on real workloads,
59 # so the default is generous; override via LAST30DAYS_TRANSCRIPT_TIMEOUT.
60 DEFAULT_TRANSCRIPT_TIMEOUT = 30
61
62
63 def _resolve_transcript_timeout(
64 timeout: Optional[float] = None,
65 config: Optional[Dict[str, Any]] = None,
66 ) -> float:
67 """Resolve the IG transcript-fetch timeout.
68
69 Priority (highest wins):
70 1. Explicit ``timeout`` kwarg
71 2. ``LAST30DAYS_TRANSCRIPT_TIMEOUT`` in os.environ
72 3. ``LAST30DAYS_TRANSCRIPT_TIMEOUT`` in caller-supplied config dict
73 4. ``DEFAULT_TRANSCRIPT_TIMEOUT`` (30s)
74
75 Mirrors the ``os.environ.get(X) or config.get(X)`` pattern used for
76 LAST30DAYS_STORE in last30days.py so the env var works whether it's
77 shell-exported or set in ~/.config/last30days/.env.
78 """
79 if timeout is not None:
80 try:
81 return float(timeout)
82 except (TypeError, ValueError):
83 pass
84 raw = os.environ.get("LAST30DAYS_TRANSCRIPT_TIMEOUT")
85 if not raw and config:
86 raw = config.get("LAST30DAYS_TRANSCRIPT_TIMEOUT")
87 if raw:
88 try:
89 return float(raw)
90 except (TypeError, ValueError):
91 pass
92 return float(DEFAULT_TRANSCRIPT_TIMEOUT)
93
94
95 def _extract_core_subject(topic: str) -> str:
96 """Extract core subject from verbose query for Instagram search."""
97 from .query import VIRAL_NOISE, extract_core_subject
98 return extract_core_subject(topic, noise=VIRAL_NOISE)
99
100
101 def _to_hashtag_form(query: str) -> str:
102 """Collapse a multi-word query to hashtag form (no spaces, lowercase).
103
104 SC's /v2/instagram/reels/search wraps Google Search and is documented
105 to be flaky on multi-token queries. Single-token queries map to a
106 hashtag page lookup which is the stable path. Used as a 500-retry
107 fallback before the request bubbles up as a silent failure.
108 """
109 return ''.join(query.split()).lower()
110
111
112 def _is_no_reels_found_404(error: http.HTTPError) -> bool:
113 """Recognize ScrapeCreators' documented empty-search response, not any 404.
114
115 The reels-search endpoint reports zero matches as HTTP 404 with a JSON
116 ``not_found`` error. Other 404s can indicate a broken endpoint, so both
117 the provider error code and its explicit no-reels message must match.
118 """
119 if error.status_code != 404 or not isinstance(error.body, str):
120 return False
121 try:
122 payload = json.loads(error.body)
123 except ValueError:
124 return False
125 return (
126 isinstance(payload, dict)
127 and payload.get("error") == "not_found"
128 and isinstance(payload.get("message"), str)
129 and payload["message"].strip().lower().startswith("no reels found for that query")
130 )
131
132
133 def _get_reels_search(
134 query: str,
135 token: str,
136 deadline: float | None,
137 cancel: threading.Event | None,
138 ) -> dict[str, Any]:
139 return http.get(
140 f"{_sc_base()}/v2/instagram/reels/search",
141 params={"query": query},
142 headers=http.scrapecreators_headers(token),
143 retries=2,
144 **_request_options(30, deadline, cancel),
145 )
146
147
148 def expand_instagram_queries(topic: str, depth: str) -> List[str]:
149 """Generate multiple Instagram search queries from a topic.
150
151 Mirrors reddit.py's expand_reddit_queries() pattern:
152 1. Extract core subject (strip noise words)
153 2. Include original topic if different from core
154 3. Add intent-specific OR-joined content-type variants
155 4. Cap by depth: 1 for quick, 2 for default, 3 for deep
156
157 Returns 1-3 query strings depending on depth.
158 """
159 core = _extract_core_subject(topic)
160 queries = [core]
161
162 # Include cleaned original topic as variant if different from core
163 original_clean = topic.strip().rstrip('?!.')
164 if core.lower() != original_clean.lower() and len(original_clean.split()) <= 8:
165 queries.append(original_clean)
166
167 qtype = infer_query_intent(topic)
168
169 # Intent-specific Instagram content-type variants
170 if qtype == "breaking_news":
171 queries.append(f"{core} reaction OR edit")
172 elif qtype == "opinion":
173 queries.append(f"{core} reaction OR edit")
174 elif qtype == "product":
175 queries.append(f"{core} review OR haul")
176 elif qtype == "comparison":
177 queries.append(f"{core} vs OR compared")
178 elif qtype == "how_to":
179 queries.append(f"{core} tutorial OR hack")
180 else:
181 queries.append(f"{core} reaction OR edit")
182
183 # Deep depth: add viral content variant
184 if depth == "deep":
185 queries.append(f"{core} viral OR trending OR reel")
186
187 # Cap by depth budget
188 caps = {"quick": 1, "default": 2, "deep": 3}
189 cap = caps.get(depth, 2)
190 return queries[:cap]
191
192
193 def _log(msg: str):
194 log.source_log("Instagram", msg, tty_only=False)
195
196
197 def _budget_expired(deadline: float | None, cancel: threading.Event | None) -> bool:
198 return bool(
199 (cancel is not None and cancel.is_set())
200 or (deadline is not None and time.monotonic() >= deadline)
201 )
202
203
204 def _request_options(timeout: float, deadline: float | None, cancel: threading.Event | None) -> dict:
205 options = {"timeout": timeout}
206 if deadline is not None:
207 options["timeout"] = min(timeout, max(0.001, deadline - time.monotonic()))
208 options["deadline_monotonic"] = deadline
209 if cancel is not None:
210 options["cancel"] = cancel
211 return options
212
213
214 def _parse_date(item: Dict[str, Any]) -> Optional[str]:
215 """Parse date from ScrapeCreators Instagram item to YYYY-MM-DD.
216
217 Handles taken_at as ISO string (e.g. "2026-02-26T16:00:00.000Z")
218 or unix timestamp.
219 """
220 ts = item.get("taken_at")
221 if not ts:
222 return None
223
224 # Try ISO string first (ScrapeCreators reels/search returns this)
225 if isinstance(ts, str):
226 try:
227 # Handle "2026-02-26T16:00:00.000Z" format
228 dt = datetime.fromisoformat(ts.replace("Z", "+00:00"))
229 return dt.strftime("%Y-%m-%d")
230 except (ValueError, TypeError):
231 pass
232 # Try just the date portion (a numeric string is a unix timestamp)
233 if len(ts) >= 10 and not ts.strip().isdigit():
234 return ts[:10]
235
236 # Fall back to unix timestamp
237 try:
238 return dates.timestamp_to_date(int(ts))
239 except (ValueError, TypeError):
240 pass
241
242 return None
243
244
245 def _extract_hashtags(caption_text: str) -> List[str]:
246 """Extract hashtags from Instagram caption text."""
247 if not caption_text:
248 return []
249 return re.findall(r'#(\w+)', caption_text)
250
251
252 def _parse_items(raw_items: List[Dict[str, Any]], core_topic: str) -> List[Dict[str, Any]]:
253 """Parse raw Instagram items into normalized dicts."""
254 items = []
255 for raw in raw_items:
256 if not isinstance(raw, dict):
257 continue
258
259 # Extract reel ID and shortcode
260 reel_pk = str(raw.get("id", raw.get("pk", "")))
261 shortcode = raw.get("shortcode", raw.get("code", ""))
262
263 # Caption text -- can be a string or dict depending on endpoint
264 caption_obj = raw.get("caption", "")
265 if isinstance(caption_obj, dict):
266 text = caption_obj.get("text", "")
267 elif isinstance(caption_obj, str):
268 text = caption_obj
269 else:
270 text = raw.get("desc", raw.get("text", ""))
271
272 # Engagement metrics (keep missing play counts as None so unreported
273 # views are distinct from a measured 0).
274 play_count = next(
275 (
276 raw[k]
277 for k in ("video_play_count", "video_view_count", "play_count")
278 if raw.get(k) is not None
279 ),
280 None,
281 )
282 like_count = raw.get("like_count") or 0
283 comment_count = raw.get("comment_count") or 0
284
285 # Author info -- 'owner' in reels/search, 'user' in user/reels
286 owner_raw = raw.get("owner") or raw.get("user")
287 if isinstance(owner_raw, dict):
288 author_name = owner_raw.get("username", "")
289 elif isinstance(owner_raw, str):
290 author_name = owner_raw
291 else:
292 author_name = ""
293
294 # Duration
295 duration = raw.get("video_duration")
296
297 # Date
298 date_str = _parse_date(raw)
299
300 # Hashtags from caption text
301 hashtags = _extract_hashtags(text)
302
303 # Compute relevance with hashtag boost
304 relevance = _compute_relevance(core_topic, text, hashtags)
305
306 # Build URL -- prefer API-provided url, fallback to shortcode
307 url = raw.get("url", "")
308 if not url and shortcode:
309 url = f"https://www.instagram.com/reel/{shortcode}"
310
311 items.append({
312 "video_id": reel_pk,
313 "text": text,
314 "url": url,
315 "author_name": author_name,
316 "date": date_str,
317 "engagement": {
318 "views": play_count,
319 "likes": like_count,
320 "comments": comment_count,
321 },
322 "hashtags": hashtags,
323 "duration": duration,
324 "relevance": relevance,
325 "why_relevant": f"Instagram: {text[:60]}" if text else f"Instagram: {core_topic}",
326 "caption_snippet": "", # populated by fetch_captions
327 })
328 return items
329
330
331 def _user_reels(
332 handle: str,
333 token: str,
334 *,
335 deadline: float | None = None,
336 cancel: threading.Event | None = None,
337 ) -> List[Dict[str, Any]]:
338 """Fetch an Instagram user's recent reels via ScrapeCreators.
339
340 Args:
341 handle: Instagram username (without @)
342 token: ScrapeCreators API key
343
344 Returns:
345 List of raw Instagram reel dicts.
346 """
347 if _budget_expired(deadline, cancel):
348 return []
349 _log(f"User reels: @{handle}")
350 reels_url = f"{_sc_base()}/v1/instagram/user/reels"
351 try:
352 data = http.get(
353 reels_url,
354 params={"handle": handle},
355 headers=http.scrapecreators_headers(token),
356 retries=2,
357 **_request_options(30, deadline, cancel),
358 )
359 except Exception as e:
360 _log(f"User reels error for @{handle}: {e}")
361 return []
362
363 raw_items = data.get("items") or data.get("reels") or data.get("data") or []
364 _log(f" -> {len(raw_items)} reels from @{handle}")
365
366 # User-reels responses wrap each reel in a ``media`` envelope, while
367 # other Instagram endpoints already return flat reel dictionaries.
368 return [
369 item["media"]
370 if isinstance(item, dict) and isinstance(item.get("media"), dict)
371 else item
372 for item in raw_items
373 ]
374
375
376 def _normalize_google_post(
377 payload: dict[str, Any], url: str
378 ) -> dict[str, Any] | None:
379 """Convert a ScrapeCreators post detail response to the reels/search shape."""
380 if not isinstance(payload, dict):
381 return None
382 data = payload.get("data")
383 if not isinstance(data, dict):
384 return None
385 media = data.get("xdt_shortcode_media")
386 if not isinstance(media, dict):
387 return None
388
389 caption = media.get("caption")
390 if not caption:
391 edges = (media.get("edge_media_to_caption") or {}).get("edges") or []
392 if edges and isinstance(edges[0], dict):
393 caption = (edges[0].get("node") or {}).get("text", "")
394
395 likes = (media.get("edge_media_preview_like") or {}).get("count")
396 comments = (media.get("edge_media_to_parent_comment") or {}).get("count")
397 if comments is None:
398 comments = (media.get("edge_media_to_comment") or {}).get("count")
399
400 return {
401 "id": media.get("id", ""),
402 "shortcode": media.get("shortcode", ""),
403 "url": url,
404 "caption": caption or "",
405 "taken_at": media.get("taken_at_timestamp") or media.get("created_at"),
406 "video_play_count": next(
407 (
408 media[k]
409 for k in ("video_play_count", "video_view_count", "play_count")
410 if media.get(k) is not None
411 ),
412 None,
413 ),
414 "like_count": likes or 0,
415 "comment_count": comments or 0,
416 "owner": media.get("owner") or media.get("user") or {},
417 }
418
419
420 def _google_reel_fallback(
421 topic: str,
422 depth: str,
423 token: str,
424 from_date: str,
425 to_date: str,
426 budget: dict[str, int] | None = None,
427 detail_cache: dict[str, dict[str, Any]] | None = None,
428 *,
429 deadline: float | None = None,
430 cancel: threading.Event | None = None,
431 error_out: list[tuple[str, str]] | None = None,
432 ) -> list[dict[str, Any]]:
433 """Discover Instagram reels through Google and fetch their post details."""
434 if budget is None:
435 pages, max_posts = GOOGLE_FALLBACK_BUDGETS.get(
436 depth, GOOGLE_FALLBACK_BUDGETS["default"]
437 )
438 budget = {"pages": pages, "posts": max_posts}
439 pages = max(0, budget.get("pages", 0))
440 max_posts = max(0, budget.get("posts", 0))
441 if not pages or not max_posts:
442 return []
443 headers = http.scrapecreators_headers(token)
444 detail_cache = detail_cache if detail_cache is not None else {}
445 shortcode_urls: dict[str, str] = {}
446 ordered_shortcodes: list[str] = []
447 end_exclusive = (
448 datetime.strptime(to_date, "%Y-%m-%d") + timedelta(days=1)
449 ).strftime("%Y-%m-%d")
450
451 for page in range(1, pages + 1):
452 if _budget_expired(deadline, cancel):
453 break
454 budget["pages"] -= 1
455 try:
456 # A 404 here means the search found nothing. Mark it an expected
457 # miss so the pipeline's failure sink doesn't brand the source
458 # with a swallowed 404 once the adapter reports a clean result.
459 with http.expected_misses(404):
460 data = http.get(
461 f"{_sc_base()}/v1/google/search",
462 params={
463 "query": (
464 f"site:instagram.com/reel {topic} "
465 f"after:{from_date} before:{end_exclusive}"
466 ),
467 "page": page,
468 },
469 headers=headers,
470 retries=1,
471 **_request_options(30, deadline, cancel),
472 )
473 except Exception as e:
474 # A 404 from the Google fallback means the search found nothing,
475 # the same clean miss the primary reels search reports with its
476 # documented not_found payload. Don't record it as a failure or
477 # it resurfaces as an error on an otherwise empty result.
478 if isinstance(e, http.HTTPError) and e.status_code == 404:
479 _log(f"Google Instagram discovery fallback found no reels on page {page}")
480 break
481 detail = f"Google Instagram discovery fallback failed on page {page}: {e}"
482 # The transport already captured this same exception. Add stage
483 # context in place without losing its HTTP status or outcome type.
484 if isinstance(e, http.HTTPError):
485 e.args = (detail,)
486 if error_out is not None:
487 state = getattr(e, "outcome_state", None) or http.classify_failure(message=str(e))
488 error_out.append((detail, state))
489 _log(detail)
490 break
491 if not isinstance(data, dict):
492 _log(f"Google Instagram fallback returned invalid data on page {page}")
493 break
494
495 results = data.get("results") or data.get("items") or []
496 if not isinstance(results, list):
497 _log(f"Google Instagram fallback returned invalid results on page {page}")
498 continue
499 for result in results:
500 if not isinstance(result, dict):
501 continue
502 url = result.get("url", "")
503 try:
504 parsed_url = urlsplit(url) if isinstance(url, str) else None
505 except ValueError:
506 continue
507 hostname = parsed_url.hostname.lower() if parsed_url and parsed_url.hostname else ""
508 is_instagram = hostname == "instagram.com" or hostname.endswith(".instagram.com")
509 is_reel_path = bool(
510 parsed_url
511 and re.fullmatch(r"/reel/[A-Za-z0-9_-]+/?", parsed_url.path)
512 )
513 shortcode_match = (
514 re.fullmatch(r"/reel/([A-Za-z0-9_-]+)/?", parsed_url.path)
515 if parsed_url
516 else None
517 )
518 if (
519 parsed_url
520 and parsed_url.scheme == "https"
521 and is_instagram
522 and is_reel_path
523 ):
524 shortcode = shortcode_match.group(1)
525 if shortcode not in shortcode_urls and shortcode not in detail_cache:
526 if len(shortcode_urls) >= max_posts:
527 continue
528 shortcode_urls[shortcode] = url
529 if shortcode not in ordered_shortcodes:
530 ordered_shortcodes.append(shortcode)
531 if len(shortcode_urls) >= max_posts:
532 break
533 if len(shortcode_urls) >= max_posts:
534 break
535
536 budget["posts"] -= len(shortcode_urls)
537
538 def fetch_post(url: str) -> dict[str, Any] | None:
539 if _budget_expired(deadline, cancel):
540 return None
541 try:
542 payload = http.get(
543 f"{_sc_base()}/v1/instagram/post",
544 params={"url": url},
545 headers=headers,
546 retries=1,
547 **_request_options(30, deadline, cancel),
548 )
549 except Exception as e:
550 _log(f"Instagram post detail failed for {url}: {e}")
551 return None
552 try:
553 return _normalize_google_post(payload, url)
554 except (AttributeError, TypeError, ValueError) as e:
555 _log(f"Instagram post detail had an invalid response for {url}: {e}")
556 return None
557
558 if shortcode_urls:
559 executor = ThreadPoolExecutor(max_workers=min(4, len(shortcode_urls)))
560 try:
561 futures = {
562 http.submit_with_context(executor, fetch_post, url): shortcode
563 for shortcode, url in shortcode_urls.items()
564 }
565 pending = set(futures)
566 while pending:
567 remaining = 0.05 if deadline is None else max(0, min(0.05, deadline - time.monotonic()))
568 done, pending = wait(pending, timeout=remaining, return_when=FIRST_COMPLETED)
569 for future in done:
570 reel = future.result()
571 if reel:
572 detail_cache[futures[future]] = reel
573 if _budget_expired(deadline, cancel):
574 break
575 finally:
576 executor.shutdown(wait=False, cancel_futures=True)
577
578 reels = []
579 for shortcode in ordered_shortcodes:
580 reel = detail_cache.get(shortcode)
581 if reel:
582 reels.append(reel)
583 return reels
584
585
586 def _search_error(error: Exception) -> dict[str, Any]:
587 return {
588 "items": [],
589 "error": f"{type(error).__name__}: {error}",
590 "_error_state": getattr(error, "outcome_state", None) or http.classify_failure(message=str(error)),
591 }
592
593
594 def search_instagram(
595 topic: str,
596 from_date: str,
597 to_date: str,
598 depth: str = "default",
599 token: str = None,
600 _fallback_budget: dict[str, int] | None = None,
601 _fallback_cache: dict[str, dict[str, Any]] | None = None,
602 *,
603 deadline: float | None = None,
604 cancel: threading.Event | None = None,
605 ) -> dict[str, Any]:
606 """Search Instagram Reels via ScrapeCreators API.
607
608 Args:
609 topic: Search topic
610 from_date: Start date (YYYY-MM-DD)
611 to_date: End date (YYYY-MM-DD)
612 depth: 'quick', 'default', or 'deep'
613 token: ScrapeCreators API key
614
615 Returns:
616 Dict with 'items' list and optional 'error'.
617 """
618 if not token:
619 return {"items": [], "error": "No SCRAPECREATORS_API_KEY configured"}
620 if _budget_expired(deadline, cancel):
621 return {"items": [], "error": RESEARCH_TIMEOUT}
622
623 config = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
624 core_topic = _extract_core_subject(topic)
625
626 _log(f"Searching Instagram for '{core_topic}' (depth={depth}, count={config['results_per_page']})")
627
628 primary_error = None
629 superseded_failures: list[http.HTTPError] = []
630 with http.tee_failures() as reels_failures:
631 try:
632 data = _get_reels_search(core_topic, token, deadline, cancel)
633 except http.HTTPError as e:
634 # SC's v2 reels search wraps Google Search and 500s frequently on
635 # multi-token queries. Single tokens hit the stable hashtag-page
636 # path. Retry once with hashtag form before bubbling up.
637 if (getattr(e, "status_code", None) == 500 and ' ' in core_topic
638 and not _budget_expired(deadline, cancel)):
639 _log(f"IG search 500 on '{core_topic}', retrying with hashtag form")
640 try:
641 data = _get_reels_search(_to_hashtag_form(core_topic), token, deadline, cancel)
642 superseded_failures.append(e)
643 except Exception as retry_e:
644 if (
645 isinstance(retry_e, http.HTTPError)
646 and getattr(retry_e, "status_code", None) == 404
647 ):
648 if _is_no_reels_found_404(retry_e):
649 superseded_failures += [e, retry_e]
650 else:
651 primary_error = retry_e
652 data = {"reels": []}
653 else:
654 _log(f"IG search retry failed: {retry_e}")
655 return _search_error(retry_e)
656 elif getattr(e, "status_code", None) == 404:
657 # Only the documented no-results payload is a clean miss. Other
658 # 404s remain errors if the independent Google fallback is empty.
659 if _is_no_reels_found_404(e):
660 superseded_failures.append(e)
661 else:
662 primary_error = e
663 data = {"reels": []}
664 else:
665 _log(f"ScrapeCreators error: {e}")
666 return _search_error(e)
667 except Exception as e:
668 _log(f"ScrapeCreators error: {e}")
669 return _search_error(e)
670 reels_failures[:] = [f for f in reels_failures if f not in superseded_failures]
671
672 # Items are in the 'reels' array (ScrapeCreators v2 response)
673 raw_items = data.get("reels") or data.get("items") or data.get("data") or []
674
675 used_google_fallback = not raw_items
676 fallback_errors: list[tuple[str, str]] = []
677 if used_google_fallback:
678 if primary_error:
679 _log("IG reels search returned 404; trying Google Search fallback")
680 else:
681 _log("IG reels search returned no results; trying Google Search fallback")
682 raw_items = _google_reel_fallback(
683 core_topic, depth, token, from_date, to_date,
684 _fallback_budget, _fallback_cache,
685 deadline=deadline, cancel=cancel,
686 error_out=fallback_errors,
687 )
688
689 if not raw_items and primary_error and not _budget_expired(deadline, cancel):
690 _log(f"Google Instagram fallback returned no reels: {primary_error}")
691 detail = f"{type(primary_error).__name__}: {primary_error}"
692 if fallback_errors:
693 detail += f"; {fallback_errors[0][0]}"
694 states = [primary_error.outcome_state, *(state for _, state in fallback_errors)]
695 return {"items": [], "error": detail,
696 "_error_state": min(states, key=lambda state: health.FAILURE_SPECIFICITY.get(state, 9))}
697
698 # Limit to configured count
699 raw_items = raw_items[:config["results_per_page"]]
700
701 # Parse items
702 items = _parse_items(raw_items, core_topic)
703
704 # Hard date filter
705 in_range = [i for i in items if i["date"] and from_date <= i["date"] <= to_date]
706 out_of_range = len(items) - len(in_range)
707 if used_google_fallback:
708 items = in_range
709 if out_of_range:
710 _log(f"Filtered {out_of_range} Google reels outside date range")
711 elif in_range:
712 items = in_range
713 if out_of_range:
714 _log(f"Filtered {out_of_range} reels outside date range")
715 else:
716 _log(f"No reels within date range, keeping all {len(items)}")
717
718 # Sort by views descending
719 items.sort(key=lambda x: x.get("engagement", {}).get("views") or 0, reverse=True)
720
721 _log(f"Found {len(items)} Instagram reels")
722 if _budget_expired(deadline, cancel):
723 return {"items": items, "error": RESEARCH_TIMEOUT}
724 if not items and fallback_errors:
725 detail, state = fallback_errors[0]
726 return {"items": [], "error": detail, "_error_state": state, "_discovery_only_error": True}
727 return {"items": items}
728
729
730 def fetch_captions(
731 video_items: List[Dict[str, Any]],
732 token: str,
733 depth: str = "default",
734 timeout: Optional[float] = None,
735 config: Optional[Dict[str, Any]] = None,
736 *,
737 deadline: float | None = None,
738 cancel: threading.Event | None = None,
739 ) -> Dict[str, str]:
740 """Fetch transcripts for top N Instagram reels via ScrapeCreators.
741
742 Strategy:
743 1. Use the 'text' field (caption) as baseline
744 2. For top N, call /v2/instagram/media/transcript for spoken-word captions
745
746 Args:
747 video_items: Items from search_instagram()
748 token: ScrapeCreators API key
749 depth: Depth level for caption limit
750 timeout: Optional per-request transcript timeout in seconds. When
751 None, resolves from LAST30DAYS_TRANSCRIPT_TIMEOUT (env or
752 config), defaulting to DEFAULT_TRANSCRIPT_TIMEOUT (30s).
753 config: Optional config dict (from env.get_config()) used as a
754 fallback source for LAST30DAYS_TRANSCRIPT_TIMEOUT when the
755 value is not exported in os.environ.
756
757 Returns:
758 Dict mapping video_id -> caption text (truncated to 500 words)
759 """
760 depth_cfg = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
761 max_captions = depth_cfg["max_captions"]
762 transcript_timeout = _resolve_transcript_timeout(timeout, config)
763
764 if not video_items or not token:
765 return {}
766
767 top_items = video_items[:max_captions]
768 _log(f"Enriching captions for {len(top_items)} reels")
769
770 captions = {}
771
772 # First pass: use text field as caption (always available, free)
773 for item in top_items:
774 vid = item["video_id"]
775 text = item.get("text", "")
776 if text:
777 words = text.split()
778 if len(words) > CAPTION_MAX_WORDS:
779 text = ' '.join(words[:CAPTION_MAX_WORDS]) + '...'
780 captions[vid] = text
781
782 # Second pass: try to get spoken-word transcripts (1 credit each)
783 for item in top_items:
784 if _budget_expired(deadline, cancel):
785 break
786 vid = item["video_id"]
787 url = item.get("url", "")
788 if not url:
789 continue
790 try:
791 # Isolate transcript fetch errors from the pipeline-level
792 # capture_failures() context so an individual reel's 400 doesn't
793 # poison the entire source outcome (#829).
794 with http.capture_failures() as _tf:
795 data = http.get(
796 f"{_sc_base()}/v2/instagram/media/transcript",
797 params={"url": url},
798 headers=http.scrapecreators_headers(token),
799 retries=1,
800 **_request_options(transcript_timeout, deadline, cancel),
801 )
802 transcripts = data.get("transcripts") or []
803 if transcripts and isinstance(transcripts, list):
804 transcript_text = " ".join(
805 t.get("text", "") for t in transcripts
806 if isinstance(t, dict) and t.get("text")
807 )
808 if transcript_text:
809 words = transcript_text.split()
810 if len(words) > CAPTION_MAX_WORDS:
811 transcript_text = ' '.join(words[:CAPTION_MAX_WORDS]) + '...'
812 captions[vid] = transcript_text
813 item["caption_is_transcript"] = True
814 except Exception as e:
815 _log(f"Transcript fetch failed for {vid}: {e}")
816
817 got = sum(1 for v in captions.values() if v)
818 _log(f"Got captions for {got}/{len(top_items)} reels")
819 return captions
820
821
822 def search_and_enrich(
823 topic: str,
824 from_date: str,
825 to_date: str,
826 depth: str = "default",
827 token: str = None,
828 ig_creators: List[str] | None = None,
829 config: Dict[str, Any] | None = None,
830 *,
831 deadline: float | None = None,
832 cancel: threading.Event | None = None,
833 ) -> Dict[str, Any]:
834 """Full Instagram search: find reels, then fetch captions for top results.
835
836 Uses expand_instagram_queries() to generate multiple search queries,
837 runs ScrapeCreators for each, and merges/deduplicates results by video ID.
838 Falls back to keyless web discovery + yt-dlp when the key is missing or 402s.
839
840 Args:
841 topic: Search topic (raw topic, not planner's narrowed query)
842 from_date: Start date (YYYY-MM-DD)
843 to_date: End date (YYYY-MM-DD)
844 depth: 'quick', 'default', or 'deep'
845 token: ScrapeCreators API key
846 ig_creators: Optional list of Instagram creator handles to fetch reels from
847 config: Optional env config (discovery keys for the OSS fallback)
848 deadline: Shared monotonic deadline for search and enrichment
849 cancel: Optional research cancellation event
850
851 Returns:
852 Dict with 'items' list. Each item has a 'caption_snippet' field.
853 """
854 from . import shortform_oss
855
856 core_topic = _extract_core_subject(topic)
857 seen_ids: Set[str] = set()
858 items: List[Dict[str, Any]] = []
859 last_error = None
860 query_errors: list[tuple[str, str]] = []
861
862 # Step 0: Creator reels (high-signal, runs first)
863 if ig_creators and token:
864 for creator in ig_creators:
865 if _budget_expired(deadline, cancel):
866 break
867 raw_items = _user_reels(creator, token, deadline=deadline, cancel=cancel)
868 parsed = _parse_items(raw_items, core_topic)
869 for item in parsed:
870 vid = item.get("video_id", "")
871 if vid and vid not in seen_ids:
872 seen_ids.add(vid)
873 items.append(item)
874
875 # Step 1: Multi-query keyword search — run ScrapeCreators for each expanded
876 # query. Without a token every call would just fail with "No
877 # SCRAPECREATORS_API_KEY configured", so skip straight to the OSS fallback
878 # (mirrors tiktok.search_and_enrich's ``if token:`` guard).
879 if token:
880 queries = expand_instagram_queries(topic, depth)
881 fallback_pages, fallback_posts = GOOGLE_FALLBACK_BUDGETS.get(
882 depth, GOOGLE_FALLBACK_BUDGETS["default"]
883 )
884 fallback_cache: dict[str, dict[str, Any]] = {}
885 for index, q in enumerate(queries):
886 if _budget_expired(deadline, cancel):
887 break
888 query_count = len(queries)
889 query_budget = {
890 "pages": fallback_pages // query_count
891 + (1 if index < fallback_pages % query_count else 0),
892 "posts": fallback_posts // query_count
893 + (1 if index < fallback_posts % query_count else 0),
894 }
895 search_result = search_instagram(
896 q, from_date, to_date, depth, token,
897 _fallback_budget=query_budget, _fallback_cache=fallback_cache,
898 deadline=deadline, cancel=cancel,
899 )
900 if search_result.get("error"):
901 error = search_result["error"]
902 state = search_result.get("_error_state") or http.classify_failure(message=error)
903 query_errors.append((error, state))
904 if not search_result.get("_discovery_only_error"):
905 last_error = error
906 for item in search_result.get("items", []):
907 vid = item.get("video_id", "")
908 if vid and vid not in seen_ids:
909 seen_ids.add(vid)
910 items.append(item)
911
912 # Sort merged results by views descending
913 items.sort(key=lambda x: x.get("engagement", {}).get("views") or 0, reverse=True)
914
915 if not items and query_errors:
916 last_error = min(
917 reversed(query_errors),
918 key=lambda error: health.FAILURE_SPECIFICITY.get(error[1], 9),
919 )[0]
920 if _budget_expired(deadline, cancel):
921 last_error = RESEARCH_TIMEOUT
922
923 # OSS fallback: web discovery + yt-dlp when the key is missing or credits
924 # are exhausted. Bounded by the same deadline/cancel as the paid path.
925 from_oss = False
926 if not items and (not token or shortform_oss.credits_exhausted(last_error)):
927 cfg = config
928 if cfg is None:
929 from . import env as envmod
930 cfg = envmod.get_config()
931 oss = shortform_oss.search(
932 "instagram", topic, from_date, to_date, depth, cfg,
933 deadline=deadline, cancel=cancel,
934 )
935 items = oss.get("items") or []
936 from_oss = bool(items)
937 if from_oss:
938 last_error = None
939 elif not token or not last_error:
940 # No paid loop ran (or produced nothing to say): a fallback
941 # failure must surface, not hide behind a budget-stop message.
942 # With a token, the ScrapeCreators error keeps priority — it is
943 # the root cause the fallback just failed to rescue.
944 last_error = oss.get("error") or last_error
945
946 if not items:
947 return {"items": [], "error": last_error}
948
949 # Step 2: Fetch captions for top N. OSS items already carry
950 # caption_snippet from the video description and spend no credits.
951 if not from_oss:
952 captions = fetch_captions(items, token, depth, deadline=deadline, cancel=cancel)
953
954 # Step 3: Attach captions to items
955 for item in items:
956 vid = item["video_id"]
957 caption = captions.get(vid)
958 if caption:
959 item["caption_snippet"] = caption
960
961 if _budget_expired(deadline, cancel):
962 last_error = RESEARCH_TIMEOUT
963 return {"items": items, "error": last_error}
964
965
966 def parse_instagram_response(response: Dict[str, Any]) -> List[Dict[str, Any]]:
967 """Parse Instagram search response to normalized format.
968
969 Returns:
970 List of item dicts ready for normalization.
971 """
972 return response.get("items", [])
973
974
975 # ---------------------------------------------------------------------------
976 # Comments (ScrapeCreators, opt-in via INCLUDE_SOURCES=instagram_comments)
977 # ---------------------------------------------------------------------------
978
979
980 def _ig_total_engagement(item: Dict[str, Any]) -> int:
981 """Sum an Instagram item's engagement for picking which posts to enrich."""
982 eng = item.get("engagement", {}) or {}
983 return (eng.get("views") or 0) + (eng.get("likes") or 0) + (eng.get("comments") or 0)
984
985
986 def enrich_with_comments(
987 items: List[Dict[str, Any]],
988 token: str,
989 max_posts: int = 3,
990 max_comments: int = 5,
991 *,
992 deadline: float | None = None,
993 cancel: threading.Event | None = None,
994 ) -> List[Dict[str, Any]]:
995 """Enrich top Instagram posts with comment data from ScrapeCreators.
996
997 Mirrors ``tiktok.enrich_with_comments`` / ``youtube_yt.enrich_with_comments``:
998 for the top N posts by engagement, fetch comments and attach them as a
999 ``top_comments`` field (highest-liked first). Failures never crash the run.
1000 """
1001 if not items or not token or max_posts <= 0 or _budget_expired(deadline, cancel):
1002 return items
1003
1004 ranked = sorted(items, key=_ig_total_engagement, reverse=True)
1005 top_items = ranked[:max_posts]
1006 _log(f"Enriching comments for {len(top_items)} Instagram posts")
1007
1008 def _enrich_one(item: dict) -> list[dict]:
1009 post_url = item.get("url", "")
1010 if not post_url:
1011 return []
1012 try:
1013 return _fetch_post_comments(
1014 post_url, token, max_comments, deadline=deadline, cancel=cancel,
1015 creator=str(item.get("author_name") or ""),
1016 )
1017 except Exception as exc:
1018 _log(f"Comment enrichment failed for {post_url}: {exc}")
1019 return []
1020
1021 enriched_count = 0
1022 executor = ThreadPoolExecutor(max_workers=min(4, len(top_items)))
1023 try:
1024 futures = {http.submit_with_context(executor, _enrich_one, item): item for item in top_items}
1025 pending = set(futures)
1026 while pending:
1027 remaining = 0.05 if deadline is None else max(0, min(0.05, deadline - time.monotonic()))
1028 done, pending = wait(pending, timeout=remaining, return_when=FIRST_COMPLETED)
1029 for future in done:
1030 comments = future.result()
1031 if comments:
1032 futures[future]["top_comments"] = comments
1033 enriched_count += 1
1034 if _budget_expired(deadline, cancel):
1035 break
1036 finally:
1037 executor.shutdown(wait=False, cancel_futures=True)
1038
1039 _log(f"Enriched {enriched_count}/{len(top_items)} posts with comments")
1040 return items
1041
1042
1043 def _fetch_post_comments(
1044 post_url: str,
1045 token: str,
1046 max_comments: int = 5,
1047 *,
1048 deadline: float | None = None,
1049 cancel: threading.Event | None = None,
1050 creator: str = "",
1051 ) -> List[Dict[str, Any]]:
1052 """Fetch comments for a single Instagram post/reel via ScrapeCreators.
1053
1054 SC endpoint: GET /v2/instagram/post/comments?url=<post_or_reel_url>
1055 Response shape: { comments: [{text, comment_like_count, child_comment_count,
1056 created_at, user{username, ...}}], cursor }
1057
1058 Returns:
1059 List of comment dicts with author, text, comment_like_count (likes), date,
1060 highest-liked first. Empty list on any error — never crashes the pipeline.
1061 """
1062 if _budget_expired(deadline, cancel):
1063 return []
1064 try:
1065 data = http.get(
1066 f"{_sc_base()}/v2/instagram/post/comments",
1067 params={"url": post_url},
1068 headers=http.scrapecreators_headers(token),
1069 retries=2,
1070 **_request_options(30, deadline, cancel),
1071 )
1072 except Exception as exc:
1073 _log(f"Comment fetch error for {post_url}: {exc}")
1074 return []
1075
1076 raw_comments = data.get("comments") or data.get("data") or []
1077 # Sort by like count desc so normalize sees the highest-signal first.
1078 raw_comments = sorted(
1079 raw_comments,
1080 key=lambda c: c.get("comment_like_count", 0) or 0,
1081 reverse=True,
1082 )
1083 out: List[Dict[str, Any]] = []
1084 for c in raw_comments[:max_comments]:
1085 if not isinstance(c, dict):
1086 continue
1087 text = c.get("text") or ""
1088 if not text:
1089 continue
1090 user = c.get("user") if isinstance(c.get("user"), dict) else {}
1091 author = user.get("username") or ""
1092 created_at = c.get("created_at") or ""
1093 # created_at is ISO 8601 (e.g. "2026-07-04T14:27:58.000Z"); take the date.
1094 date_str = created_at[:10] if isinstance(created_at, str) and len(created_at) >= 10 else ""
1095 out.append({
1096 "author": author,
1097 "text": text[:400],
1098 "comment_like_count": c.get("comment_like_count", 0) or 0,
1099 "date": date_str,
1100 })
1101 # Whether the post's own creator wrote this. Both are handles, a stable
1102 # identifier, so they compare exactly. With no handle on either side
1103 # the key is left out: unknown.
1104 handle = str(user.get("username") or "").strip().lstrip("@").lower()
1105 owner = str(creator or "").strip().lstrip("@").lower()
1106 if handle and owner:
1107 out[-1]["is_uploader"] = handle == owner
1108 return out
1109
1109 lines PYTHON