返回 last30days-skill
meta_ads.py
根目录 / skills / last30days / scripts / lib / meta_ads.py
1 """Meta Ad Library source for last30days.
2
3 What a brand is *paying* to say this month, next to what everyone else is
4 saying about it in the other sources. Discovery resolves the advertiser page
5 behind a brand topic, enrichment pulls that page's creatives, and the newest
6 video creatives get their spoken script transcribed.
7
8 Two-stage shape, following the Amazon buyer-signal lane:
9
10 1. **Discovery** -- one keyword ad search resolves which advertiser page the
11 topic actually belongs to. Ad-search-first, because the company-search
12 endpoint misses brands whose pages carry product names rather than the
13 corporate name. Company search is the fallback; an explicit page override
14 skips both.
15 2. **Enrichment** -- the resolved page's ads inside the run window, cursor
16 paginated under a depth cap, deduped to distinct creatives, then a small
17 capped set of transcripts.
18
19 Metering: one credit per request regardless of records returned, so the caps
20 below bound paid *requests*, not records. A default-depth run is 1 discovery
21 + at most 1 company search + up to 2 enrichment pages + up to 3 transcripts,
22 so at most 7 credits. Every cap here counts requests issued, never results
23 obtained: an upstream that returns nothing still bills for being asked.
24
25 Two live-verified quirks drive the code:
26
27 * The keyword endpoint returns its rows under ``searchResults`` while the
28 company endpoint returns the same shape under ``results``. Both are read
29 tolerantly rather than by endpoint.
30 * ``status`` defaults to ACTIVE upstream. The window fetch overrides it, or a
31 creative that launched inside the window and already ended -- a one-week
32 promo push, exactly the signal this source exists for -- never comes back.
33
34 Meta exposes ``reach_estimate`` and ``spend`` only for political and issue
35 ads; both are null on commercial ads, so items carry no engagement beyond
36 the creative variant count.
37
38 Requires SCRAPECREATORS_API_KEY.
39 """
40
41 from __future__ import annotations
42
43 import datetime
44 import re
45 import time
46 from typing import Any, Dict, List, Optional, Tuple
47
48 from . import dates, health, http, log
49
50 _DEFAULT_SC_BASE = "https://api.scrapecreators.com/v1/facebook/adLibrary"
51 SC_BASE = _DEFAULT_SC_BASE
52
53 _DEFAULT_SEARCH_ADS_URL = f"{_DEFAULT_SC_BASE}/search/ads"
54 _DEFAULT_SEARCH_COMPANIES_URL = f"{_DEFAULT_SC_BASE}/search/companies"
55 _DEFAULT_COMPANY_ADS_URL = f"{_DEFAULT_SC_BASE}/company/ads"
56 _DEFAULT_AD_TRANSCRIPT_URL = f"{_DEFAULT_SC_BASE}/ad/transcript"
57
58 SEARCH_ADS_URL = _DEFAULT_SEARCH_ADS_URL
59 SEARCH_COMPANIES_URL = _DEFAULT_SEARCH_COMPANIES_URL
60 COMPANY_ADS_URL = _DEFAULT_COMPANY_ADS_URL
61 AD_TRANSCRIPT_URL = _DEFAULT_AD_TRANSCRIPT_URL
62
63
64 def _sc_base() -> str:
65 if SC_BASE != _DEFAULT_SC_BASE:
66 return SC_BASE
67 from . import env
68 return f"{env.get_scrapecreators_base_url()}/v1/facebook/adLibrary"
69
70
71 def _search_ads_url() -> str:
72 if SEARCH_ADS_URL != _DEFAULT_SEARCH_ADS_URL:
73 return SEARCH_ADS_URL
74 return f"{_sc_base()}/search/ads"
75
76
77 def _search_companies_url() -> str:
78 if SEARCH_COMPANIES_URL != _DEFAULT_SEARCH_COMPANIES_URL:
79 return SEARCH_COMPANIES_URL
80 return f"{_sc_base()}/search/companies"
81
82
83 def _company_ads_url() -> str:
84 if COMPANY_ADS_URL != _DEFAULT_COMPANY_ADS_URL:
85 return COMPANY_ADS_URL
86 return f"{_sc_base()}/company/ads"
87
88
89 def _ad_transcript_url() -> str:
90 if AD_TRANSCRIPT_URL != _DEFAULT_AD_TRANSCRIPT_URL:
91 return AD_TRANSCRIPT_URL
92 return f"{_sc_base()}/ad/transcript"
93
94 DEFAULT_COUNTRY = "US"
95
96 # Discovery only needs live creatives to identify the advertiser, and asking
97 # for live ones keeps that call cheap and current. The window fetch is the
98 # opposite case: see the module docstring.
99 DISCOVERY_STATUS = "ACTIVE"
100 ENRICHMENT_STATUS = "ALL"
101
102 # Discovery deliberately uses the endpoint's default (unordered) search type.
103 # Exact-phrase mode narrows so hard that a brand advertising under a product
104 # name disappears from its own search.
105 DISCOVERY_SEARCH_TYPE = "keyword_unordered"
106
107 DEPTH_CONFIG: Dict[str, Dict[str, int]] = {
108 "quick": {"pages": 1, "transcripts": 0},
109 "default": {"pages": 2, "transcripts": 3},
110 "deep": {"pages": 4, "transcripts": 5},
111 }
112
113 # Whole-lane wall clock. Pagination bounds the request COUNT, not time, so
114 # each request is additionally clamped to what is left of this.
115 LANE_BUDGET_SECONDS = 120.0
116 REQUEST_TIMEOUT = 30.0
117 MIN_REQUEST_TIMEOUT = 5.0
118
119 # Transcripts are slower than list calls: the live median was well over 15s.
120 TRANSCRIPT_TIMEOUT = 45.0
121
122 # Credential- or account-scoped failures. Retrying the next call would fail
123 # identically, and retrying a 429 deepens the limit already being hit.
124 FATAL_STATUS_CODES = frozenset({401, 402, 403, 429})
125
126 # Shortest token that may establish a name match. Below this, a topic ending
127 # in a short word ("... AI") matches every advertiser that shares it: a live
128 # probe returned 1,467 unrelated advertisers for one such topic.
129 MIN_MATCH_TOKEN = 4
130
131 # Absolute pagination bound, independent of the depth cap.
132 MAX_PAGES_HARD = 10
133
134 # Resolution outcomes carried on the tally so the footer can tell an honest
135 # empty from a wrong-entity match.
136 RESOLVED = "resolved"
137 UNRESOLVED = "unresolved"
138 NO_CANDIDATES = "no_candidates"
139
140 _TOKEN_RE = re.compile(r"[a-z0-9]+")
141
142 # A promo code is only recognized when the copy actually calls it one. Model
143 # numbers and SKUs ("E-325") share the token shape and must not match.
144 _PROMO_RE = re.compile(
145 r"\b(?:promo|discount|coupon)?\s*code\s*[:\-]?\s*([A-Za-z0-9]{4,12})\b",
146 re.IGNORECASE,
147 )
148
149
150 def _log(msg: str) -> None:
151 log.source_log("Meta Ads", msg, tty_only=False)
152
153
154 # --------------------------------------------------------------- matching
155
156
157 def _tokens(text: str) -> List[str]:
158 return _TOKEN_RE.findall(str(text or "").lower())
159
160
161 def _match_tokens(text: str) -> set[str]:
162 """Tokens long enough to establish a match.
163
164 Deliberately not ``relevance.tokenize``: that helper expands short tokens
165 through a synonym table, which is right for scoring body text and wrong
166 here -- it would let an advertiser sharing one short word pass as the
167 topic's own brand.
168 """
169 return {tok for tok in _tokens(text) if len(tok) >= MIN_MATCH_TOKEN}
170
171
172 def _compact(text: str) -> str:
173 """Normalized form for exact-identity comparison ("Bright iQ" -> "brightiq")."""
174 return "".join(_tokens(text))
175
176
177 # How an advertiser page name matched the topic, strongest first. Resolution
178 # prefers a whole tier over ad volume: volume measures how much a page is
179 # spending, never whether it is the right company.
180 MATCH_EXACT = "exact"
181 MATCH_TOKEN = "token"
182 MATCH_CONTAINED = "contained"
183 MATCH_NONE = ""
184
185
186 def match_strength(topic: str, name: str) -> str:
187 """How strongly an advertiser page name belongs to the topic.
188
189 Three tiers, because they are not equally trustworthy:
190
191 * ``exact`` -- the normalized names are the same string. Unambiguous.
192 * ``token`` -- they share a whole word of at least ``MIN_MATCH_TOKEN``.
193 * ``contained`` -- a whole word of one appears inside the other's
194 normalized form. This is what lets an umbrella topic find a brand
195 advertising under product-line page names, and it is also the weakest
196 signal: substring containment cannot distinguish a product line from a
197 coincidence, so a short brand can be found inside an unrelated longer
198 word. It is accepted only when no stronger tier matched, and the footer
199 says when resolution rested on it.
200
201 A topic whose every word is shorter than the token floor (an initialism
202 brand) has no usable tokens at all, so it can only ever match exactly.
203 Returning False for it outright would make such a brand unresolvable even
204 against its own identically-named page.
205 """
206 topic_compact = _compact(topic)
207 name_compact = _compact(name)
208 if not topic_compact or not name_compact:
209 return MATCH_NONE
210 if topic_compact == name_compact:
211 return MATCH_EXACT
212 topic_tokens = _match_tokens(topic)
213 name_tokens = _match_tokens(name)
214 if not topic_tokens or not name_tokens:
215 return MATCH_NONE
216 if topic_tokens & name_tokens:
217 return MATCH_TOKEN
218 if any(tok in name_compact for tok in topic_tokens):
219 return MATCH_CONTAINED
220 if any(tok in topic_compact for tok in name_tokens):
221 return MATCH_CONTAINED
222 return MATCH_NONE
223
224
225 def names_match(topic: str, name: str) -> bool:
226 """True when an advertiser page name plausibly belongs to the topic."""
227 return match_strength(topic, name) != MATCH_NONE
228
229
230 def _group_advertisers(rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
231 """Collapse ad rows into advertiser pages, busiest first."""
232 groups: Dict[str, Dict[str, Any]] = {}
233 for row in rows:
234 if not isinstance(row, dict):
235 continue
236 page_id = str(row.get("page_id") or "").strip()
237 if not page_id:
238 continue
239 name = str(row.get("page_name") or "").strip()
240 group = groups.setdefault(page_id, {"id": page_id, "name": name, "ads": 0})
241 group["ads"] += 1
242 if not group["name"] and name:
243 group["name"] = name
244 return sorted(
245 groups.values(), key=lambda g: (-g["ads"], g["name"].lower(), g["id"])
246 )
247
248
249 def _token_spread(pages: List[Dict[str, Any]]) -> Dict[str, int]:
250 """How many distinct advertisers in this result set carry each word."""
251 spread: Dict[str, int] = {}
252 for page in pages:
253 for token in _match_tokens(page["name"]):
254 spread[token] = spread.get(token, 0) + 1
255 return spread
256
257
258 def _match_rarity(topic: str, name: str, spread: Dict[str, int]) -> int:
259 """How distinctive the word this page matched on is. Lower is better.
260
261 A word carried by many advertisers in the same result set is a category,
262 not an identity: "kitchen" sits in every kitchen brand's name, so matching
263 on it resolves whoever is advertising hardest rather than the right
264 company. A word carried by one advertiser names that advertiser.
265
266 Rarity is measured against the candidates themselves rather than a fixed
267 stopword list, because the same word can be a category in one search and
268 the brand's own name in another. Counting alone would not separate those:
269 an umbrella brand's name also appears across several of its product-line
270 pages. What distinguishes them is that a *rarer* alternative exists --
271 "Acme Kitchen" carries "acme" as well, while "Kitchen World" carries only
272 the shared word -- so the best available word decides, not the fact of
273 sharing.
274 """
275 topic_tokens = _match_tokens(topic)
276 name_tokens = _match_tokens(name)
277 shared = topic_tokens & name_tokens
278 if not shared:
279 # Containment match: score the word that did the containing.
280 shared = {
281 tok for tok in topic_tokens if tok in _compact(name)
282 } | {tok for tok in name_tokens if tok in _compact(topic)}
283 if not shared:
284 return 0
285 return min(spread.get(tok, 1) for tok in shared)
286
287
288 def _matched_tokens(topic: str, name: str) -> set[str]:
289 """Topic words that actually took part in the match.
290
291 For a containment match the participating topic word has to be identified,
292 not assumed: crediting every topic word whenever any page word appears
293 somewhere in the topic would let "Grill World" claim "best Acme grills" on
294 the strength of "grill", carrying the brand word along with it.
295 """
296 topic_tokens = _match_tokens(topic)
297 name_tokens = _match_tokens(name)
298 shared = topic_tokens & name_tokens
299 if shared:
300 return shared
301 name_compact = _compact(name)
302 topic_compact = _compact(topic)
303 matched = {tok for tok in topic_tokens if tok in name_compact}
304 for name_token in name_tokens:
305 if name_token in topic_compact:
306 matched |= {
307 tok
308 for tok in topic_tokens
309 if name_token in tok or tok in name_token
310 }
311 return matched
312
313
314 def _head_token(topic: str) -> str:
315 """The leading word of the topic's primary entity.
316
317 Brand names lead and category words trail: in "Acme Kitchen" the brand is
318 "acme" and "kitchen" says what it sells. This mirrors the entity-grounding
319 rule the engine already applies elsewhere, where grounding keys on the head
320 token of the primary entity because trailing words are usually descriptors.
321
322 A research topic does not always open with the brand, though: "best Acme
323 grills" leads with an intent modifier, and treating "best" as the identity
324 would reject the brand's own page. So the head is taken from the primary
325 entity rather than the raw phrase, skipping the same descriptor vocabulary
326 the engine's other adapters strip before searching.
327 """
328 from .query import NOISE_WORDS
329
330 eligible = [tok for tok in _tokens(topic) if len(tok) >= MIN_MATCH_TOKEN]
331 for token in eligible:
332 if token not in NOISE_WORDS:
333 return token
334 # Every word was a descriptor, so there is no identity to key on; fall
335 # back to the leading word rather than matching anything at all.
336 return eligible[0] if eligible else ""
337
338
339 def _name_covered_by_topic(topic: str, name: str) -> bool:
340 """True when the topic spells out this advertiser's whole name.
341
342 Whole means whole. Every word of the page name must appear in the topic as
343 a word, short ones included and without dissolving word boundaries: an
344 advertiser called "Acme AI" is not named by a topic about "Acme Kitchen"
345 just because the two share "acme", and "Cart Wheel" is not named by "Acme
346 Cartwheel" just because its letters appear inside a longer word. Ignoring
347 either would let a fragment of one company's name stand in for another's.
348
349 The name must also account for more than a single word of the topic, unless
350 it accounts for the topic entirely, so a page called just "Kitchen" cannot
351 claim a topic about "Acme Kitchen" on the category word alone.
352 """
353 topic_words = set(_tokens(topic))
354 name_words = set(_tokens(name))
355 if not topic_words or not name_words:
356 return False
357 if not name_words <= topic_words:
358 return False
359 topic_tokens = _match_tokens(topic)
360 covered = topic_tokens & name_words
361 return len(covered) >= 2 or (bool(covered) and covered == topic_tokens)
362
363
364 def _is_category_only(topic: str, name: str, spread: Dict[str, int]) -> bool:
365 """True when this page shares some of the topic's words but is not its brand.
366
367 A single-word topic is its own identity, so any page carrying that word --
368 including an umbrella brand's product-line page -- is the brand.
369
370 A multi-word topic has to be matched as a name, not by one of its words. The
371 page qualifies when the topic spells its name out, or when it carries every
372 identifying word of the topic. Sharing only one of them is what a category
373 lookalike and a same-word different-company both look like, and neither
374 should have another firm's paid creatives attributed to it.
375 """
376 matched = _matched_tokens(topic, name)
377 if not matched:
378 return True
379 topic_tokens = _match_tokens(topic)
380 if len(topic_tokens) <= 1:
381 return False
382 if _name_covered_by_topic(topic, name):
383 return False
384 name_words = set(_tokens(name))
385 name_compact = _compact(name)
386 covered = {
387 token
388 for token in topic_tokens
389 if token in name_words or token in name_compact
390 }
391 return covered != topic_tokens
392
393
394 def resolve_page(
395 topic: str, rows: List[Dict[str, Any]]
396 ) -> Tuple[Optional[Dict[str, Any]], List[str], str, str]:
397 """Pick the advertiser page for a topic from a list of ad rows.
398
399 Strength decides before volume. Ad count only breaks ties *inside* the
400 strongest tier that matched, because volume measures how much a page is
401 spending and says nothing about whether it is the right company: a reseller
402 or outlet page running more ads than the brand it resells would otherwise
403 claim the brand's own topic.
404
405 Returns ``(page, runner_up_names, top_unmatched_name, strength)``. ``page``
406 is None when nothing matched, and ``top_unmatched_name`` is empty only when
407 no rows came back at all, which is what separates "wrong advertiser" from
408 "nothing there". ``strength`` is the tier that won, so the caller can tell
409 the reader when resolution rested on the weakest one.
410 """
411 ordered = _group_advertisers(rows)
412 spread = _token_spread(ordered)
413 scored = [(match_strength(topic, g["name"]), g) for g in ordered]
414 for tier in (MATCH_EXACT, MATCH_TOKEN, MATCH_CONTAINED):
415 group = [
416 g
417 for strength, g in scored
418 if strength == tier
419 # An exact normalized-name match is unambiguous, so it is never
420 # second-guessed: the guard below exists for the weaker tiers,
421 # where a shared word is the only thing holding the match up.
422 and (tier == MATCH_EXACT or not _is_category_only(topic, g["name"], spread))
423 ]
424 if not group:
425 continue
426 # Within a tier: the most distinctive matched word first, then the
427 # page accounting for the most of the topic, and only then ad volume.
428 # Two pages can share a brand word while one also matches the rest of
429 # the topic, and that one is the better answer however much the other
430 # is spending.
431 group.sort(
432 key=lambda g: (
433 _match_rarity(topic, g["name"], spread),
434 -len(_matched_tokens(topic, g["name"])),
435 -g["ads"],
436 g["id"],
437 )
438 )
439 winner = group[0]
440 # Runner-ups come from every tier that matched at all: a weaker
441 # same-name-family page is exactly what a reader checking a
442 # questionable resolution wants to see.
443 runner_ups = [
444 g["name"]
445 for strength, g in scored
446 if strength != MATCH_NONE and g["id"] != winner["id"]
447 ][:2]
448 return winner, runner_ups, "", tier
449 return None, [], (ordered[0]["name"] if ordered else ""), MATCH_NONE
450
451
452 # ----------------------------------------------------------- ad row fields
453
454
455 def _envelope_rows(response: Any) -> List[Dict[str, Any]]:
456 """Read ad rows from either endpoint's envelope."""
457 if not isinstance(response, dict):
458 return []
459 for key in ("searchResults", "results", "ads", "data"):
460 value = response.get(key)
461 if isinstance(value, list):
462 return [row for row in value if isinstance(row, dict)]
463 return []
464
465
466 def _envelope_total(response: Any) -> int:
467 if not isinstance(response, dict):
468 return 0
469 try:
470 return int(response.get("searchResultsCount") or 0)
471 except (TypeError, ValueError):
472 return 0
473
474
475 def _envelope_cursor(response: Any) -> Optional[str]:
476 if not isinstance(response, dict):
477 return None
478 cursor = response.get("cursor")
479 if isinstance(cursor, (str, int)) and str(cursor).strip():
480 return str(cursor)
481 return None
482
483
484 def _snapshot(row: Dict[str, Any]) -> Dict[str, Any]:
485 snapshot = row.get("snapshot")
486 return snapshot if isinstance(snapshot, dict) else {}
487
488
489 def _body_text(snapshot: Dict[str, Any]) -> str:
490 body = snapshot.get("body")
491 if isinstance(body, dict):
492 return str(body.get("text") or "").strip()
493 return str(body or "").strip()
494
495
496 def _cards(snapshot: Dict[str, Any]) -> List[Dict[str, Any]]:
497 cards = snapshot.get("cards")
498 if not isinstance(cards, list):
499 return []
500 return [card for card in cards if isinstance(card, dict)]
501
502
503 def launch_date(row: Dict[str, Any]) -> Optional[str]:
504 """YYYY-MM-DD the creative started running, or None."""
505 raw = str(row.get("start_date_string") or "")[:10]
506 try:
507 datetime.date.fromisoformat(raw)
508 return raw
509 except ValueError:
510 pass
511 epoch = row.get("start_date")
512 if isinstance(epoch, (int, float)) and epoch > 0:
513 return dates.timestamp_to_date(epoch)
514 return None
515
516
517 def dedupe_key(row: Dict[str, Any]) -> str:
518 """Identity for one creative.
519
520 ``collation_id`` groups the variants of one creative, which is the unit a
521 reader cares about. It is frequently absent though (9 of 30 ads on one
522 live page carried none), and keying on it alone would collapse every such
523 creative into a single item.
524 """
525 collation = str(row.get("collation_id") or "").strip()
526 if collation:
527 return f"collation:{collation}"
528 return f"ad:{str(row.get('ad_archive_id') or '').strip()}"
529
530
531 def has_video(row: Dict[str, Any]) -> bool:
532 snapshot = _snapshot(row)
533 videos = snapshot.get("videos")
534 if isinstance(videos, list) and any(isinstance(v, dict) and v for v in videos):
535 return True
536 for card in _cards(snapshot):
537 if card.get("video_hd_url") or card.get("video_sd_url"):
538 return True
539 return False
540
541
542 def extract_promo_code(text: str) -> Optional[str]:
543 """Return an uppercase promo code the copy explicitly labels as one."""
544 for match in _PROMO_RE.finditer(str(text or "")):
545 token = match.group(1)
546 if token.isupper() and any(ch.isalpha() for ch in token):
547 return token
548 return None
549
550
551 def _landing_url(snapshot: Dict[str, Any]) -> str:
552 link = str(snapshot.get("link_url") or "").strip()
553 if link:
554 return link
555 for card in _cards(snapshot):
556 card_link = str(card.get("link_url") or "").strip()
557 if card_link:
558 return card_link
559 return ""
560
561
562 def _placements(row: Dict[str, Any]) -> List[str]:
563 raw = row.get("publisher_platform")
564 if not isinstance(raw, list):
565 return []
566 return [str(p).strip() for p in raw if str(p or "").strip()]
567
568
569 def _variants(row: Dict[str, Any]) -> int:
570 try:
571 count = int(row.get("collation_count") or 0)
572 except (TypeError, ValueError):
573 count = 0
574 return max(1, count)
575
576
577 def build_item(row: Dict[str, Any], page: Dict[str, Any]) -> Dict[str, Any]:
578 """Turn one ad row into a normalizer-ready item dict."""
579 snapshot = _snapshot(row)
580 body = _body_text(snapshot)
581 title = str(snapshot.get("title") or "").strip()
582 if not title:
583 title = body.split("\n", 1)[0][:140]
584 archive_id = str(row.get("ad_archive_id") or "").strip()
585 url = str(row.get("url") or "").strip()
586 if not url and archive_id:
587 url = f"https://www.facebook.com/ads/library/?id={archive_id}"
588 placements = _placements(row)
589 return {
590 "id": archive_id or dedupe_key(row),
591 "title": title,
592 "text": body,
593 "url": url,
594 "date": launch_date(row),
595 "advertiser": page.get("name") or "",
596 "page_id": page.get("id") or "",
597 "is_active": bool(row.get("is_active")),
598 "ended_on": str(row.get("end_date_string") or "")[:10] or None,
599 "display_format": str(snapshot.get("display_format") or "").strip(),
600 "cta": str(snapshot.get("cta_text") or "").strip(),
601 "landing_url": _landing_url(snapshot),
602 "placements": placements,
603 "promo_code": extract_promo_code(body),
604 "variants": _variants(row),
605 "has_video": has_video(row),
606 "transcript": "",
607 }
608
609
610 # ------------------------------------------------------------ HTTP helpers
611
612
613 class _Budget:
614 """Monotonic wall-clock budget shared by every call in one lane run."""
615
616 def __init__(self, seconds: float = LANE_BUDGET_SECONDS) -> None:
617 self.deadline = time.monotonic() + seconds
618
619 @property
620 def remaining(self) -> float:
621 return self.deadline - time.monotonic()
622
623 def exhausted(self) -> bool:
624 return self.remaining <= 0
625
626 def timeout(self, ceiling: float = REQUEST_TIMEOUT) -> float:
627 return max(MIN_REQUEST_TIMEOUT, min(ceiling, self.remaining))
628
629
630 class _Fatal(Exception):
631 """A lane-ending failure: no further calls may be made."""
632
633 def __init__(self, message: str, status: Optional[int] = None) -> None:
634 super().__init__(message)
635 self.status = status
636
637
638 class _StopFetching(Exception):
639 """Stop making calls, but keep whatever already came back.
640
641 Distinct from ``_Fatal`` on purpose. A credential or account failure
642 invalidates the lane itself, so its output is discarded. Running out of
643 wall clock, or a transient upstream failure partway through pagination,
644 only ends the *fetching*: the creatives already in hand are real evidence
645 and are reported as a partial result rather than thrown away.
646 """
647
648 def __init__(self, message: str, outcome_state: Optional[str] = None) -> None:
649 super().__init__(message)
650 self.outcome_state = outcome_state
651
652
653 def _call(
654 url: str,
655 params: Dict[str, Any],
656 token: str,
657 budget: _Budget,
658 ceiling: float = REQUEST_TIMEOUT,
659 ) -> Dict[str, Any]:
660 """One metered GET.
661
662 ``max_429_retries=0`` matters: the shared client retries a 429 twice by
663 default, which both contradicts the no-further-calls contract for a rate
664 limit and spends the lane budget sleeping between attempts.
665 """
666 if budget.exhausted():
667 raise _StopFetching("lane budget timed out (exhausted)", outcome_state=health.TIMEOUT)
668 try:
669 response = http.get(
670 url,
671 params=params,
672 headers=http.scrapecreators_headers(token),
673 timeout=budget.timeout(ceiling),
674 retries=1,
675 max_429_retries=0,
676 deadline_monotonic=budget.deadline,
677 )
678 except http.HTTPError as exc:
679 status = exc.status_code
680 message = f"HTTP {status}: {exc}" if status else str(exc)
681 if status in FATAL_STATUS_CODES:
682 # Credential- or account-scoped: every later call fails the same
683 # way, so the lane ends and keeps nothing.
684 raise _Fatal(message, status) from exc
685 if (
686 exc.outcome_state == health.TIMEOUT
687 and "timed out" not in message.lower()
688 and "timeout" not in message.lower()
689 ):
690 message = f"timed out: {message}"
691 # Anything else (a 5xx, a bad gateway partway through pagination) is
692 # about this one request. Stop fetching, but keep the creatives
693 # already retrieved rather than discarding paid-for work.
694 raise _StopFetching(message, outcome_state=exc.outcome_state) from exc
695 except Exception as exc: # noqa: BLE001 - an unclassifiable transport failure
696 raise _Fatal(f"{type(exc).__name__}: {exc}") from exc
697 return response if isinstance(response, dict) else {}
698
699
700 # ------------------------------------------------------------ lane stages
701
702
703 def _discover(
704 topic: str, country: str, token: str, budget: _Budget
705 ) -> Tuple[Optional[Dict[str, Any]], List[str], str, str, str]:
706 """Resolve the advertiser page.
707
708 Returns ``(page, runner_ups, top_unmatched, state, strength)``.
709 """
710 response = _call(
711 _search_ads_url(),
712 {
713 "query": topic,
714 "country": country,
715 "status": DISCOVERY_STATUS,
716 "search_type": DISCOVERY_SEARCH_TYPE,
717 "trim": "true",
718 },
719 token,
720 budget,
721 )
722 rows = _envelope_rows(response)
723 page, runner_ups, top, strength = resolve_page(topic, rows)
724 if page:
725 _log(
726 f"Resolved advertiser '{page['name']}' (page {page['id']}) "
727 f"from ad search by {strength} name match"
728 )
729 return page, runner_ups, "", RESOLVED, strength
730
731 companies = _call(_search_companies_url(), {"query": topic}, token, budget)
732 # Reshape company rows into the same shape resolve_page reads, so the
733 # fallback gets the identical exact-before-partial tiering. Taking the
734 # first name that merely matched would let this path resolve a lookalike
735 # the primary path would have rejected.
736 company_rows = [
737 {"page_id": str(row.get("page_id") or "").strip(),
738 "page_name": str(row.get("name") or "").strip()}
739 for row in _envelope_rows(companies)
740 if str(row.get("page_id") or "").strip()
741 ]
742 company_page, company_runner_ups, company_top, company_strength = resolve_page(
743 topic, company_rows
744 )
745 if company_page:
746 _log(
747 f"Resolved advertiser '{company_page['name']}' "
748 f"(page {company_page['id']}) from company search by "
749 f"{company_strength} name match"
750 )
751 return company_page, company_runner_ups, "", RESOLVED, company_strength
752
753 fallback_top = top or company_top
754 if not rows and not company_rows:
755 _log("No advertiser candidates returned by either search")
756 return None, [], "", NO_CANDIDATES, MATCH_NONE
757 _log(f"No advertiser matched '{topic}'; closest was '{fallback_top}'")
758 return None, [], fallback_top, UNRESOLVED, MATCH_NONE
759
760
761 def _fetch_window(
762 page: Dict[str, Any],
763 country: str,
764 from_date: str,
765 to_date: str,
766 max_pages: int,
767 token: str,
768 budget: _Budget,
769 ) -> Tuple[List[Dict[str, Any]], int, bool, str]:
770 """Cursor-paginate the page's window ads.
771
772 Returns ``(rows, endpoint_total, more_available, interruption)``, where
773 ``interruption`` is the reason fetching stopped early (empty when it ran
774 to its natural end). It is carried verbatim rather than summarized: a
775 transient upstream failure and an exhausted clock produce the same partial
776 shape, and reporting one as the other sends the reader to fix the wrong
777 thing.
778 """
779 rows: List[Dict[str, Any]] = []
780 total = 0
781 cursor: Optional[str] = None
782 prev_cursor: Optional[str] = None
783 more = False
784 interruption = ""
785 pages = min(max_pages, MAX_PAGES_HARD)
786 stop = "page cap reached"
787
788 for _ in range(pages):
789 params: Dict[str, Any] = {
790 "pageId": page["id"],
791 "country": country,
792 "status": ENRICHMENT_STATUS,
793 "start_date": from_date,
794 "end_date": to_date,
795 }
796 if cursor:
797 params["cursor"] = cursor
798 try:
799 response = _call(_company_ads_url(), params, token, budget)
800 except (_Fatal, _StopFetching) as exc:
801 if not rows:
802 raise
803 # Whatever the reason, the creatives already fetched were paid for
804 # and are valid: a rate limit or expired credential says "stop
805 # calling", not "the pages that already returned 200 were wrong".
806 stop = str(exc)
807 interruption = str(exc)
808 more = True
809 break
810 page_rows = _envelope_rows(response)
811 total = _envelope_total(response) or total
812 if not page_rows:
813 stop = "empty page"
814 break
815 rows.extend(page_rows)
816 cursor = _envelope_cursor(response)
817 if not cursor:
818 stop = "no cursor"
819 break
820 if cursor == prev_cursor:
821 stop = "cursor stopped advancing"
822 break
823 prev_cursor = cursor
824 else:
825 more = bool(cursor)
826
827 _log(f" fetched {len(rows)} ad rows of {total or len(rows)}, stopped: {stop}")
828 return rows, total, more, interruption
829
830
831 def _classify(
832 rows: List[Dict[str, Any]],
833 page: Dict[str, Any],
834 from_date: str,
835 to_date: str,
836 ) -> Tuple[List[Dict[str, Any]], int]:
837 """Split deduped rows into in-window items and a still-running tally.
838
839 The endpoint's date filter returns everything *active during* the window,
840 which on a busy page is mostly creatives launched months earlier. The
841 last-30-days signal is what launched inside it; the rest are counted so
842 the footer can say how much steady-state advertising sits behind them.
843 """
844 seen: set[str] = set()
845 items: List[Dict[str, Any]] = []
846 still_running = 0
847 for row in rows:
848 key = dedupe_key(row)
849 if key in seen:
850 continue
851 seen.add(key)
852 launched = launch_date(row)
853 if launched and from_date <= launched <= to_date:
854 items.append(build_item(row, page))
855 else:
856 still_running += 1
857 items.sort(key=lambda item: item.get("date") or "", reverse=True)
858 return items, still_running
859
860
861 def _add_transcripts(
862 items: List[Dict[str, Any]], cap: int, token: str, budget: _Budget
863 ) -> Tuple[int, str]:
864 """Transcribe the newest video creatives.
865
866 Candidates are chosen from the whole fetched set, after every page is in,
867 so a newer creative on page two is not passed over for an older one on
868 page one. Returns ``(transcribed, interruption)``.
869 """
870 if cap <= 0:
871 return 0, ""
872 transcribed = 0
873 # The cap bounds paid REQUESTS, not successes. Counting only successes
874 # would keep calling for every remaining video creative whenever the
875 # upstream has no transcript available -- each of those still costs a
876 # credit, so a page of silent video ads would blow through the run's whole
877 # documented credit ceiling while the tally still read zero.
878 candidates = [item for item in items if item.get("has_video")][:cap]
879 for item in candidates:
880 try:
881 response = _call(
882 _ad_transcript_url(),
883 {"id": item["id"]},
884 token,
885 budget,
886 ceiling=TRANSCRIPT_TIMEOUT,
887 )
888 except (_Fatal, _StopFetching) as exc:
889 return transcribed, str(exc)
890 if not response.get("transcript_available"):
891 continue
892 text = str(response.get("transcript") or "").strip()
893 if not text:
894 continue
895 item["transcript"] = text
896 transcribed += 1
897 return transcribed, ""
898
899
900 def _empty_tally(state: str, **extra: Any) -> Dict[str, Any]:
901 tally = {
902 "resolution": state,
903 "launched_in_window": 0,
904 "still_running": 0,
905 "video": 0,
906 "transcribed": 0,
907 "fetched": 0,
908 "endpoint_total": 0,
909 "cursor_remaining": False,
910 "placements": [],
911 "promo_codes": [],
912 "advertiser": "",
913 "page_id": "",
914 "top_candidate": "",
915 "runner_ups": [],
916 "match_strength": MATCH_NONE,
917 }
918 tally.update(extra)
919 return tally
920
921
922 # ------------------------------------------------------------ public entry
923
924
925 def search_meta_ads(
926 topic: str,
927 from_date: str,
928 to_date: str,
929 depth: str = "default",
930 token: str = "",
931 country: str = DEFAULT_COUNTRY,
932 page_override: str = "",
933 ) -> Dict[str, Any]:
934 """Resolve an advertiser and return its in-window creatives.
935
936 Returns ``{"ads", "page", "tally", "partial"?, "error"?}``. ``ads`` are
937 normalizer-ready item dicts; ``tally`` carries every count the footer
938 renders, computed here rather than downstream because the pipeline
939 truncates each source's stream to a per-depth limit before rendering.
940 """
941 topic = (topic or "").strip()
942 if not token:
943 _log("No SCRAPECREATORS_API_KEY - skipping")
944 return {"ads": [], "page": None, "tally": _empty_tally(UNRESOLVED)}
945 if not topic and not page_override:
946 _log("Empty topic - skipping")
947 return {"ads": [], "page": None, "tally": _empty_tally(UNRESOLVED)}
948
949 cfg = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
950 country = (country or DEFAULT_COUNTRY).strip() or DEFAULT_COUNTRY
951 budget = _Budget()
952
953 try:
954 if page_override:
955 page: Optional[Dict[str, Any]] = {"id": page_override, "name": topic or page_override}
956 runner_ups: List[str] = []
957 top_candidate = ""
958 state = RESOLVED
959 strength = MATCH_EXACT
960 _log(f"Using page override {page_override}")
961 else:
962 page, runner_ups, top_candidate, state, strength = _discover(
963 topic, country, token, budget
964 )
965
966 if page is None:
967 return {
968 "ads": [],
969 "page": None,
970 "tally": _empty_tally(state, top_candidate=top_candidate),
971 }
972
973 rows, endpoint_total, more, interruption = _fetch_window(
974 page, country, from_date, to_date, cfg["pages"], token, budget
975 )
976 items, still_running = _classify(rows, page, from_date, to_date)
977 if interruption:
978 transcribed, transcript_interruption = 0, ""
979 else:
980 transcribed, transcript_interruption = _add_transcripts(
981 items, cfg["transcripts"], token, budget
982 )
983 interruption = interruption or transcript_interruption
984 except (_Fatal, _StopFetching) as exc:
985 # Nothing was salvageable: either a credential/account failure, or the
986 # clock ran out before any creatives were fetched.
987 _log(f"Lane stopped: {exc}")
988 outcome: Dict[str, Any] = {
989 "ads": [],
990 "page": None,
991 "tally": _empty_tally(UNRESOLVED),
992 "error": str(exc),
993 }
994 if getattr(exc, "outcome_state", None):
995 outcome["outcome_state"] = exc.outcome_state
996 return outcome
997
998 placements: List[str] = []
999 promo_codes: List[str] = []
1000 for item in items:
1001 for placement in item["placements"]:
1002 if placement not in placements:
1003 placements.append(placement)
1004 code = item.get("promo_code")
1005 if code and code not in promo_codes:
1006 promo_codes.append(code)
1007
1008 tally = _empty_tally(
1009 RESOLVED,
1010 launched_in_window=len(items),
1011 still_running=still_running,
1012 video=sum(1 for item in items if item.get("has_video")),
1013 transcribed=transcribed,
1014 fetched=len(rows),
1015 endpoint_total=endpoint_total,
1016 cursor_remaining=more,
1017 placements=placements,
1018 promo_codes=promo_codes,
1019 advertiser=page.get("name") or "",
1020 page_id=page.get("id") or "",
1021 runner_ups=runner_ups,
1022 match_strength=strength,
1023 )
1024
1025 result: Dict[str, Any] = {"ads": items, "page": page, "tally": tally}
1026 if interruption:
1027 # Keep what came back. Thin coverage caused by our own clock or one
1028 # failed request must not read as a finding about how much the
1029 # advertiser is running.
1030 result["partial"] = True
1031 result["error"] = interruption
1032
1033 _log(
1034 f"{len(items)} creative(s) launched in window for '{page['name']}' "
1035 f"({still_running} still running from before, {transcribed} transcribed)"
1036 )
1037 return result
1038
1038 lines PYTHON