返回 last30days-skill
amazon.py
根目录 / skills / last30days / scripts / lib / amazon.py
1 """Amazon product and review signals via the Bright Data CLI.
2
3 Two-stage source, following the digg discover-then-enrich shape:
4
5 1. **Discovery** -- one product search per run turns a
6 model-supplied product keyword into product records carrying live
7 aggregate stats (rating, rating count, price). Cheap and fast.
8 2. **Enrichment** -- review pulls fetch a capped sample of
9 written reviews for the top few surviving products, in parallel, under
10 a lane deadline. Reviews ride on their product item as metadata
11 comments and feed community-voice weaving.
12
13 The signature signal is the fusion of those two: an all-time rating from
14 thousands of ratings, set against the average of just the reviews inside
15 the last-30-day window. When those disagree, something changed this month,
16 and the review text says what. No Amazon page shows that.
17
18 Metering (R13): one credit per pipeline request regardless of records
19 returned, so the caps here bound paid-tier *records*, not credits. A
20 default run is 1 search + up to 3 review pulls = 4 requests.
21
22 Field names and quirks below are verified against live payloads pulled
23 2026-08-13; see the plan's schema block. Three fields arrive doubled
24 (``review_posted_date``, ``review_header``, ``badge``) and are repaired
25 here rather than downstream.
26 """
27
28 from __future__ import annotations
29
30 import re
31 import time
32 from concurrent.futures import ThreadPoolExecutor, as_completed
33 from datetime import datetime, timezone
34 from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
35 from urllib.parse import urlparse
36
37 from . import brightdata, log
38 from .relevance import token_overlap_relevance
39
40
41 # Bright Data scraper IDs: "Amazon products search" and "Amazon Reviews".
42 SEARCH_DATASET = "gd_lwdb4vjm1ehb499uxs"
43 REVIEWS_DATASET = "gd_le8e811kzy4ggddlq"
44
45 DEFAULT_DOMAIN = "https://www.amazon.com"
46
47 # Reviews requested per pull. Uniform across topic shapes and depths by
48 # decision: billing is per *request*, not per record, so a bigger cap is
49 # free on the monthly credit tier, and the in-window sample is what the
50 # drift signal rests on. Live-verified that latency does not scale with
51 # this number (50 reviews in 22s vs 20 reviews in 115s on a slower SKU).
52 #
53 # It is a ceiling, never a quota -- a SKU with 31 total reviews returns 31.
54 MAX_REVIEWS = 50
55
56 # How many products get a review pull, per depth. Quick spends one credit
57 # on discovery only: aggregate stats with no recent window.
58 DEPTH_CONFIG = {
59 "quick": 0,
60 "default": 3,
61 "deep": 5,
62 }
63
64 SEARCH_TIMEOUT = 90
65 REVIEW_TIMEOUT = 60
66
67 # Wall-clock ceiling for the whole parallel review lane. Pulls that miss it
68 # are abandoned, and their products degrade to `quiet` rather than
69 # disappearing. One minute, down from three: a healthy pull answers in about
70 # 20s, and when the provider's review scraper does not answer at all (live
71 # 2026-11-10: no records after 180s while the product search took 16s) the
72 # run should lose a minute to it, not three. A slow SKU (one live pull took
73 # 115s) now reads `quiet` too.
74 LANE_DEADLINE = 60
75
76 # The engine's foreground contract. The lane deadline is clamped against
77 # whatever remains of it, minus room to render.
78 FOREGROUND_CONTRACT = 300
79 RENDER_MARGIN = 20
80
81 # Minimum useful budget for the review lane. Below this threshold, Bright
82 # Data pulls reliably time out (cli_timeout = max(5, timeout-10), so budget
83 # 11s → CLI timeout 1s; 45s leaves the CLI 35s against a ~20s healthy pull).
84 # Crumbs are a skip, not a short timeout: firing doomed pulls still spends 3
85 # credits with no reviews returned.
86 MIN_USEFUL_REVIEW_BUDGET = 45
87
88 # Footer and Partial Coverage wording for a review lane whose every pull
89 # failed or missed the deadline: the products and their search stats still
90 # stand, and the reader is told why there are no review excerpts.
91 REVIEWS_UNAVAILABLE_NOTE = "written reviews unavailable from the provider this run"
92 _REVIEWS_UNAVAILABLE_STATUSES = ("review lane timed out", "review pulls failed")
93
94
95 def outcome_detail(status: str) -> str:
96 """The source-outcome detail for an ``enrich_with_reviews`` status."""
97 if status in _REVIEWS_UNAVAILABLE_STATUSES:
98 return f"{REVIEWS_UNAVAILABLE_NOTE} ({status})"
99 return status
100
101
102 # Minimum dated reviews inside the window before a drift arrow is honest.
103 # Live census: a 50-cap pull returned 31 records of which only 5 were
104 # inside 30 days, so an unguarded arrow would routinely publish a "trend"
105 # computed from one or two reviews.
106 MIN_DRIFT_SAMPLE = 5
107
108 RECENT_WINDOW_DAYS = 30
109
110 # Product names run long and pipe-delimited; the footer needs a scannable
111 # handle, not a title.
112 SHORT_NAME_MAX = 18
113
114 _STAR_FIELDS = (
115 ("one_star", 1),
116 ("two_star", 2),
117 ("three_star", 3),
118 ("four_star", 4),
119 ("five_star", 5),
120 )
121
122
123 def _log(msg: str) -> None:
124 log.source_log("Amazon", msg, tty_only=False)
125
126
127 def _today() -> datetime:
128 return datetime.now(timezone.utc)
129
130
131 # --------------------------------------------------------------- parsing
132
133
134 def undouble(text: str) -> str:
135 """Repair the CLI's doubled string fields.
136
137 Observed live: ``review_header`` arrives as ``"Best Box!Best Box!"`` and
138 ``badge`` as ``"Verified Purchase, Verified Purchase"``. Handles the
139 exact-repeat case and the comma-joined repeat, and leaves anything else
140 untouched -- a genuinely repetitive title must survive intact.
141 """
142 value = (text or "").strip()
143 if not value:
144 return ""
145 half, odd = divmod(len(value), 2)
146 # Only treat an exact repeat as doubling when the halves are substantial
147 # and look like a phrase rather than a syllable -- otherwise a real title
148 # of "ByeBye" or "NoNo" gets silently truncated to half of itself. The
149 # observed artifact doubles whole headlines, so requiring some length and
150 # either whitespace or terminal punctuation keeps the repair targeted.
151 if not odd and half >= 6 and value[:half] == value[half:]:
152 first = value[:half]
153 if " " in first or first[-1] in ".!?":
154 return first.strip()
155 parts = [p.strip() for p in value.split(",")]
156 if len(parts) == 2 and parts[0] and parts[0] == parts[1]:
157 return parts[0]
158 return value
159
160
161 _DATE_HEAD = re.compile(r"^([A-Z][a-z]+ \d{1,2}, \d{4})")
162
163
164 def parse_review_date(raw: Any) -> Optional[str]:
165 """Pull the ISO date out of the CLI's prose-wrapped date field.
166
167 Live shape: ``"August 3, 2026Reviewed in the United States on August 3,
168 2026"``. Only the leading ``%B %d, %Y`` is trustworthy; the tail is
169 localized prose that varies by marketplace.
170
171 Returns ``YYYY-MM-DD`` or None.
172 """
173 match = _DATE_HEAD.match(str(raw or "").strip())
174 if not match:
175 return None
176 try:
177 return datetime.strptime(match.group(1), "%B %d, %Y").date().isoformat()
178 except ValueError:
179 return None
180
181
182 def short_name(name: str, brand: str = "") -> str:
183 """Derive a scannable footer handle from a long product name.
184
185 Live names are pipe-delimited marketing strings with the brand carried
186 in its own field rather than as a prefix ("Chill Max Leak-Proof XL
187 Bento-Style Lunch Box | Included Ice Pack Keeps Food Cold"). Take the
188 segment before the first delimiter, drop a leading brand token if one
189 did sneak in, and clip to a scannable width on a word boundary.
190 """
191 text = re.split(r"[|(–—]", str(name or ""), maxsplit=1)[0].strip(" -,")
192 brand_token = str(brand or "").strip()
193 if brand_token:
194 # Word-boundary anchored: a bare startswith() eats into sub-brands and
195 # coincidental prefixes ("AnkerWork" under brand "Anker" would become
196 # "Work", "Chillax" under "Chill" would become "ax").
197 stripped = re.sub(
198 rf"^{re.escape(brand_token)}\b[\s\-,]*", "", text, count=1, flags=re.IGNORECASE
199 )
200 if stripped:
201 text = stripped.strip(" -,")
202 if len(text) <= SHORT_NAME_MAX:
203 return text
204 clipped = text[:SHORT_NAME_MAX].rsplit(" ", 1)[0].strip(" -,")
205 return clipped or text[:SHORT_NAME_MAX].strip()
206
207
208 def _as_float(value: Any) -> Optional[float]:
209 try:
210 result = float(value)
211 except (TypeError, ValueError):
212 return None
213 return result
214
215
216 def _as_int(value: Any) -> int:
217 try:
218 return int(value)
219 except (TypeError, ValueError):
220 return 0
221
222
223 def _is_sponsored(value: Any) -> bool:
224 """The flag arrives as the string 'true'/'false', not a bool.
225
226 Recorded in metadata but never used to filter (R4): its distribution
227 swings hard with keyword phrasing, so filtering on it can blank the
228 lane on an unlucky query.
229 """
230 if isinstance(value, bool):
231 return value
232 return str(value or "").strip().lower() == "true"
233
234
235 def _valid_product_url(url: str, domain: str) -> bool:
236 """Accept only https URLs on the configured Amazon host."""
237 try:
238 parsed = urlparse(url)
239 expected = urlparse(domain or DEFAULT_DOMAIN)
240 except ValueError:
241 return False
242 if parsed.scheme != "https" or not parsed.netloc:
243 return False
244 host = parsed.netloc.lower().removeprefix("www.")
245 want = (expected.netloc or "").lower().removeprefix("www.")
246 return bool(want) and host == want
247
248
249 # Amazon ASINs are a fixed shape. Validating it matters because the value
250 # is interpolated into a URL that is then refetched through the CLI *and*
251 # rendered as a link in the report -- two sinks, one unvalidated API field.
252 _ASIN_RE = re.compile(r"^[A-Za-z0-9]{10}$")
253
254
255 def _valid_asin(asin: str) -> bool:
256 return bool(_ASIN_RE.match(asin or ""))
257
258
259 def canonical_product_url(url: str, asin: str, domain: str) -> str:
260 """Strip Amazon's tracking tail down to a stable /dp/<asin> link.
261
262 Search records carry 200+ character URLs with session-scoped ``dib``
263 tokens. Those work but are unreadable in a report and unstable across
264 runs, which breaks dedupe on re-runs of the same topic.
265
266 Falls back to the (already host-validated) original URL if the ASIN is
267 not well-formed, so a malformed record can never shape the rebuilt URL.
268 """
269 if not _valid_asin(asin):
270 return url
271 base = (domain or DEFAULT_DOMAIN).rstrip("/")
272 return f"{base}/dp/{asin}"
273
274
275 # ------------------------------------------------------------- discovery
276
277
278 def search_products(
279 keyword: str,
280 *,
281 domain: str = DEFAULT_DOMAIN,
282 config: Optional[Dict[str, Any]] = None,
283 timeout: int = SEARCH_TIMEOUT,
284 ) -> Dict[str, Any]:
285 """Run one product search. Never raises; returns the adapter envelope."""
286 query = (keyword or "").strip()
287 if not query:
288 return {"records": []}
289 # Model-supplied and shaped by untrusted pre-research. --input JSON already
290 # keeps it out of argv; this is defense in depth, and '-x' is never a product.
291 if query.startswith("-"):
292 _log(f"rejecting option-shaped keyword: {query!r}")
293 return {"records": [], "error": "amazon keyword may not begin with '-'"}
294 _log(f"search '{query}' on {domain}")
295 response = brightdata.run_pipeline(
296 SEARCH_DATASET,
297 {"keyword": query, "url": domain or DEFAULT_DOMAIN, "pages_to_search": 1},
298 timeout=timeout, config=config,
299 )
300 if response.get("error"):
301 _log(f"search failed: {response['error']}")
302 else:
303 _log(f"search returned {len(response.get('records') or [])} records")
304 return response
305
306
307 def parse_search_response(
308 response: Dict[str, Any],
309 keyword: str,
310 *,
311 domain: str = DEFAULT_DOMAIN,
312 min_relevance: float = 0.15,
313 ) -> List[Dict[str, Any]]:
314 """Turn raw search records into deduped, relevance-gated product dicts.
315
316 Dedupe is by ASIN: live payloads repeat a single product up to five
317 times across the result set (64 unique of 66 records on one pull).
318 Relevance is scored against the *supplied keyword*, not the run topic,
319 because the model may search "June Oven" on a topic about a person.
320 """
321 records = response.get("records") if isinstance(response, dict) else None
322 if not isinstance(records, list):
323 return []
324
325 today = _today().date().isoformat()
326 seen: Dict[str, Dict[str, Any]] = {}
327 for record in records:
328 if not isinstance(record, dict):
329 continue
330 asin = str(record.get("asin") or "").strip()
331 raw_url = str(record.get("url") or "").strip()
332 if not _valid_asin(asin) or not _valid_product_url(raw_url, domain):
333 continue
334
335 name = str(record.get("name") or "").strip()
336 brand = str(record.get("brand") or "").strip()
337 if not name:
338 continue
339
340 relevance = token_overlap_relevance(keyword, f"{brand} {name}".strip())
341 if relevance < min_relevance:
342 continue
343
344 num_ratings = _as_int(record.get("num_ratings"))
345 existing = seen.get(asin)
346 # Duplicates of one ASIN can disagree on rating count (variant-level
347 # records); keep the richest.
348 if existing and _as_int(existing.get("num_ratings")) >= num_ratings:
349 continue
350
351 seen[asin] = {
352 "asin": asin,
353 # Current-date stamped (KTD6, trustpilot precedent): a live
354 # aggregate rating is a fact about now, not about the product's
355 # launch date, so it must not be dropped by the 30-day filter.
356 "date": today,
357 "name": name,
358 "short_name": short_name(name, brand),
359 "brand": brand,
360 "url": canonical_product_url(raw_url, asin, domain),
361 "rating": _as_float(record.get("rating")),
362 "num_ratings": num_ratings,
363 "price": _as_float(record.get("final_price")),
364 "currency": str(record.get("currency") or "").strip(),
365 "badge": undouble(str(record.get("badge") or "")),
366 "sponsored": _is_sponsored(record.get("sponsored")),
367 "bought_past_month": _as_int(record.get("bought_past_month")),
368 "rank_on_page": _as_int(record.get("rank_on_page")),
369 "relevance": relevance,
370 }
371
372 products = sorted(
373 seen.values(),
374 key=lambda p: (p["num_ratings"], p["relevance"]),
375 reverse=True,
376 )
377 _log(f"{len(products)} unique on-keyword products after dedupe")
378 return products
379
380
381 def infer_brand(products: Sequence[Dict[str, Any]], keyword: str) -> str:
382 """Detect a brand topic by matching record brands against the keyword.
383
384 This is the guard against paying to review a competitor. Rival brands
385 buy ads against a brand keyword and can outrank the brand's own catalog
386 on raw rating count: on a live "bentgo lunch box" search a competitor
387 held the top two slots and would have taken two of the three review
388 pulls, putting a rival's reviews in a Bentgo report.
389
390 Matching the *keyword's own tokens*, rather than picking the most
391 common brand in the results, is what keeps category topics unfiltered.
392 "best bluetooth speaker" names no brand, so nothing is constrained and
393 the top products across brands compete on merit -- which is exactly
394 what that topic shape wants.
395 """
396 normalized_keyword = " ".join(re.findall(r"[a-z0-9]+", (keyword or "").lower()))
397 if not normalized_keyword:
398 return ""
399 keyword_tokens = set(normalized_keyword.split())
400
401 # Keyed by the lowercased brand so one vendor spelled two ways ("Bentgo"
402 # and "BENTGO" in the same result set) reads as one candidate. Without
403 # this the set has two members, the function bails, and the guard it
404 # exists to provide silently turns off.
405 candidates: Dict[str, str] = {}
406 for product in products:
407 brand = str(product.get("brand") or "").strip()
408 if not brand:
409 continue
410 brand_tokens = re.findall(r"[a-z0-9]+", brand.lower())
411 if not brand_tokens:
412 continue
413 # Multi-word brands ("Hydro Flask") can never match a single-token
414 # test, so compare the brand's whole token sequence against the
415 # keyword's -- otherwise the guard is off for every two-word brand.
416 if len(brand_tokens) == 1:
417 matched = brand_tokens[0] in keyword_tokens and len(brand_tokens[0]) > 2
418 else:
419 matched = " ".join(brand_tokens) in normalized_keyword
420 if matched:
421 # First spelling wins, so the result is deterministic across runs.
422 candidates.setdefault(brand.lower(), brand)
423 return next(iter(candidates.values())) if len(candidates) == 1 else ""
424
425
426 def select_enrichment_targets(
427 products: Sequence[Dict[str, Any]],
428 *,
429 limit: int,
430 brand: str = "",
431 keyword: str = "",
432 ) -> List[Dict[str, Any]]:
433 """Pick which products get a review pull.
434
435 Ranked by rating count, which is a coarse signal: search records carry
436 variant-level counts that can undercount badly (84 on a record whose
437 review pull reported 8,446). The review pull's own
438 ``product_rating_count`` is authoritative once available.
439
440 Two filters run before the cut:
441
442 * **Brand**, supplied or inferred from the keyword (see ``infer_brand``).
443 The record's own ``brand`` field does the work, which also solves
444 accessory contamination outright -- a "grill brush for Weber" carries
445 the brush maker's brand, not Weber. A front-anchored name match covers
446 the few records where ``brand`` is null.
447 * **Variant collapse.** Live results repeat one product across colors
448 and sizes under distinct ASINs with near-identical names. Two of those
449 would burn two of three pulls on the same product and render as
450 duplicate footer entries, so only the best-ranked of each short-name
451 group stays eligible.
452 """
453 if limit <= 0:
454 return []
455 pool = list(products)
456
457 wanted = (brand or "").strip().lower() or infer_brand(pool, keyword).lower()
458 if wanted:
459 matched = [
460 p for p in pool
461 if (p.get("brand") or "").strip().lower() == wanted
462 or (not (p.get("brand") or "").strip()
463 and str(p.get("name") or "").strip().lower().startswith(wanted))
464 ]
465 if matched:
466 pool = matched
467
468 deduped: List[Dict[str, Any]] = []
469 seen_names: set[str] = set()
470 for product in pool:
471 key = (product.get("short_name") or "").strip().lower()
472 if key and key in seen_names:
473 continue
474 if key:
475 seen_names.add(key)
476 deduped.append(product)
477 return deduped[:limit]
478
479
480 # ------------------------------------------------------------ enrichment
481
482
483 def fetch_reviews(
484 product_url: str,
485 *,
486 max_reviews: int = MAX_REVIEWS,
487 config: Optional[Dict[str, Any]] = None,
488 timeout: int = REVIEW_TIMEOUT,
489 ) -> Dict[str, Any]:
490 """Pull a capped review sample for one product. Never raises."""
491 if not product_url:
492 return {"records": []}
493 return brightdata.run_pipeline(
494 REVIEWS_DATASET, {"url": product_url, "max_reviews": int(max_reviews)},
495 timeout=timeout, config=config,
496 )
497
498
499 def parse_reviews(response: Dict[str, Any]) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
500 """Split a review payload into comment dicts and product-level stats.
501
502 Product-level fields (``product_rating``, ``product_rating_count``, the
503 ``product_rating_object`` star distribution) ride on *every* review
504 record, so they are read off the first one.
505
506 Comments are built directly in the shared score/excerpt shape rather
507 than routed through ``normalize._remap_comments``, which strips keys it
508 does not know -- and rating, date, and verified are exactly the keys
509 this source needs to keep. Sorted newest first so the woven sample
510 favors recent voices.
511 """
512 records = response.get("records") if isinstance(response, dict) else None
513 if not isinstance(records, list) or not records:
514 return [], {}
515
516 first = records[0]
517 distribution = first.get("product_rating_object")
518 stats: Dict[str, Any] = {
519 "product_rating": _as_float(first.get("product_rating")),
520 "product_rating_count": _as_int(first.get("product_rating_count")),
521 "star_distribution": distribution if isinstance(distribution, dict) else {},
522 }
523
524 comments: List[Dict[str, Any]] = []
525 for record in records:
526 if not isinstance(record, dict):
527 continue
528 body = str(record.get("review_text") or "").strip()
529 header = undouble(str(record.get("review_header") or ""))
530 excerpt = body or header
531 if not excerpt:
532 continue
533 comments.append(
534 {
535 # Shared comment shape: downstream weaving reads score/excerpt.
536 "score": _as_int(record.get("helpful_count")),
537 "excerpt": excerpt,
538 "author": str(record.get("author_name") or "").strip(),
539 "rating": _as_int(record.get("rating")),
540 "date": parse_review_date(record.get("review_posted_date")),
541 "verified": bool(record.get("is_verified")),
542 "vine": bool(record.get("is_amazon_vine")),
543 "title": header,
544 }
545 )
546
547 # Newest first; undated records sink rather than disappear (R2a).
548 comments.sort(key=lambda c: (c["date"] or "", c["score"]), reverse=True)
549 return comments, stats
550
551
552 def _remaining_lane_budget(elapsed: float, deadline: Optional[float] = None) -> int:
553 """Compute the review lane's wall-clock budget.
554
555 Returns the lesser of LANE_DEADLINE and whatever remains of the foreground
556 contract (and ``deadline``, when provided). If the remaining time is below
557 MIN_USEFUL_REVIEW_BUDGET, returns 0 (skip the lane entirely) rather than
558 firing doomed short pulls that spend Bright Data credits without returning
559 reviews.
560 """
561 remaining = FOREGROUND_CONTRACT - elapsed - RENDER_MARGIN
562 if deadline is not None:
563 remaining = min(remaining, deadline - time.monotonic())
564 if remaining < MIN_USEFUL_REVIEW_BUDGET:
565 return 0
566 return int(min(LANE_DEADLINE, remaining))
567
568
569 def enrich_with_reviews(
570 products: Sequence[Dict[str, Any]],
571 *,
572 depth: str = "default",
573 config: Optional[Dict[str, Any]] = None,
574 elapsed: float = 0.0,
575 max_reviews: int = MAX_REVIEWS,
576 brand: str = "",
577 keyword: str = "",
578 fetcher=None,
579 deadline: Optional[float] = None,
580 ) -> Tuple[List[Dict[str, Any]], Optional[str]]:
581 """Attach review samples to the top products, in parallel, under a deadline.
582
583 Every product is returned either way. A product whose pull is dropped
584 by the deadline keeps its search-record stats and simply carries no
585 review sample -- it renders as ``quiet`` rather than vanishing, because
586 losing a top product entirely is a worse failure than losing its
587 recent-window read. The dropped pull has spent its credit regardless.
588
589 Returns (enriched_products, status_detail). status_detail is None when
590 enrichment succeeded normally, or a string describing a degraded outcome:
591 - ``"review lane skipped (budget 0s)"`` -- crumb budget, lane did not run
592 - ``"review lane timed out"`` -- no pull completed and the deadline dropped some
593 - ``"review pulls failed"`` -- no pull completed; each one errored
594
595 Every product is stamped ``reviews_attempted`` once pulls were fired, so
596 finalize does not fire (and wait on) the same lane a second time.
597 """
598 enriched = [dict(p) for p in products]
599 pull_count = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
600 if pull_count <= 0:
601 _log(f"depth={depth}: discovery only, no review pulls")
602 return enriched, None
603
604 budget = _remaining_lane_budget(elapsed, deadline=deadline)
605 if budget <= 0:
606 _log(f"review lane skipped (budget {budget}s, floor {MIN_USEFUL_REVIEW_BUDGET}s)")
607 return enriched, "review lane skipped (budget 0s)"
608
609 targets = select_enrichment_targets(
610 enriched, limit=pull_count, brand=brand, keyword=keyword
611 )
612 if not targets:
613 return enriched, None
614
615 by_asin = {p["asin"]: p for p in enriched}
616 for product in enriched:
617 product["reviews_attempted"] = True
618 pull = fetcher or (
619 lambda url: fetch_reviews(
620 url, max_reviews=max_reviews, config=config,
621 timeout=min(REVIEW_TIMEOUT, budget),
622 )
623 )
624
625 _log(f"pulling up to {max_reviews} reviews for {len(targets)} products (budget {budget}s)")
626 started = time.monotonic()
627 completed_count = 0
628 dropped_count = 0
629 # Not a `with` block on purpose. Every future is already running (one
630 # worker per target), so `future.cancel()` can never succeed, and
631 # ThreadPoolExecutor's context-manager exit calls shutdown(wait=True) --
632 # which would block on the very straggler the deadline just declared
633 # dropped, making the deadline advisory rather than real. Shutting down
634 # without waiting lets the abandoned thread finish and discard its result
635 # in the background while the run proceeds.
636 pool = ThreadPoolExecutor(max_workers=max(1, len(targets)))
637 try:
638 futures = {pool.submit(pull, t["url"]): t["asin"] for t in targets}
639 try:
640 for future in as_completed(futures, timeout=budget):
641 asin = futures[future]
642 try:
643 response = future.result()
644 except Exception as exc: # never let one pull kill siblings
645 _log(f"review pull failed for {asin}: {exc}")
646 continue
647 if response.get("error"):
648 _log(f"review pull error for {asin}: {response['error']}")
649 continue
650 comments, stats = parse_reviews(response)
651 product = by_asin.get(asin)
652 if product is None:
653 continue
654 product["top_comments"] = comments
655 product.update({k: v for k, v in stats.items() if v})
656 completed_count += 1
657 except TimeoutError:
658 dropped_count = sum(1 for f in futures if not f.done())
659 _log(f"lane deadline {budget}s hit; dropped {dropped_count} straggling pull(s)")
660 finally:
661 pool.shutdown(wait=False, cancel_futures=True)
662
663 _log(f"review lane finished in {time.monotonic() - started:.0f}s")
664
665 # Report a degraded outcome when no pull completed: dropped by the
666 # deadline, or each one came back as an error.
667 status_detail = None
668 if completed_count == 0:
669 status_detail = "review lane timed out" if dropped_count else "review pulls failed"
670
671 return enriched, status_detail
672
673
674 def enrich_source_items(
675 items: List[Any],
676 *,
677 depth: str = "default",
678 config: Optional[Dict[str, Any]] = None,
679 keyword: str = "",
680 elapsed: float = 0.0,
681 max_reviews: int = MAX_REVIEWS,
682 fetcher=None,
683 deadline: Optional[float] = None,
684 ) -> List[Any]:
685 """Attach review samples to the amazon SourceItems that survived dedupe.
686
687 Reads product identity out of ``metadata`` and writes ``top_comments``
688 plus the computed stat block back into it, in place. Runs from
689 ``pipeline._finalize_items_by_source`` so the review budget is spent on
690 the products the brief will actually show, not on the top of the raw
691 fanout (the digg enrichment precedent).
692 """
693 products: List[Dict[str, Any]] = []
694 by_asin: Dict[str, Any] = {}
695 for item in items:
696 if getattr(item, "source", None) != "amazon":
697 continue
698 metadata = getattr(item, "metadata", None) or {}
699 asin = str(metadata.get("asin") or "").strip()
700 if not asin or metadata.get("top_comments") or metadata.get("reviews_attempted"):
701 continue
702 products.append(
703 {
704 "asin": asin,
705 "url": getattr(item, "url", "") or metadata.get("url", ""),
706 "name": metadata.get("name") or getattr(item, "title", ""),
707 "short_name": metadata.get("short_name") or "",
708 "brand": metadata.get("brand") or "",
709 "num_ratings": metadata.get("num_ratings") or 0,
710 "rating": metadata.get("rating"),
711 }
712 )
713 by_asin[asin] = item
714
715 if not products:
716 return items
717
718 enriched, _status = enrich_with_reviews(
719 products, depth=depth, config=config, elapsed=elapsed,
720 max_reviews=max_reviews, keyword=keyword, fetcher=fetcher,
721 deadline=deadline,
722 )
723 for product in enriched:
724 item = by_asin.get(product["asin"])
725 if item is None:
726 continue
727 metadata = getattr(item, "metadata", None)
728 if metadata is None:
729 continue
730 if product.get("top_comments"):
731 metadata["top_comments"] = product["top_comments"]
732 stats = product_stats(product)
733 metadata["stats"] = stats
734 # The review pull's product_rating_count supersedes the search
735 # record's, which is variant-level and can undercount by orders of
736 # magnitude (84 on a record whose pull reported 8,446). Normalization
737 # ran before enrichment, so refresh the surfaces that already baked
738 # the old number in -- otherwise one product shows two different
739 # rating counts in the same report.
740 for key in ("product_rating", "product_rating_count", "star_distribution"):
741 if product.get(key):
742 metadata[key] = product[key]
743 authoritative = stats.get("ratings_total") or 0
744 if authoritative and getattr(item, "engagement", None) is not None:
745 item.engagement["ratings"] = authoritative
746 metadata["num_ratings"] = authoritative
747 _refresh_title(item, stats)
748 return items
749
750
751 def _refresh_title(item: Any, stats: Dict[str, Any]) -> None:
752 """Rewrite the trailing "- 4.4/5 (N ratings)" headline after enrichment."""
753 title = getattr(item, "title", "") or ""
754 rating = stats.get("all_time")
755 total = stats.get("ratings_total") or 0
756 if not title or rating is None or not total:
757 return
758 headline = f"{rating}/5 ({total:,} ratings)"
759 base = title.rsplit(" - ", 1)[0] if " - " in title else title
760 item.title = f"{base} - {headline}"
761
762
763 # ------------------------------------------------------------------ stats
764
765
766 def stats_from_item(item: Any, *, today: Optional[datetime] = None) -> Dict[str, Any]:
767 """Compute the stat block for a rendered SourceItem.
768
769 Enrichment stores a precomputed block, but mock runs and replayed
770 fixtures skip enrichment entirely, so render recomputes from metadata
771 when it is absent. Cheap and pure -- all the inputs already live on
772 the item.
773 """
774 metadata = getattr(item, "metadata", None) or {}
775 cached = metadata.get("stats")
776 if isinstance(cached, dict) and cached:
777 return cached
778 return product_stats(
779 {
780 "short_name": metadata.get("short_name") or "",
781 "name": metadata.get("name") or getattr(item, "title", ""),
782 "url": getattr(item, "url", "") or "",
783 "rating": metadata.get("rating"),
784 "num_ratings": metadata.get("num_ratings") or 0,
785 "product_rating": metadata.get("product_rating"),
786 "product_rating_count": metadata.get("product_rating_count") or 0,
787 "star_distribution": metadata.get("star_distribution") or {},
788 "top_comments": metadata.get("top_comments") or [],
789 },
790 today=today,
791 )
792
793
794 def footer_entry(stats: Dict[str, Any], *, quote: str = "") -> str:
795 """Render one product's segment of the emoji-footer line (R1c).
796
797 Shapes, by drift state::
798
799 Chill Max XL 4.4★→3.8★ ↓ "the lid jams" negative drift (+ quote)
800 Deluxe Bag 4.7★→5.0★ positive or flat drift
801 Spirit E-325 4.4★ quiet too few in-window reviews
802 BLUEY Set new no all-time baseline
803
804 The ``↓`` is asymmetric on purpose: a sagging product is the alarm
805 worth catching at a glance, and a healthy one needs no decoration.
806 """
807 name = stats.get("short_name") or "Product"
808 all_time = stats.get("all_time")
809 recent = stats.get("recent_avg")
810 drift = stats.get("drift")
811
812 if drift == "new" or all_time is None:
813 return f"{name} new"
814 if drift == "quiet" or recent is None:
815 return f"{name} {all_time}★ quiet"
816
817 entry = f"{name} {all_time}★→{recent}★"
818 if drift == "down":
819 entry += " ↓"
820 if quote:
821 entry += f' "{quote}"'
822 return entry
823
824
825 def five_star_share(distribution: Dict[str, Any]) -> Optional[float]:
826 """Share of ratings that are 5-star, from the star-distribution object."""
827 if not isinstance(distribution, dict) or not distribution:
828 return None
829 total = sum(_as_int(distribution.get(key)) for key, _ in _STAR_FIELDS)
830 if total <= 0:
831 return None
832 return _as_int(distribution.get("five_star")) / total
833
834
835 def recent_window_stats(
836 comments: Iterable[Dict[str, Any]],
837 *,
838 today: Optional[datetime] = None,
839 window_days: int = RECENT_WINDOW_DAYS,
840 ) -> Dict[str, Any]:
841 """Average rating and sample size inside the recent window."""
842 reference = (today or _today()).date()
843 ratings: List[int] = []
844 for comment in comments or []:
845 iso = comment.get("date")
846 if not iso:
847 continue
848 try:
849 posted = datetime.strptime(iso, "%Y-%m-%d").date()
850 except (TypeError, ValueError):
851 continue
852 if 0 <= (reference - posted).days <= window_days:
853 rating = _as_int(comment.get("rating"))
854 if rating:
855 ratings.append(rating)
856 if not ratings:
857 return {"recent_n": 0, "recent_avg": None}
858 return {"recent_n": len(ratings), "recent_avg": sum(ratings) / len(ratings)}
859
860
861 def product_stats(
862 product: Dict[str, Any],
863 *,
864 today: Optional[datetime] = None,
865 ) -> Dict[str, Any]:
866 """Compute the render-facing stat block for one product.
867
868 ``drift`` is one of:
869 * ``"new"`` -- no all-time baseline to move away from
870 * ``"quiet"`` -- baseline exists but the window has too few dated
871 reviews to average honestly (below MIN_DRIFT_SAMPLE)
872 * ``"up"`` / ``"down"`` / ``"flat"`` -- a real, sample-backed move
873
874 The engine owns every number here; the model owns the words (R1b).
875 """
876 # The review pull's rating count supersedes the search record's, which
877 # can be variant-level and badly low.
878 all_time = product.get("product_rating")
879 if all_time is None:
880 all_time = product.get("rating")
881 ratings_total = product.get("product_rating_count") or product.get("num_ratings") or 0
882
883 window = recent_window_stats(product.get("top_comments") or [], today=today)
884 recent_avg = window["recent_avg"]
885 recent_n = window["recent_n"]
886
887 if all_time is None:
888 drift = "new"
889 elif recent_n < MIN_DRIFT_SAMPLE or recent_avg is None:
890 drift = "quiet"
891 elif round(recent_avg, 1) > round(float(all_time), 1):
892 drift = "up"
893 elif round(recent_avg, 1) < round(float(all_time), 1):
894 drift = "down"
895 else:
896 drift = "flat"
897
898 return {
899 "short_name": product.get("short_name") or short_name(product.get("name", "")),
900 "url": product.get("url", ""),
901 "all_time": round(float(all_time), 1) if all_time is not None else None,
902 "ratings_total": _as_int(ratings_total),
903 "five_star_share": five_star_share(product.get("star_distribution") or {}),
904 "recent_avg": round(recent_avg, 1) if recent_avg is not None else None,
905 "recent_n": recent_n,
906 "reviews_pulled": len(product.get("top_comments") or []),
907 "drift": drift,
908 }
909
909 lines PYTHON