| 1 | """Normalization of source-specific payloads into the v3 generic item model.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import math |
| 6 | from datetime import date, datetime, timezone |
| 7 | from typing import Any |
| 8 | from urllib.parse import urlparse |
| 9 | |
| 10 | from . import dates, schema, x_envelope |
| 11 | |
| 12 | |
| 13 | def _parse_iso_day(value: str | None) -> str | None: |
| 14 | text = str(value or "").strip() |
| 15 | if not text: |
| 16 | return None |
| 17 | try: |
| 18 | if len(text) == 10: |
| 19 | return date.fromisoformat(text).isoformat() |
| 20 | dt = datetime.fromisoformat(text.replace("Z", "+00:00")) |
| 21 | return (dt.astimezone(timezone.utc) if dt.tzinfo else dt).date().isoformat() |
| 22 | except ValueError: |
| 23 | return None |
| 24 | |
| 25 | |
| 26 | def _matched_date_in_window( |
| 27 | date_str: str, |
| 28 | from_date: str | None, |
| 29 | to_date: str | None, |
| 30 | ) -> bool: |
| 31 | text = str(date_str or "").strip() |
| 32 | if not text: |
| 33 | return False |
| 34 | if not from_date and not to_date: |
| 35 | return True |
| 36 | iso = _parse_iso_day(text) |
| 37 | if not iso: |
| 38 | return False |
| 39 | start = _parse_iso_day(from_date) if from_date else None |
| 40 | end = _parse_iso_day(to_date) if to_date else None |
| 41 | if start and iso < start: |
| 42 | return False |
| 43 | if end and iso > end: |
| 44 | return False |
| 45 | return True |
| 46 | |
| 47 | |
| 48 | def filter_by_date_range( |
| 49 | items: list[schema.SourceItem], |
| 50 | from_date: str, |
| 51 | to_date: str, |
| 52 | require_date: bool = False, |
| 53 | ) -> list[schema.SourceItem]: |
| 54 | """Keep only items within the requested window.""" |
| 55 | filtered: list[schema.SourceItem] = [] |
| 56 | for item in items: |
| 57 | if not item.published_at: |
| 58 | basis = item.metadata.get("date_window_basis") if item.source == "grounding" else None |
| 59 | if ( |
| 60 | not require_date |
| 61 | or basis == "server_bounds" |
| 62 | or basis == "server_start_current" |
| 63 | or basis == "keyless_current" |
| 64 | ): |
| 65 | filtered.append(item) |
| 66 | continue |
| 67 | if item.published_at < from_date or item.published_at > to_date: |
| 68 | # A Reddit comment-search hit stays when the comment it matched is |
| 69 | # in the window, even on an older thread (the thread date is kept). |
| 70 | matched = str((item.metadata or {}).get("matched_comment_date") or "") |
| 71 | if not (matched and from_date <= matched <= to_date): |
| 72 | continue |
| 73 | filtered.append(item) |
| 74 | return filtered |
| 75 | |
| 76 | |
| 77 | def normalize_source_items( |
| 78 | source: str, |
| 79 | items: list[dict[str, Any]], |
| 80 | from_date: str, |
| 81 | to_date: str, |
| 82 | freshness_mode: str = "balanced_recent", |
| 83 | ) -> list[schema.SourceItem]: |
| 84 | """Normalize raw source items, filter by date range, with evergreen fallback for how_to queries.""" |
| 85 | source = source.lower() |
| 86 | normalizers = { |
| 87 | "reddit": _normalize_reddit, |
| 88 | "x": _normalize_x, |
| 89 | "youtube": _normalize_youtube, |
| 90 | "tiktok": lambda s, i, idx, fd, td: _normalize_shortform_video( |
| 91 | s, i, idx, fd, td, "TK", "TikTok post" |
| 92 | ), |
| 93 | "instagram": lambda s, i, idx, fd, td: _normalize_shortform_video( |
| 94 | s, i, idx, fd, td, "IG", "Instagram reel" |
| 95 | ), |
| 96 | "hackernews": _normalize_hackernews, |
| 97 | "devto": _normalize_devto, |
| 98 | "v2ex": _normalize_v2ex, |
| 99 | "juejin": _normalize_juejin, |
| 100 | "stocktwits": _normalize_stocktwits, |
| 101 | "dripstack": _normalize_dripstack, |
| 102 | "bluesky": lambda s, i, idx, fd, td: _normalize_microblog( |
| 103 | s, i, idx, fd, td, "BS", "Bluesky post" |
| 104 | ), |
| 105 | "truthsocial": lambda s, i, idx, fd, td: _normalize_microblog( |
| 106 | s, i, idx, fd, td, "TS", "Truth Social post" |
| 107 | ), |
| 108 | "threads": lambda s, i, idx, fd, td: _normalize_microblog( |
| 109 | s, i, idx, fd, td, "TH", "Threads post" |
| 110 | ), |
| 111 | "telegram": lambda s, i, idx, fd, td: _normalize_microblog( |
| 112 | s, i, idx, fd, td, "TG", "Telegram post" |
| 113 | ), |
| 114 | "xquik": _normalize_x, |
| 115 | "pinterest": _normalize_pinterest, |
| 116 | "polymarket": _normalize_polymarket, |
| 117 | "digg": _normalize_digg, |
| 118 | "arxiv": _normalize_arxiv, |
| 119 | "techmeme": _normalize_techmeme, |
| 120 | "news_rss": _normalize_news_rss, |
| 121 | "trustpilot": _normalize_trustpilot, |
| 122 | "amazon": _normalize_amazon, |
| 123 | "meta_ads": _normalize_meta_ads, |
| 124 | "grounding": _normalize_grounding, |
| 125 | "xiaohongshu": _normalize_grounding, |
| 126 | "github": _normalize_github, |
| 127 | "perplexity": _normalize_grounding, |
| 128 | "jobs": _normalize_jobs, |
| 129 | "linkedin": _normalize_linkedin, |
| 130 | "linkedin_profile": _normalize_linkedin_profile, |
| 131 | } |
| 132 | normalizer = normalizers.get(source) |
| 133 | if normalizer is None: |
| 134 | raise ValueError(f"Unsupported source: {source}") |
| 135 | normalized = [ |
| 136 | normalizer(source, item, index, from_date, to_date) |
| 137 | for index, item in enumerate(items) |
| 138 | ] |
| 139 | if source == "arxiv": |
| 140 | # The adapter owns arXiv's 365-day recency contract. Applying the |
| 141 | # report window again here drops relevant papers the adapter accepted. |
| 142 | return normalized |
| 143 | if source == "jobs": |
| 144 | # A careers board is a snapshot of CURRENTLY OPEN roles. An open posting |
| 145 | # is current evidence regardless of when it was posted, so date-windowing |
| 146 | # it drops still-open roles (the "Founding Research Scientist, Human |
| 147 | # Simulation" miss: 26 open roles filtered to 3 by a 30-day window). |
| 148 | # Keep the full board; recency is annotated, not used to drop. |
| 149 | return normalized |
| 150 | require_date = source == "grounding" |
| 151 | filtered = filter_by_date_range( |
| 152 | normalized, from_date, to_date, require_date=require_date |
| 153 | ) |
| 154 | if filtered: |
| 155 | return filtered |
| 156 | # For evergreen_ok, YouTube search keeps out-of-window videos when fewer |
| 157 | # than 3 are recent, then pays for transcripts. A second hard date filter |
| 158 | # here dropped those transcribed items to zero (#1043). Keep |
| 159 | # transcript-backed retrieved items instead of paying for transcripts that |
| 160 | # never appear in the brief. Metadata-only / caption-failed videos are not |
| 161 | # that rescue. Recent modes (strict_recent / balanced_recent) get no |
| 162 | # rescue: years-old videos on a recent topic are noise, not evidence. |
| 163 | if freshness_mode == "evergreen_ok" and source == "youtube" and normalized: |
| 164 | transcribed = [ |
| 165 | item for item in normalized if str(item.snippet or "").strip() |
| 166 | ] |
| 167 | if transcribed: |
| 168 | if require_date: |
| 169 | dated = [item for item in transcribed if item.published_at] |
| 170 | return dated or transcribed |
| 171 | return transcribed |
| 172 | if freshness_mode == "evergreen_ok" and source == "youtube": |
| 173 | if require_date: |
| 174 | return [item for item in normalized if item.published_at] |
| 175 | return normalized |
| 176 | return filtered |
| 177 | |
| 178 | |
| 179 | def _remap_comments( |
| 180 | raw: list[Any], |
| 181 | score_keys: tuple[str, ...], |
| 182 | excerpt_keys: tuple[str, ...], |
| 183 | *, |
| 184 | preserve_absent_score: bool = False, |
| 185 | ) -> list[dict[str, Any]]: |
| 186 | """Normalize comments from any source into the shared Reddit-compatible shape. |
| 187 | |
| 188 | Downstream code (signals._top_comment_score, render._top_comments_list, |
| 189 | entity_extract, rerank) all expect `score` and `excerpt`. This helper maps |
| 190 | per-source field names (YT: likes/text, TikTok: digg_count/text) onto that |
| 191 | shape while preserving author/date/url passthrough. |
| 192 | |
| 193 | Sources that distinguish an absent vote from a measured zero can opt into |
| 194 | preserving the absent value as ``None``. |
| 195 | """ |
| 196 | out: list[dict[str, Any]] = [] |
| 197 | for raw_c in raw: |
| 198 | if not isinstance(raw_c, dict): |
| 199 | continue |
| 200 | score = _first_present( |
| 201 | raw_c, |
| 202 | score_keys, |
| 203 | default=None if preserve_absent_score else 0, |
| 204 | ) |
| 205 | excerpt = _first_present(raw_c, excerpt_keys, default="") |
| 206 | if score is None and preserve_absent_score: |
| 207 | normalized_score = None |
| 208 | else: |
| 209 | try: |
| 210 | normalized_score = int(score or 0) |
| 211 | except (TypeError, ValueError): |
| 212 | normalized_score = 0 |
| 213 | entry: dict[str, Any] = { |
| 214 | "score": normalized_score, |
| 215 | "excerpt": str(excerpt or "")[:400], |
| 216 | "author": str(raw_c.get("author") or ""), |
| 217 | "date": str(raw_c.get("date") or ""), |
| 218 | } |
| 219 | if raw_c.get("url"): |
| 220 | entry["url"] = str(raw_c["url"]) |
| 221 | # Whether the item's own author wrote the comment, where the source |
| 222 | # said so. A comment stored without the key is unknown. |
| 223 | if isinstance(raw_c.get("is_uploader"), bool): |
| 224 | entry["is_uploader"] = raw_c["is_uploader"] |
| 225 | out.append(entry) |
| 226 | return out |
| 227 | |
| 228 | |
| 229 | def _first_present(d: dict[str, Any], keys: tuple[str, ...], default: Any) -> Any: |
| 230 | for key in keys: |
| 231 | if key in d and d[key] not in (None, ""): |
| 232 | return d[key] |
| 233 | return default |
| 234 | |
| 235 | |
| 236 | def _join_comment_excerpts( |
| 237 | top_comments: list[Any], |
| 238 | key: str, |
| 239 | limit: int = 3, |
| 240 | ) -> str: |
| 241 | """Space-join the `key` field from the first `limit` dict-shaped comments.""" |
| 242 | return " ".join( |
| 243 | str(comment.get(key) or "").strip() |
| 244 | for comment in top_comments[:limit] |
| 245 | if isinstance(comment, dict) |
| 246 | ) |
| 247 | |
| 248 | |
| 249 | def _domain_from_url(url: str) -> str | None: |
| 250 | if not url: |
| 251 | return None |
| 252 | domain = urlparse(url).netloc.strip().lower() |
| 253 | return domain or None |
| 254 | |
| 255 | |
| 256 | def _date_confidence( |
| 257 | item: dict[str, Any], from_date: str, to_date: str, default: str = "low" |
| 258 | ) -> str: |
| 259 | if item.get("date_confidence"): |
| 260 | return str(item["date_confidence"]) |
| 261 | date_value = item.get("date") |
| 262 | if not date_value: |
| 263 | return default |
| 264 | return dates.get_date_confidence(str(date_value), from_date, to_date) |
| 265 | |
| 266 | |
| 267 | def _source_item( |
| 268 | *, |
| 269 | item_id: str, |
| 270 | source: str, |
| 271 | title: str, |
| 272 | body: str, |
| 273 | url: str, |
| 274 | published_at: str | None, |
| 275 | date_confidence: str, |
| 276 | relevance_hint: float, |
| 277 | why_relevant: str, |
| 278 | author: str | None = None, |
| 279 | container: str | None = None, |
| 280 | engagement: dict[str, float | int] | None = None, |
| 281 | snippet: str = "", |
| 282 | metadata: dict[str, Any] | None = None, |
| 283 | ) -> schema.SourceItem: |
| 284 | return schema.SourceItem( |
| 285 | item_id=item_id, |
| 286 | source=source, |
| 287 | title=title.strip() or body.strip()[:160] or item_id, |
| 288 | body=body.strip(), |
| 289 | url=url.strip(), |
| 290 | author=(author or "").strip() or None, |
| 291 | container=(container or "").strip() or None, |
| 292 | published_at=published_at, |
| 293 | date_confidence=date_confidence, |
| 294 | engagement=engagement or {}, |
| 295 | relevance_hint=max(0.0, min(1.0, float(relevance_hint or 0.0))), |
| 296 | why_relevant=why_relevant.strip(), |
| 297 | snippet=snippet.strip(), |
| 298 | metadata=metadata or {}, |
| 299 | ) |
| 300 | |
| 301 | |
| 302 | def _normalize_stocktwits( |
| 303 | source: str, |
| 304 | item: dict[str, Any], |
| 305 | index: int, |
| 306 | from_date: str, |
| 307 | to_date: str, |
| 308 | ) -> schema.SourceItem: |
| 309 | meta = item.get("metadata") or {} |
| 310 | return _source_item( |
| 311 | item_id=str(item.get("id") or f"ST{index + 1}"), |
| 312 | source=source, |
| 313 | title=str(item.get("title") or ""), |
| 314 | body=str(item.get("snippet") or ""), |
| 315 | url=str(item.get("url") or ""), |
| 316 | author=str(item.get("author") or "") or None, |
| 317 | container=str(meta.get("symbol") or "") or None, |
| 318 | published_at=item.get("date"), |
| 319 | date_confidence=_date_confidence(item, from_date, to_date, default="high"), |
| 320 | engagement=item.get("engagement") or {}, |
| 321 | relevance_hint=item.get("relevance", 0.7), |
| 322 | why_relevant=str(item.get("why_relevant") or ""), |
| 323 | snippet=str(item.get("snippet") or "")[:400], |
| 324 | metadata=meta, # carries sentiment + symbol-level bull/bear aggregate |
| 325 | ) |
| 326 | |
| 327 | |
| 328 | def _normalize_dripstack( |
| 329 | source: str, |
| 330 | item: dict[str, Any], |
| 331 | index: int, |
| 332 | from_date: str, |
| 333 | to_date: str, |
| 334 | ) -> schema.SourceItem: |
| 335 | """Normalizer for DripStack newsletter search results. |
| 336 | |
| 337 | DripStack returns article metadata from paid financial newsletters. |
| 338 | No engagement signal — ranking relies on DripStack's own relevanceScore |
| 339 | (0-100, normalized to 0-1) plus recency. The publication name serves as |
| 340 | author/attribution (e.g. "SemiAnalysis", "Bloomberg"). |
| 341 | """ |
| 342 | meta = item.get("metadata") or {} |
| 343 | return _source_item( |
| 344 | item_id=str(item.get("id") or f"DS{index + 1}"), |
| 345 | source=source, |
| 346 | title=str(item.get("title") or ""), |
| 347 | body=str(item.get("body") or "") |
| 348 | or str(item.get("snippet") or "") |
| 349 | or str(item.get("title") or ""), |
| 350 | url=str(item.get("url") or ""), |
| 351 | author=str(item.get("author") or "") or None, |
| 352 | container=str(meta.get("publication_slug") or "") or None, |
| 353 | published_at=item.get("date"), |
| 354 | date_confidence=_date_confidence(item, from_date, to_date, default="high"), |
| 355 | engagement={}, |
| 356 | relevance_hint=item.get("relevance", 0.5), |
| 357 | why_relevant=str(item.get("why_relevant") or ""), |
| 358 | snippet=str(item.get("snippet") or "")[:400], |
| 359 | metadata={ |
| 360 | **meta, |
| 361 | "publication_slug": meta.get("publication_slug"), |
| 362 | }, |
| 363 | ) |
| 364 | |
| 365 | |
| 366 | def _normalize_reddit( |
| 367 | source: str, |
| 368 | item: dict[str, Any], |
| 369 | index: int, |
| 370 | from_date: str, |
| 371 | to_date: str, |
| 372 | ) -> schema.SourceItem: |
| 373 | top_comments = item.get("top_comments") or [] |
| 374 | comment_text = _join_comment_excerpts(top_comments, "excerpt") |
| 375 | post_author = str(item.get("author") or "").strip() |
| 376 | if post_author.lower().removeprefix("/").removeprefix("u/") in ("", "[deleted]", "[removed]"): |
| 377 | post_author = "" |
| 378 | body = "\n".join( |
| 379 | part |
| 380 | for part in [ |
| 381 | str(item.get("title") or "").strip(), |
| 382 | str(item.get("selftext") or "").strip(), |
| 383 | comment_text, |
| 384 | ] |
| 385 | if part |
| 386 | ) |
| 387 | return _source_item( |
| 388 | item_id=str(item.get("id") or f"R{index + 1}"), |
| 389 | source=source, |
| 390 | title=str(item.get("title") or ""), |
| 391 | body=body, |
| 392 | url=str(item.get("url") or ""), |
| 393 | author=None, |
| 394 | container=str(item.get("subreddit") or ""), |
| 395 | published_at=item.get("date"), |
| 396 | date_confidence=_date_confidence(item, from_date, to_date), |
| 397 | engagement=item.get("engagement") or {}, |
| 398 | relevance_hint=item.get("relevance", 0.5), |
| 399 | why_relevant=str(item.get("why_relevant") or ""), |
| 400 | snippet=comment_text or str(item.get("selftext") or "")[:400], |
| 401 | metadata={ |
| 402 | "top_comments": top_comments, |
| 403 | "comment_insights": item.get("comment_insights") or [], |
| 404 | # Preserve the OP username for post-normalization comment enrichment |
| 405 | # while keeping SourceItem.author = None on Reddit items. |
| 406 | **({"post_author": post_author} if post_author else {}), |
| 407 | # Where the score and the comments came from (reddit_refs labels), |
| 408 | # so a merge keeps the live score and render can say "score pending". |
| 409 | **{ |
| 410 | key: item[key] |
| 411 | for key in ("engagement_source", "comments_source") |
| 412 | if item.get(key) |
| 413 | }, |
| 414 | # The comment a logged-in comment search matched: its date keeps |
| 415 | # an older thread in the window, and render labels it. Never attach |
| 416 | # a reply outside the requested [from_date, to_date] window (e.g., |
| 417 | # post-cutoff replies in an --as-of run). |
| 418 | **( |
| 419 | { |
| 420 | "matched_comment_date": str(item["matched_comment"]["date"]).strip(), |
| 421 | "matched_comment_url": item["matched_comment"].get("url") or "", |
| 422 | } |
| 423 | if isinstance(item.get("matched_comment"), dict) |
| 424 | and _matched_date_in_window( |
| 425 | str(item["matched_comment"].get("date") or ""), from_date, to_date, |
| 426 | ) |
| 427 | else {} |
| 428 | ), |
| 429 | }, |
| 430 | ) |
| 431 | |
| 432 | |
| 433 | def _normalize_x( |
| 434 | source: str, |
| 435 | item: dict[str, Any], |
| 436 | index: int, |
| 437 | from_date: str, |
| 438 | to_date: str, |
| 439 | ) -> schema.SourceItem: |
| 440 | # X returns post text HTML-escaped ("Tom & Jerry"). Use x_envelope's |
| 441 | # guarded unescape + control-char stripping + markup defanging so oversized |
| 442 | # numeric entities cannot crash normalization and encoded tokens cannot |
| 443 | # bypass sanitization. |
| 444 | text = x_envelope._clean_text(str(item.get("text") or "")).strip() |
| 445 | mentioned = item.get("mentioned_handles") or [] |
| 446 | return _source_item( |
| 447 | item_id=str(item.get("id") or f"X{index + 1}"), |
| 448 | source=source, |
| 449 | title=text[:140] or f"X post {index + 1}", |
| 450 | body=text, |
| 451 | url=str(item.get("url") or ""), |
| 452 | author=str(item.get("author_handle") or "").lstrip("@"), |
| 453 | published_at=item.get("date"), |
| 454 | date_confidence=_date_confidence(item, from_date, to_date), |
| 455 | engagement=item.get("engagement") or {}, |
| 456 | relevance_hint=item.get("relevance", 0.5), |
| 457 | why_relevant=str(item.get("why_relevant") or ""), |
| 458 | metadata={"mentioned_handles": list(mentioned)} if mentioned else {}, |
| 459 | ) |
| 460 | |
| 461 | |
| 462 | def _normalize_jobs( |
| 463 | source: str, |
| 464 | item: dict[str, Any], |
| 465 | index: int, |
| 466 | from_date: str, |
| 467 | to_date: str, |
| 468 | ) -> schema.SourceItem: |
| 469 | description = str(item.get("description") or item.get("snippet") or "").strip() |
| 470 | title = str(item.get("title") or "").strip() |
| 471 | department = str(item.get("department") or "").strip() |
| 472 | location = str(item.get("location") or "").strip() |
| 473 | # The body keeps the reader's paragraph breaks (``description_blocks``) so |
| 474 | # Hiring Signals can split company text from role text even when an HTML |
| 475 | # paragraph has no ending punctuation; the snippet stays the flat text. |
| 476 | blocks = str(item.get("description_blocks") or "").strip() |
| 477 | body = "\n".join( |
| 478 | part for part in [title, department, location, blocks or description] if part |
| 479 | ) |
| 480 | provider = str(item.get("provider") or "").strip() |
| 481 | return _source_item( |
| 482 | item_id=str(item.get("id") or f"J{index + 1}"), |
| 483 | source=source, |
| 484 | title=title or f"Job posting {index + 1}", |
| 485 | body=body, |
| 486 | url=str(item.get("url") or ""), |
| 487 | author=provider or None, |
| 488 | container=department or None, |
| 489 | published_at=item.get("date"), |
| 490 | date_confidence=_date_confidence(item, from_date, to_date), |
| 491 | engagement={"open_roles": 1}, |
| 492 | relevance_hint=item.get("relevance", 0.65), |
| 493 | why_relevant=str(item.get("why_relevant") or "Public job posting"), |
| 494 | snippet=description[:500], |
| 495 | metadata={ |
| 496 | "provider": provider, |
| 497 | "department": department, |
| 498 | "departments": item.get("departments") |
| 499 | or ([department] if department else []), |
| 500 | "location": location, |
| 501 | "offices": item.get("offices") or [], |
| 502 | "board_token": item.get("board_token") or "", |
| 503 | "source_url": item.get("source_url") or "", |
| 504 | "source_domain": item.get("source_domain") |
| 505 | or _domain_from_url(str(item.get("url") or "")) |
| 506 | or "", |
| 507 | }, |
| 508 | ) |
| 509 | |
| 510 | |
| 511 | def _normalize_youtube( |
| 512 | source: str, |
| 513 | item: dict[str, Any], |
| 514 | index: int, |
| 515 | from_date: str, |
| 516 | to_date: str, |
| 517 | ) -> schema.SourceItem: |
| 518 | transcript = str(item.get("transcript_snippet") or "").strip() |
| 519 | description = str(item.get("description") or "").strip() |
| 520 | title = str(item.get("title") or "").strip() |
| 521 | highlights = item.get("transcript_highlights") or [] |
| 522 | metadata: dict[str, Any] = {} |
| 523 | if highlights: |
| 524 | metadata["transcript_highlights"] = highlights |
| 525 | if item.get("captions_disabled"): |
| 526 | # Surfaced for quality_nudge: uploader disabled captions, so this |
| 527 | # video should be subtracted from the degraded-transcript-ratio |
| 528 | # denominator (it was never going to produce a transcript). |
| 529 | metadata["captions_disabled"] = True |
| 530 | metadata["top_comments"] = _remap_comments( |
| 531 | item.get("top_comments") or [], |
| 532 | score_keys=("score", "likes"), |
| 533 | excerpt_keys=("excerpt", "text"), |
| 534 | ) |
| 535 | return _source_item( |
| 536 | item_id=str(item.get("video_id") or item.get("id") or f"YT{index + 1}"), |
| 537 | source=source, |
| 538 | title=title, |
| 539 | body="\n".join(part for part in [title, description, transcript] if part), |
| 540 | url=str(item.get("url") or ""), |
| 541 | author=str(item.get("channel_name") or ""), |
| 542 | published_at=item.get("date"), |
| 543 | date_confidence=_date_confidence(item, from_date, to_date, default="high"), |
| 544 | engagement=item.get("engagement") or {}, |
| 545 | relevance_hint=item.get("relevance", 0.5), |
| 546 | why_relevant=str(item.get("why_relevant") or ""), |
| 547 | snippet=transcript, |
| 548 | metadata=metadata, |
| 549 | ) |
| 550 | |
| 551 | |
| 552 | def _normalize_shortform_video( |
| 553 | source: str, |
| 554 | item: dict[str, Any], |
| 555 | index: int, |
| 556 | from_date: str, |
| 557 | to_date: str, |
| 558 | id_prefix: str, |
| 559 | default_title: str, |
| 560 | ) -> schema.SourceItem: |
| 561 | """Shared normalizer for TikTok and Instagram (identical structure).""" |
| 562 | caption = str(item.get("caption_snippet") or "").strip() |
| 563 | text = str(item.get("text") or "").strip() |
| 564 | return _source_item( |
| 565 | item_id=str(item.get("id") or f"{id_prefix}{index + 1}"), |
| 566 | source=source, |
| 567 | title=text[:140] or caption[:140] or f"{default_title} {index + 1}", |
| 568 | body="\n".join(part for part in [text, caption] if part), |
| 569 | url=str(item.get("url") or ""), |
| 570 | author=str(item.get("author_name") or ""), |
| 571 | published_at=item.get("date"), |
| 572 | date_confidence=_date_confidence(item, from_date, to_date, default="high"), |
| 573 | engagement=item.get("engagement") or {}, |
| 574 | relevance_hint=item.get("relevance", 0.5), |
| 575 | why_relevant=str(item.get("why_relevant") or ""), |
| 576 | snippet=caption, |
| 577 | metadata={ |
| 578 | "hashtags": item.get("hashtags") or [], |
| 579 | # True only when the snippet is a spoken-word transcript, not the |
| 580 | # written description fetch_captions starts from. |
| 581 | "spoken_caption": bool(item.get("caption_is_transcript")), |
| 582 | # Found by the host's own web search (--shortform-urls); the |
| 583 | # footer names that lane. |
| 584 | "host_search": bool(item.get("_host_found")), |
| 585 | "top_comments": _remap_comments( |
| 586 | item.get("top_comments") or [], |
| 587 | # Instagram comments use comment_like_count as the vote field |
| 588 | # (ScrapeCreators /v2/instagram/post/comments); digg_count/likes |
| 589 | # kept for shape compatibility. |
| 590 | score_keys=("score", "comment_like_count", "digg_count", "likes"), |
| 591 | excerpt_keys=("excerpt", "text"), |
| 592 | ), |
| 593 | }, |
| 594 | ) |
| 595 | |
| 596 | |
| 597 | def _normalize_pinterest( |
| 598 | source: str, |
| 599 | item: dict[str, Any], |
| 600 | index: int, |
| 601 | from_date: str, |
| 602 | to_date: str, |
| 603 | ) -> schema.SourceItem: |
| 604 | """Normalizer for Pinterest pins (visual content with descriptions). |
| 605 | |
| 606 | Saves are the primary engagement signal, analogous to likes/upvotes. |
| 607 | """ |
| 608 | description = str(item.get("description") or "").strip() |
| 609 | return _source_item( |
| 610 | item_id=str(item.get("pin_id") or item.get("id") or f"PI{index + 1}"), |
| 611 | source=source, |
| 612 | title=description[:140] or f"Pinterest pin {index + 1}", |
| 613 | body=description, |
| 614 | url=str(item.get("url") or ""), |
| 615 | author=str(item.get("author") or ""), |
| 616 | container=str(item.get("board") or ""), |
| 617 | published_at=item.get("date"), |
| 618 | date_confidence=_date_confidence(item, from_date, to_date, default="low"), |
| 619 | engagement=item.get("engagement") or {}, |
| 620 | relevance_hint=item.get("relevance", 0.5), |
| 621 | why_relevant=str(item.get("why_relevant") or ""), |
| 622 | snippet=description[:400], |
| 623 | ) |
| 624 | |
| 625 | |
| 626 | def _normalize_devto( |
| 627 | source: str, |
| 628 | item: dict[str, Any], |
| 629 | index: int, |
| 630 | from_date: str, |
| 631 | to_date: str, |
| 632 | ) -> schema.SourceItem: |
| 633 | top_comments = _remap_comments( |
| 634 | item.get("top_comments") or [], |
| 635 | score_keys=("replies",), |
| 636 | excerpt_keys=("text", "excerpt"), |
| 637 | preserve_absent_score=True, |
| 638 | ) |
| 639 | comment_text = _join_comment_excerpts(top_comments, "excerpt") |
| 640 | title = str(item.get("title") or "").strip() |
| 641 | description = str(item.get("text") or "").strip() |
| 642 | body = "\n".join(part for part in [title, description, comment_text] if part) |
| 643 | return _source_item( |
| 644 | item_id=str(item.get("id") or f"DEV{index + 1}"), |
| 645 | source=source, |
| 646 | title=title or f"dev.to article {index + 1}", |
| 647 | body=body, |
| 648 | url=str(item.get("url") or ""), |
| 649 | author=str(item.get("author") or ""), |
| 650 | container="dev.to", |
| 651 | published_at=item.get("date"), |
| 652 | date_confidence=_date_confidence(item, from_date, to_date, default="high"), |
| 653 | engagement=item.get("engagement") or {}, |
| 654 | relevance_hint=item.get("relevance", 0.5), |
| 655 | why_relevant=str(item.get("why_relevant") or ""), |
| 656 | snippet=description or comment_text, |
| 657 | metadata={**(item.get("metadata") or {}), "top_comments": top_comments}, |
| 658 | ) |
| 659 | |
| 660 | |
| 661 | def _normalize_juejin( |
| 662 | source: str, |
| 663 | item: dict[str, Any], |
| 664 | index: int, |
| 665 | from_date: str, |
| 666 | to_date: str, |
| 667 | ) -> schema.SourceItem: |
| 668 | top_comments = _remap_comments( |
| 669 | item.get("top_comments") or [], |
| 670 | score_keys=("score", "likes"), |
| 671 | excerpt_keys=("text", "excerpt"), |
| 672 | ) |
| 673 | comment_text = _join_comment_excerpts(top_comments, "excerpt") |
| 674 | title = str(item.get("title") or "").strip() |
| 675 | description = str(item.get("text") or "").strip() |
| 676 | body = "\n".join(part for part in [title, description, comment_text] if part) |
| 677 | return _source_item( |
| 678 | item_id=str(item.get("id") or f"JJ{index + 1}"), |
| 679 | source=source, |
| 680 | title=title or f"Juejin article {index + 1}", |
| 681 | body=body, |
| 682 | url=str(item.get("url") or ""), |
| 683 | author=str(item.get("author") or ""), |
| 684 | container="Juejin", |
| 685 | published_at=item.get("date"), |
| 686 | date_confidence=_date_confidence(item, from_date, to_date, default="low"), |
| 687 | engagement=item.get("engagement") or {}, |
| 688 | relevance_hint=item.get("relevance", 0.5), |
| 689 | why_relevant=str(item.get("why_relevant") or ""), |
| 690 | snippet=description or comment_text, |
| 691 | metadata={**(item.get("metadata") or {}), "top_comments": top_comments}, |
| 692 | ) |
| 693 | |
| 694 | |
| 695 | def _normalize_v2ex( |
| 696 | source: str, |
| 697 | item: dict[str, Any], |
| 698 | index: int, |
| 699 | from_date: str, |
| 700 | to_date: str, |
| 701 | ) -> schema.SourceItem: |
| 702 | top_comments = _remap_comments( |
| 703 | item.get("top_comments") or [], |
| 704 | score_keys=("score",), |
| 705 | excerpt_keys=("text", "excerpt"), |
| 706 | preserve_absent_score=True, |
| 707 | ) |
| 708 | comment_text = _join_comment_excerpts(top_comments, "excerpt") |
| 709 | title = str(item.get("title") or "").strip() |
| 710 | content = str(item.get("text") or "").strip() |
| 711 | body = "\n".join(part for part in [title, content, comment_text] if part) |
| 712 | return _source_item( |
| 713 | item_id=str(item.get("id") or f"V2EX{index + 1}"), |
| 714 | source=source, |
| 715 | title=title or f"V2EX topic {index + 1}", |
| 716 | body=body, |
| 717 | url=str(item.get("url") or ""), |
| 718 | author=str(item.get("author") or ""), |
| 719 | container="V2EX", |
| 720 | published_at=item.get("date"), |
| 721 | date_confidence=_date_confidence(item, from_date, to_date, default="high"), |
| 722 | engagement=item.get("engagement") or {}, |
| 723 | relevance_hint=item.get("relevance", 0.5), |
| 724 | why_relevant=str(item.get("why_relevant") or ""), |
| 725 | snippet=content or comment_text, |
| 726 | metadata={**(item.get("metadata") or {}), "top_comments": top_comments}, |
| 727 | ) |
| 728 | |
| 729 | |
| 730 | def _normalize_hackernews( |
| 731 | source: str, |
| 732 | item: dict[str, Any], |
| 733 | index: int, |
| 734 | from_date: str, |
| 735 | to_date: str, |
| 736 | ) -> schema.SourceItem: |
| 737 | # HN comments arrive as {author, text, points}; downstream code keys on |
| 738 | # score/excerpt, so remap here exactly as the YouTube and TikTok normalisers |
| 739 | # do. Without this the per-source floor in render._top_comments_list reads a |
| 740 | # `score` that is never present and rejects every HN comment. |
| 741 | top_comments = _remap_comments( |
| 742 | item.get("top_comments") or [], |
| 743 | score_keys=("points", "score"), |
| 744 | excerpt_keys=("text", "excerpt"), |
| 745 | preserve_absent_score=True, |
| 746 | ) |
| 747 | comment_text = _join_comment_excerpts(top_comments, "excerpt") |
| 748 | title = str(item.get("title") or "").strip() |
| 749 | body = "\n".join( |
| 750 | part |
| 751 | for part in [title, str(item.get("text") or "").strip(), comment_text] |
| 752 | if part |
| 753 | ) |
| 754 | return _source_item( |
| 755 | item_id=str(item.get("id") or f"HN{index + 1}"), |
| 756 | source=source, |
| 757 | title=title or f"HN story {index + 1}", |
| 758 | body=body, |
| 759 | url=str(item.get("url") or item.get("hn_url") or ""), |
| 760 | author=str(item.get("author") or ""), |
| 761 | container="Hacker News", |
| 762 | published_at=item.get("date"), |
| 763 | date_confidence=_date_confidence(item, from_date, to_date, default="high"), |
| 764 | engagement=item.get("engagement") or {}, |
| 765 | relevance_hint=item.get("relevance", 0.5), |
| 766 | why_relevant=str(item.get("why_relevant") or ""), |
| 767 | snippet=comment_text, |
| 768 | metadata={ |
| 769 | "hn_url": item.get("hn_url"), |
| 770 | "top_comments": top_comments, |
| 771 | "comment_insights": item.get("comment_insights") or [], |
| 772 | }, |
| 773 | ) |
| 774 | |
| 775 | |
| 776 | def _normalize_microblog( |
| 777 | source: str, |
| 778 | item: dict[str, Any], |
| 779 | index: int, |
| 780 | from_date: str, |
| 781 | to_date: str, |
| 782 | id_prefix: str, |
| 783 | default_title: str, |
| 784 | ) -> schema.SourceItem: |
| 785 | """Shared normalizer for Bluesky and Truth Social (identical structure).""" |
| 786 | text = str(item.get("text") or "").strip() |
| 787 | return _source_item( |
| 788 | item_id=str(item.get("id") or f"{id_prefix}{index + 1}"), |
| 789 | source=source, |
| 790 | title=text[:140] or f"{default_title} {index + 1}", |
| 791 | body=text, |
| 792 | url=str(item.get("url") or ""), |
| 793 | author=str(item.get("handle") or item.get("author_handle") or "").lstrip("@"), |
| 794 | published_at=item.get("date"), |
| 795 | date_confidence=_date_confidence(item, from_date, to_date, default="high"), |
| 796 | engagement=item.get("engagement") or {}, |
| 797 | relevance_hint=item.get("relevance", 0.5), |
| 798 | why_relevant=str(item.get("why_relevant") or ""), |
| 799 | metadata={"display_name": item.get("display_name")}, |
| 800 | ) |
| 801 | |
| 802 | |
| 803 | def _normalize_digg( |
| 804 | source: str, |
| 805 | item: dict[str, Any], |
| 806 | index: int, |
| 807 | from_date: str, |
| 808 | to_date: str, |
| 809 | ) -> schema.SourceItem: |
| 810 | """Normalizer for Digg clusters. |
| 811 | |
| 812 | Each cluster is one item. The TLDR carries the most useful body for |
| 813 | rerank and synthesis. Top-ranked X posts attached at search time are |
| 814 | passed through under metadata['posts'] so render can emit them as |
| 815 | inline 'via Digg' quotes. A story from the all-topic search also |
| 816 | carries its UUID, topic and canonical URL in metadata; the UUID is |
| 817 | what story-scoped CLI commands take. |
| 818 | """ |
| 819 | title = str(item.get("title") or "").strip() |
| 820 | tldr = str(item.get("tldr") or "").strip() |
| 821 | body = "\n\n".join(part for part in [title, tldr] if part) |
| 822 | posts = item.get("posts") or [] |
| 823 | if not isinstance(posts, list): |
| 824 | posts = [] |
| 825 | cluster_url_id = str(item.get("id") or f"DG{index + 1}") |
| 826 | metadata = { |
| 827 | "clusterUrlId": cluster_url_id, |
| 828 | "tldr": tldr, |
| 829 | "rank": (item.get("engagement") or {}).get("rank"), |
| 830 | "uniqueAuthors": (item.get("engagement") or {}).get("uniqueAuthors"), |
| 831 | "postCount": (item.get("engagement") or {}).get("postCount"), |
| 832 | "firstPostAge": item.get("first_post_age"), |
| 833 | "posts": posts, |
| 834 | } |
| 835 | if item.get("cluster_id"): |
| 836 | metadata["clusterId"] = item["cluster_id"] |
| 837 | metadata["topic"] = item.get("topic") or "" |
| 838 | metadata["url"] = item.get("url") |
| 839 | return _source_item( |
| 840 | item_id=cluster_url_id, |
| 841 | source=source, |
| 842 | title=title or f"Digg cluster {index + 1}", |
| 843 | body=body, |
| 844 | url=str(item.get("url") or f"https://digg.com/ai/{cluster_url_id}"), |
| 845 | author="", |
| 846 | container="Digg", |
| 847 | published_at=item.get("date"), |
| 848 | date_confidence=_date_confidence(item, from_date, to_date, default="high"), |
| 849 | engagement=item.get("engagement") or {}, |
| 850 | relevance_hint=item.get("relevance", 0.5), |
| 851 | why_relevant=str(item.get("why_relevant") or ""), |
| 852 | snippet=tldr[:400], |
| 853 | metadata=metadata, |
| 854 | ) |
| 855 | |
| 856 | |
| 857 | def _normalize_arxiv( |
| 858 | source: str, |
| 859 | item: dict[str, Any], |
| 860 | index: int, |
| 861 | from_date: str, |
| 862 | to_date: str, |
| 863 | ) -> schema.SourceItem: |
| 864 | """Normalizer for arXiv papers. |
| 865 | |
| 866 | The abstract (summary) is the body that feeds rerank and synthesis. arXiv |
| 867 | has no engagement signal, so engagement is empty and ranking leans on |
| 868 | relevance and recency. |
| 869 | """ |
| 870 | title = str(item.get("title") or "").strip() |
| 871 | summary = str(item.get("summary") or "").strip() |
| 872 | body = "\n\n".join(part for part in [title, summary] if part) |
| 873 | authors = item.get("authors") or [] |
| 874 | if not isinstance(authors, list): |
| 875 | authors = [] |
| 876 | paper_id = str(item.get("id") or f"AX{index + 1}") |
| 877 | return _source_item( |
| 878 | item_id=paper_id, |
| 879 | source=source, |
| 880 | title=title or f"arXiv paper {index + 1}", |
| 881 | body=body, |
| 882 | url=str(item.get("url") or ""), |
| 883 | author=str(item.get("author") or "") or None, |
| 884 | container="arXiv", |
| 885 | published_at=item.get("date"), |
| 886 | date_confidence=_date_confidence(item, from_date, to_date, default="high"), |
| 887 | engagement={}, |
| 888 | relevance_hint=item.get("relevance", 0.5), |
| 889 | why_relevant=str(item.get("why_relevant") or ""), |
| 890 | snippet=summary[:400], |
| 891 | metadata={ |
| 892 | "authors": authors, |
| 893 | "summary": summary, |
| 894 | }, |
| 895 | ) |
| 896 | |
| 897 | |
| 898 | def _normalize_techmeme( |
| 899 | source: str, |
| 900 | item: dict[str, Any], |
| 901 | index: int, |
| 902 | from_date: str, |
| 903 | to_date: str, |
| 904 | ) -> schema.SourceItem: |
| 905 | """Normalizer for Techmeme headlines. |
| 906 | |
| 907 | The headline is both title and body (Techmeme carries no abstract). The |
| 908 | publication is the container/author. No engagement signal in the search |
| 909 | shape, so ranking leans on relevance and recency. |
| 910 | """ |
| 911 | title = str(item.get("title") or "").strip() |
| 912 | source_name = str(item.get("source_name") or "").strip() |
| 913 | return _source_item( |
| 914 | item_id=str(item.get("id") or f"TM{index + 1}"), |
| 915 | source=source, |
| 916 | title=title or f"Techmeme headline {index + 1}", |
| 917 | body=title, |
| 918 | url=str(item.get("url") or ""), |
| 919 | author=source_name or None, |
| 920 | container=source_name or "Techmeme", |
| 921 | published_at=item.get("date"), |
| 922 | date_confidence=_date_confidence(item, from_date, to_date, default="low"), |
| 923 | engagement={}, |
| 924 | relevance_hint=item.get("relevance", 0.5), |
| 925 | why_relevant=str(item.get("why_relevant") or ""), |
| 926 | snippet=title[:400], |
| 927 | metadata={ |
| 928 | "publication": source_name, |
| 929 | }, |
| 930 | ) |
| 931 | |
| 932 | |
| 933 | def _normalize_news_rss( |
| 934 | source: str, |
| 935 | item: dict[str, Any], |
| 936 | index: int, |
| 937 | from_date: str, |
| 938 | to_date: str, |
| 939 | ) -> schema.SourceItem: |
| 940 | """Normalizer for mainstream news & OPML RSS stories (news-rss-pp-cli). |
| 941 | |
| 942 | Uses the headline as title and the article summary (or truncated newsletter |
| 943 | body) as body/snippet. Publisher sits in author/container, and multi-outlet |
| 944 | corroboration count + outlets travel in metadata. |
| 945 | """ |
| 946 | title = str(item.get("title") or "").strip() |
| 947 | summary = str(item.get("summary") or "").strip() |
| 948 | publisher = str(item.get("publisher") or "").strip() |
| 949 | domain = str(item.get("publisher_domain") or "").strip() |
| 950 | body = summary if summary and summary != title else title |
| 951 | raw_cluster = item.get("cluster_count") |
| 952 | try: |
| 953 | cluster_count = max(1, int(raw_cluster)) if raw_cluster is not None else 1 |
| 954 | except (TypeError, ValueError): |
| 955 | cluster_count = 1 |
| 956 | metadata: dict[str, Any] = { |
| 957 | "publication": publisher, |
| 958 | "publisher_domain": domain, |
| 959 | "cluster_count": cluster_count, |
| 960 | "rss_source": str(item.get("rss_source") or ""), |
| 961 | } |
| 962 | outlets = item.get("cluster_outlets") |
| 963 | if isinstance(outlets, list) and outlets: |
| 964 | metadata["cluster_outlets"] = [str(o) for o in outlets if str(o).strip()] |
| 965 | return _source_item( |
| 966 | item_id=str(item.get("id") or f"NR{index + 1}"), |
| 967 | source=source, |
| 968 | title=title or f"News RSS story {index + 1}", |
| 969 | body=body, |
| 970 | url=str(item.get("url") or ""), |
| 971 | author=publisher or domain or None, |
| 972 | container=publisher or domain or "News RSS", |
| 973 | published_at=item.get("date"), |
| 974 | date_confidence=_date_confidence(item, from_date, to_date, default="low"), |
| 975 | engagement={}, |
| 976 | relevance_hint=item.get("relevance", 0.5), |
| 977 | why_relevant=str(item.get("why_relevant") or ""), |
| 978 | snippet=(summary or title)[:400], |
| 979 | metadata=metadata, |
| 980 | ) |
| 981 | |
| 982 | |
| 983 | def _normalize_meta_ads( |
| 984 | source: str, |
| 985 | item: dict[str, Any], |
| 986 | index: int, |
| 987 | from_date: str, |
| 988 | to_date: str, |
| 989 | ) -> schema.SourceItem: |
| 990 | """Normalizer for Meta Ad Library creatives. |
| 991 | |
| 992 | One item per distinct creative launched inside the window. Identity is the |
| 993 | Ad Library permalink, never the landing URL: many creatives for one product |
| 994 | share a landing page, and fusion merges by normalized URL, so keying on the |
| 995 | landing page would collapse a whole campaign into one candidate and lose |
| 996 | every transcript but the first. |
| 997 | |
| 998 | Grounding-exempt on the Amazon precedent. Ad copy is written to sell, not |
| 999 | to name the brand -- "Stop making boring drinks" never repeats the topic -- |
| 1000 | and the advertiser page was already resolved by name before any of these |
| 1001 | were created, so they are on-entity by construction. |
| 1002 | """ |
| 1003 | body = str(item.get("text") or "").strip() |
| 1004 | transcript = str(item.get("transcript") or "").strip() |
| 1005 | advertiser = str(item.get("advertiser") or "").strip() |
| 1006 | cta = str(item.get("cta") or "").strip() |
| 1007 | landing = str(item.get("landing_url") or "").strip() |
| 1008 | placements = [str(p) for p in (item.get("placements") or [])] |
| 1009 | promo = str(item.get("promo_code") or "").strip() |
| 1010 | |
| 1011 | # The spoken script is usually the sharper version of the pitch, so it |
| 1012 | # leads the evidence snippet when present. |
| 1013 | snippet_parts = [part for part in [body, transcript] if part] |
| 1014 | # The adapter deliberately keeps creatives that launched inside the window |
| 1015 | # and have since ended -- a one-week promo push is exactly the signal this |
| 1016 | # source exists for -- so the wording has to follow the stored state rather |
| 1017 | # than calling every creative active. |
| 1018 | running = bool(item.get("is_active")) |
| 1019 | ended_on = str(item.get("ended_on") or "").strip() |
| 1020 | if running: |
| 1021 | state_word = "Running paid creative" |
| 1022 | elif ended_on: |
| 1023 | state_word = f"Paid creative that ran until {ended_on}" |
| 1024 | else: |
| 1025 | state_word = "Paid creative that has since ended" |
| 1026 | default_why = f"{state_word} from {advertiser}" if advertiser else state_word |
| 1027 | context = " │ ".join( |
| 1028 | part |
| 1029 | for part in [ |
| 1030 | cta or "", |
| 1031 | f"code {promo}" if promo else "", |
| 1032 | landing, |
| 1033 | ] |
| 1034 | if part |
| 1035 | ) |
| 1036 | return _source_item( |
| 1037 | item_id=str(item.get("id") or f"MA{index + 1}"), |
| 1038 | source=source, |
| 1039 | title=str(item.get("title") or "").strip() or body[:140] or f"Meta ad {index + 1}", |
| 1040 | body=body, |
| 1041 | url=str(item.get("url") or "").strip(), |
| 1042 | author=advertiser, |
| 1043 | container="Meta Ad Library", |
| 1044 | published_at=item.get("date"), |
| 1045 | date_confidence=_date_confidence(item, from_date, to_date, default="high"), |
| 1046 | engagement={"variants": int(item.get("variants") or 1)}, |
| 1047 | relevance_hint=0.8, |
| 1048 | why_relevant=str(item.get("why_relevant") or "") or default_why, |
| 1049 | snippet=" ".join(snippet_parts)[:400], |
| 1050 | metadata={ |
| 1051 | "grounding_exempt": True, |
| 1052 | "advertiser": advertiser, |
| 1053 | "page_id": str(item.get("page_id") or ""), |
| 1054 | "is_active": bool(item.get("is_active")), |
| 1055 | "ended_on": item.get("ended_on"), |
| 1056 | "display_format": str(item.get("display_format") or ""), |
| 1057 | "placements": placements, |
| 1058 | "cta": cta, |
| 1059 | "landing_url": landing, |
| 1060 | "promo_code": promo, |
| 1061 | "variants": int(item.get("variants") or 1), |
| 1062 | "has_video": bool(item.get("has_video")), |
| 1063 | "transcript_snippet": transcript[:400], |
| 1064 | "ad_context": context, |
| 1065 | }, |
| 1066 | ) |
| 1067 | |
| 1068 | |
| 1069 | def _normalize_trustpilot( |
| 1070 | source: str, |
| 1071 | item: dict[str, Any], |
| 1072 | index: int, |
| 1073 | from_date: str, |
| 1074 | to_date: str, |
| 1075 | ) -> schema.SourceItem: |
| 1076 | """Normalizer for Trustpilot company sentiment. |
| 1077 | |
| 1078 | One item per company. The AI summary (already balanced positive/negative) |
| 1079 | is the body. TrustScore and review count are engagement and metadata. |
| 1080 | """ |
| 1081 | title = str(item.get("title") or "").strip() |
| 1082 | name = str(item.get("name") or "").strip() |
| 1083 | summary = str(item.get("summary") or "").strip() |
| 1084 | body = "\n\n".join(part for part in [title, summary] if part) |
| 1085 | return _source_item( |
| 1086 | item_id=str(item.get("id") or f"TP{index + 1}"), |
| 1087 | source=source, |
| 1088 | title=title |
| 1089 | or (f"{name} on Trustpilot" if name else f"Trustpilot reviews {index + 1}"), |
| 1090 | body=body, |
| 1091 | url=str(item.get("url") or ""), |
| 1092 | author=name or None, |
| 1093 | container="Trustpilot", |
| 1094 | published_at=item.get("date"), |
| 1095 | date_confidence=_date_confidence(item, from_date, to_date, default="low"), |
| 1096 | engagement=item.get("engagement") or {}, |
| 1097 | relevance_hint=item.get("relevance", 0.6), |
| 1098 | why_relevant=str(item.get("why_relevant") or ""), |
| 1099 | snippet=summary[:400], |
| 1100 | metadata={ |
| 1101 | "name": name, |
| 1102 | "trustScore": item.get("trustScore"), |
| 1103 | "reviewCount": item.get("reviewCount"), |
| 1104 | "aiSummary": summary, |
| 1105 | }, |
| 1106 | ) |
| 1107 | |
| 1108 | |
| 1109 | def _normalize_amazon( |
| 1110 | source: str, |
| 1111 | item: dict[str, Any], |
| 1112 | index: int, |
| 1113 | from_date: str, |
| 1114 | to_date: str, |
| 1115 | ) -> schema.SourceItem: |
| 1116 | """Normalizer for Amazon product-and-review signals. |
| 1117 | |
| 1118 | One item per product. The aggregate rating is current-state evidence, so |
| 1119 | the item is stamped with today's date on the Trustpilot precedent -- a |
| 1120 | live 4.4-star average is a fact about now, not about whenever the |
| 1121 | product launched. |
| 1122 | |
| 1123 | Reviews arrive already in the shared score/excerpt comment shape (built |
| 1124 | in the amazon adapter, deliberately not routed through _remap_comments, |
| 1125 | which would strip the rating/date/verified keys this source needs), so |
| 1126 | they pass straight through to metadata. |
| 1127 | """ |
| 1128 | name = str(item.get("name") or "").strip() |
| 1129 | brand = str(item.get("brand") or "").strip() |
| 1130 | top_comments = item.get("top_comments") or [] |
| 1131 | comment_text = _join_comment_excerpts(top_comments, "excerpt") |
| 1132 | rating = item.get("product_rating") if item.get("product_rating") is not None else item.get("rating") |
| 1133 | ratings_total = item.get("product_rating_count") or item.get("num_ratings") or 0 |
| 1134 | |
| 1135 | headline = " ".join( |
| 1136 | part for part in [ |
| 1137 | f"{rating}/5" if rating is not None else "", |
| 1138 | f"({ratings_total:,} ratings)" if ratings_total else "", |
| 1139 | ] if part |
| 1140 | ) |
| 1141 | # The brand rides in its own field and is usually absent from the name, |
| 1142 | # so prepend it -- unless the name already leads with it, which would |
| 1143 | # otherwise read "Weber Weber Spirit E-325". |
| 1144 | if brand and not name.lower().startswith(brand.lower()): |
| 1145 | product_label = f"{brand} {name}".strip() |
| 1146 | else: |
| 1147 | product_label = name or brand |
| 1148 | title = " - ".join(part for part in [product_label, headline] if part) |
| 1149 | body = "\n".join(part for part in [title, comment_text] if part) |
| 1150 | |
| 1151 | return _source_item( |
| 1152 | item_id=str(item.get("asin") or f"AMZ{index + 1}"), |
| 1153 | source=source, |
| 1154 | title=title or f"Amazon product {index + 1}", |
| 1155 | body=body, |
| 1156 | url=str(item.get("url") or ""), |
| 1157 | author=brand or None, |
| 1158 | container="Amazon", |
| 1159 | published_at=item.get("date"), |
| 1160 | date_confidence=_date_confidence(item, from_date, to_date, default="low"), |
| 1161 | engagement=item.get("engagement") or {"ratings": ratings_total}, |
| 1162 | relevance_hint=item.get("relevance", 0.6), |
| 1163 | why_relevant=str(item.get("why_relevant") or ""), |
| 1164 | snippet=comment_text[:400], |
| 1165 | metadata={ |
| 1166 | "asin": str(item.get("asin") or ""), |
| 1167 | "name": name, |
| 1168 | "short_name": item.get("short_name") or "", |
| 1169 | "brand": brand, |
| 1170 | "rating": item.get("rating"), |
| 1171 | "num_ratings": item.get("num_ratings") or 0, |
| 1172 | "price": item.get("price"), |
| 1173 | "currency": item.get("currency") or "", |
| 1174 | "badge": item.get("badge") or "", |
| 1175 | # Recorded, never used as a filter: the flag's distribution |
| 1176 | # swings with keyword phrasing, so filtering can blank the lane. |
| 1177 | "sponsored": bool(item.get("sponsored")), |
| 1178 | "top_comments": top_comments, |
| 1179 | # The review lane already fired for this product set (search |
| 1180 | # time), so finalize must not pull again. |
| 1181 | "reviews_attempted": bool(item.get("reviews_attempted")), |
| 1182 | "product_rating": item.get("product_rating"), |
| 1183 | "product_rating_count": item.get("product_rating_count") or 0, |
| 1184 | "star_distribution": item.get("star_distribution") or {}, |
| 1185 | # Relevant by construction: the adapter already gated products |
| 1186 | # against the model-supplied keyword, and review text rarely |
| 1187 | # names the product (KTD8). |
| 1188 | "grounding_exempt": True, |
| 1189 | }, |
| 1190 | ) |
| 1191 | |
| 1192 | |
| 1193 | def _normalize_polymarket( |
| 1194 | source: str, |
| 1195 | item: dict[str, Any], |
| 1196 | index: int, |
| 1197 | from_date: str, |
| 1198 | to_date: str, |
| 1199 | ) -> schema.SourceItem: |
| 1200 | title = str(item.get("title") or "").strip() |
| 1201 | question = str(item.get("question") or "").strip() |
| 1202 | matched = item.get("matched_market") if isinstance(item.get("matched_market"), dict) else None |
| 1203 | matched_question = str((matched or {}).get("question") or "").strip() |
| 1204 | engagement = { |
| 1205 | "volume": item.get("volume1mo") or item.get("volume24hr") or 0, |
| 1206 | "liquidity": item.get("liquidity") or 0, |
| 1207 | } |
| 1208 | return _source_item( |
| 1209 | item_id=str(item.get("event_id") or item.get("id") or f"PM{index + 1}"), |
| 1210 | source=source, |
| 1211 | title=title or question or f"Polymarket event {index + 1}", |
| 1212 | body="\n".join( |
| 1213 | part |
| 1214 | for part in dict.fromkeys( |
| 1215 | [title, question, matched_question, str(item.get("price_movement") or "")] |
| 1216 | ) |
| 1217 | if part |
| 1218 | ), |
| 1219 | url=str(item.get("url") or ""), |
| 1220 | author=None, |
| 1221 | container="Polymarket", |
| 1222 | published_at=item.get("date"), |
| 1223 | date_confidence=_date_confidence(item, from_date, to_date, default="high"), |
| 1224 | engagement=engagement, |
| 1225 | relevance_hint=item.get("relevance", 0.5), |
| 1226 | why_relevant=str(item.get("why_relevant") or ""), |
| 1227 | snippet=str(item.get("price_movement") or ""), |
| 1228 | metadata={ |
| 1229 | "event_id": item.get("event_id"), |
| 1230 | "question": question, |
| 1231 | "end_date": item.get("end_date"), |
| 1232 | "outcome_prices": item.get("outcome_prices") or [], |
| 1233 | **( |
| 1234 | {"outcome_market_ids": item["outcome_market_ids"]} |
| 1235 | if item.get("outcome_market_ids") |
| 1236 | else {} |
| 1237 | ), |
| 1238 | "outcomes_remaining": item.get("outcomes_remaining"), |
| 1239 | # The market and price that stand for the event in the footer. |
| 1240 | **({"headline": item["headline"]} if item.get("headline") else {}), |
| 1241 | # What the compact output's one-line odds summary is built from. |
| 1242 | **({"odds": item["odds"]} if item.get("odds") else {}), |
| 1243 | # The subject's own market and the selection rule's verdict on it; |
| 1244 | # render orders the Markets block and footer by them. |
| 1245 | **( |
| 1246 | { |
| 1247 | "matched_market": matched, |
| 1248 | "selection_score": item.get("selection_score"), |
| 1249 | "selection_tier": item.get("selection_tier"), |
| 1250 | } |
| 1251 | if matched else {} |
| 1252 | ), |
| 1253 | }, |
| 1254 | ) |
| 1255 | |
| 1256 | |
| 1257 | def _normalize_github( |
| 1258 | source: str, |
| 1259 | item: dict[str, Any], |
| 1260 | index: int, |
| 1261 | from_date: str, |
| 1262 | to_date: str, |
| 1263 | ) -> schema.SourceItem: |
| 1264 | title = str(item.get("title") or "").strip() |
| 1265 | snippet_text = str(item.get("snippet") or "").strip() |
| 1266 | top_comments = item.get("metadata", {}).get("top_comments") or [] |
| 1267 | comment_text = _join_comment_excerpts(top_comments, "excerpt") |
| 1268 | body = "\n".join(part for part in [title, snippet_text, comment_text] if part) |
| 1269 | metadata = item.get("metadata") or {} |
| 1270 | return _source_item( |
| 1271 | item_id=str(item.get("id") or f"GH{index + 1}"), |
| 1272 | source=source, |
| 1273 | title=title or f"GitHub item {index + 1}", |
| 1274 | body=body, |
| 1275 | url=str(item.get("url") or ""), |
| 1276 | author=str(item.get("author") or ""), |
| 1277 | container=str(item.get("container") or ""), |
| 1278 | published_at=item.get("date"), |
| 1279 | date_confidence=_date_confidence(item, from_date, to_date, default="high"), |
| 1280 | engagement=item.get("engagement") or {}, |
| 1281 | relevance_hint=item.get("relevance", 0.5), |
| 1282 | why_relevant=str(item.get("why_relevant") or ""), |
| 1283 | snippet=comment_text or snippet_text[:400], |
| 1284 | metadata={ |
| 1285 | "top_comments": top_comments, |
| 1286 | "labels": metadata.get("labels") or [], |
| 1287 | "state": metadata.get("state", ""), |
| 1288 | "is_pr": metadata.get("is_pr", False), |
| 1289 | "date_is_snapshot": bool(metadata.get("date_is_snapshot")), |
| 1290 | **{key: metadata[key] for key in ("repo_counts_observed_at", "repo_counts_observed_on") if metadata.get(key)}, |
| 1291 | **({"repo_description": metadata["repo_description"]} if "repo_description" in metadata else {}), |
| 1292 | }, |
| 1293 | ) |
| 1294 | |
| 1295 | |
| 1296 | def _normalize_grounding( |
| 1297 | source: str, |
| 1298 | item: dict[str, Any], |
| 1299 | index: int, |
| 1300 | from_date: str, |
| 1301 | to_date: str, |
| 1302 | ) -> schema.SourceItem: |
| 1303 | title = str(item.get("title") or "").strip() |
| 1304 | snippet = str(item.get("snippet") or "").strip() |
| 1305 | url = str(item.get("url") or "").strip() |
| 1306 | raw_meta = item.get("metadata") |
| 1307 | metadata = dict(raw_meta) if isinstance(raw_meta, dict) else {} |
| 1308 | raw_comments = item.get("top_comments") |
| 1309 | if not isinstance(raw_comments, list) or not raw_comments: |
| 1310 | meta_comments = metadata.get("top_comments") |
| 1311 | raw_comments = meta_comments if isinstance(meta_comments, list) else [] |
| 1312 | top_comments = [dict(c) if isinstance(c, dict) else c for c in raw_comments] |
| 1313 | if top_comments: |
| 1314 | metadata["top_comments"] = top_comments |
| 1315 | comment_text = _join_comment_excerpts(top_comments, "excerpt").strip() if top_comments else "" |
| 1316 | enriched_via = item.get("enriched_via") |
| 1317 | if enriched_via: |
| 1318 | metadata["enriched_via"] = enriched_via |
| 1319 | reddit_thread_score = item.get("reddit_thread_score") |
| 1320 | if ( |
| 1321 | isinstance(reddit_thread_score, (int, float)) |
| 1322 | and not isinstance(reddit_thread_score, bool) |
| 1323 | and math.isfinite(reddit_thread_score) |
| 1324 | ): |
| 1325 | metadata["reddit_thread_score"] = reddit_thread_score |
| 1326 | reddit_subreddit = str(item.get("reddit_subreddit") or "").strip().removeprefix("r/") |
| 1327 | if reddit_subreddit: |
| 1328 | metadata["reddit_subreddit"] = reddit_subreddit |
| 1329 | return _source_item( |
| 1330 | item_id=str(item.get("id") or f"W{index + 1}"), |
| 1331 | source=source, |
| 1332 | title=title or _domain_from_url(url) or f"Web result {index + 1}", |
| 1333 | body="\n".join(part for part in [title, snippet, comment_text] if part), |
| 1334 | url=url, |
| 1335 | author=None, |
| 1336 | container=str(item.get("source_domain") or _domain_from_url(url) or ""), |
| 1337 | published_at=item.get("date"), |
| 1338 | date_confidence=_date_confidence(item, from_date, to_date), |
| 1339 | engagement=dict(item.get("engagement") or {}), |
| 1340 | relevance_hint=item.get("relevance", 0.5), |
| 1341 | why_relevant=str(item.get("why_relevant") or ""), |
| 1342 | snippet=snippet, |
| 1343 | metadata=metadata, |
| 1344 | ) |
| 1345 | |
| 1346 | |
| 1347 | def _normalize_linkedin( |
| 1348 | source: str, |
| 1349 | item: dict[str, Any], |
| 1350 | index: int, |
| 1351 | from_date: str, |
| 1352 | to_date: str, |
| 1353 | ) -> schema.SourceItem: |
| 1354 | """Normalizer for LinkedIn posts and articles via ScrapeCreators. |
| 1355 | |
| 1356 | A LinkedIn article (Pulse long-form, under a /pulse/ URL) is treated as |
| 1357 | high signal: it ranks above ordinary posts. Detection is belt-and-suspenders |
| 1358 | — honor the parser's `is_article` flag, and re-derive from the URL so an |
| 1359 | article still ranks high even if the flag wasn't set upstream. |
| 1360 | """ |
| 1361 | text = str(item.get("text") or "").strip() |
| 1362 | author = str(item.get("author") or "").strip() |
| 1363 | url = str(item.get("url") or "").strip() |
| 1364 | is_article = bool(item.get("is_article")) or "/pulse/" in url.lower() |
| 1365 | kind = "article" if is_article else "post" |
| 1366 | default_relevance = 0.9 if is_article else 0.5 |
| 1367 | return _source_item( |
| 1368 | item_id=str(item.get("id") or f"LI{index + 1}"), |
| 1369 | source=source, |
| 1370 | title=text[:140] or f"LinkedIn {kind} {index + 1}", |
| 1371 | body=text, |
| 1372 | url=url, |
| 1373 | author=author, |
| 1374 | container="LinkedIn Article" if is_article else "LinkedIn", |
| 1375 | published_at=item.get("date"), |
| 1376 | date_confidence=_date_confidence(item, from_date, to_date, default="medium"), |
| 1377 | engagement=item.get("engagement") or {}, |
| 1378 | relevance_hint=item.get("relevance", default_relevance), |
| 1379 | why_relevant=str(item.get("why_relevant") or ""), |
| 1380 | snippet=text[:200], |
| 1381 | metadata={"author_display": author, "is_article": is_article}, |
| 1382 | ) |
| 1383 | |
| 1384 | |
| 1385 | def _normalize_linkedin_profile( |
| 1386 | source: str, |
| 1387 | item: dict[str, Any], |
| 1388 | index: int, |
| 1389 | from_date: str, |
| 1390 | to_date: str, |
| 1391 | ) -> schema.SourceItem: |
| 1392 | """Normalizer for a person run's own LinkedIn posts. |
| 1393 | |
| 1394 | The posts come from the person's anchored profile, so each carries the |
| 1395 | identity-anchor marker. A reshare is titled as one, so every surface that |
| 1396 | prints the title says the person reshared it rather than wrote it. |
| 1397 | """ |
| 1398 | text = str(item.get("text") or "").strip() |
| 1399 | author = str(item.get("author") or "").strip() |
| 1400 | is_reshare = bool(item.get("is_reshare")) |
| 1401 | title = text[:140] or f"LinkedIn post {index + 1}" |
| 1402 | if is_reshare: |
| 1403 | title = f"Reshared: {title}" |
| 1404 | return _source_item( |
| 1405 | item_id=str(item.get("id") or f"LP{index + 1}"), |
| 1406 | source=source, |
| 1407 | title=title, |
| 1408 | body=text, |
| 1409 | url=str(item.get("url") or ""), |
| 1410 | author=author, |
| 1411 | container="LinkedIn", |
| 1412 | published_at=item.get("date"), |
| 1413 | date_confidence=_date_confidence(item, from_date, to_date, default="high"), |
| 1414 | engagement=item.get("engagement") or {}, |
| 1415 | relevance_hint=0.8, |
| 1416 | why_relevant="The person's own LinkedIn post", |
| 1417 | snippet=text[:200], |
| 1418 | metadata={"author_display": author, "identity_anchor": True, "is_reshare": is_reshare}, |
| 1419 | ) |
| 1420 |