unitbytes 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
unitbytes/news.py ADDED
@@ -0,0 +1,491 @@
1
+ """Google News domain namespace (`ub.news`) with topic feeds and canonical LLM/RAG citation formatting."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import asdict, dataclass
6
+ from datetime import datetime
7
+ from decimal import Decimal
8
+ import os
9
+ import re
10
+ from typing import TYPE_CHECKING, Any, Literal, Mapping, Sequence
11
+ from urllib.parse import urlparse
12
+
13
+ from ._serialization import filter_unseen_by_key
14
+ from ._transports import unwrap_items_payload
15
+ from .shopping import _normalize_string_list, normalize_domain, validate_google_commerce_url
16
+
17
+ if TYPE_CHECKING:
18
+ from .client import UnitBytes
19
+
20
+ ACTOR_GOOGLE_NEWS = "unitbytes/google-news-scraper"
21
+ DEFAULT_NEWS_STATE_FILE = ".google_news_seen_state.json"
22
+
23
+ NewsTimeRange = Literal["any", "1h", "24h", "7d", "30d", "1y"]
24
+ NewsSortOption = Literal["relevance", "date"]
25
+ NewsFeedMode = Literal["auto", "search", "rss"]
26
+
27
+ NEWS_TIME_RANGES: frozenset[str] = frozenset({"any", "1h", "24h", "7d", "30d", "1y"})
28
+ NEWS_SORT_OPTIONS: frozenset[str] = frozenset({"relevance", "date"})
29
+ NEWS_FEED_MODES: frozenset[str] = frozenset({"auto", "search", "rss"})
30
+
31
+ VALID_NEWS_TOPICS: frozenset[str] = frozenset(
32
+ {
33
+ "TOP_HEADLINES",
34
+ "WORLD",
35
+ "NATION",
36
+ "BUSINESS",
37
+ "TECHNOLOGY",
38
+ "ENTERTAINMENT",
39
+ "SPORTS",
40
+ "SCIENCE",
41
+ "HEALTH",
42
+ }
43
+ )
44
+
45
+ TOPIC_ALIASES: dict[str, str] = {
46
+ "TOP": "TOP_HEADLINES",
47
+ "HEADLINES": "TOP_HEADLINES",
48
+ "TOP_STORIES": "TOP_HEADLINES",
49
+ "TOP-HEADLINES": "TOP_HEADLINES",
50
+ "HOME": "TOP_HEADLINES",
51
+ "TECH": "TECHNOLOGY",
52
+ "FINANCE": "BUSINESS",
53
+ "ECONOMY": "BUSINESS",
54
+ "NATIONAL": "NATION",
55
+ "LOCAL": "NATION",
56
+ "US": "NATION",
57
+ "SPORT": "SPORTS",
58
+ "MEDICAL": "HEALTH",
59
+ "GLOBAL": "WORLD",
60
+ "INTERNATIONAL": "WORLD",
61
+ }
62
+
63
+ _CAAQ_TOPIC_RE = re.compile(r"^CAAq[A-Za-z0-9_-]{8,}$")
64
+
65
+
66
+ def normalize_news_topic(raw_topic: str) -> str:
67
+ cleaned = str(raw_topic or "").strip()
68
+ if not cleaned:
69
+ raise ValueError("Topic cannot be empty.")
70
+ if _CAAQ_TOPIC_RE.fullmatch(cleaned):
71
+ return cleaned
72
+ upper = cleaned.upper().replace(" ", "_").replace("-", "_")
73
+ mapped = TOPIC_ALIASES.get(upper, upper)
74
+ if mapped not in VALID_NEWS_TOPICS:
75
+ allowed = ", ".join(sorted(VALID_NEWS_TOPICS))
76
+ raise ValueError(f"Unsupported Google News topic {raw_topic!r}. Allowed values: {allowed}.")
77
+ return mapped
78
+
79
+
80
+ def normalize_iso_date(raw_date: str | None, *, field_name: str = "date") -> str | None:
81
+ if raw_date is None:
82
+ return None
83
+ text = str(raw_date).strip()
84
+ if not text:
85
+ return None
86
+ for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%m/%d/%Y"):
87
+ try:
88
+ return datetime.strptime(text, fmt).strftime("%Y-%m-%d")
89
+ except ValueError:
90
+ continue
91
+ raise ValueError(f"Invalid {field_name} {raw_date!r}. Expected YYYY-MM-DD format.")
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class RagCitation:
96
+ index: int
97
+ article_id: str
98
+ title: str
99
+ publisher: str
100
+ publisher_domain: str | None
101
+ url: str
102
+ is_canonical_publisher_url: bool
103
+ published_at: str | None
104
+ author: str | None
105
+ word_count: int | None
106
+ content_source: str
107
+ excerpt: str
108
+ truncated: bool
109
+
110
+ def to_dict(self) -> dict[str, Any]:
111
+ return asdict(self)
112
+
113
+
114
+ @dataclass(frozen=True)
115
+ class RagNewsBundle:
116
+ total_articles: int
117
+ full_text_articles: int
118
+ snippet_only_articles: int
119
+ estimated_tokens: int
120
+ context_markdown: str
121
+ citations: list[RagCitation]
122
+
123
+ def to_dict(self) -> dict[str, Any]:
124
+ return {
125
+ "total_articles": self.total_articles,
126
+ "full_text_articles": self.full_text_articles,
127
+ "snippet_only_articles": self.snippet_only_articles,
128
+ "estimated_tokens": self.estimated_tokens,
129
+ "context_markdown": self.context_markdown,
130
+ "citations": [c.to_dict() for c in self.citations],
131
+ }
132
+
133
+
134
+ def _clean_text_block(raw: Any) -> str:
135
+ if raw is None:
136
+ return ""
137
+ text = str(raw).replace("\r\n", "\n").replace("\r", "\n")
138
+ lines = [re.sub(r"[ \t]+", " ", ln).strip() for ln in text.split("\n")]
139
+ paragraphs: list[str] = []
140
+ for ln in lines:
141
+ if ln:
142
+ paragraphs.append(ln)
143
+ elif paragraphs and paragraphs[-1] != "":
144
+ paragraphs.append("")
145
+ while paragraphs and paragraphs[-1] == "":
146
+ paragraphs.pop()
147
+ return "\n".join(paragraphs).strip()
148
+
149
+
150
+ def _truncate_cleanly(text: str, max_chars: int) -> tuple[str, bool]:
151
+ if len(text) <= max_chars:
152
+ return text, False
153
+ suffix = " [...truncated]"
154
+ budget = max(20, max_chars - len(suffix))
155
+ sliced = text[:budget].rstrip()
156
+ last_space = max(sliced.rfind(" "), sliced.rfind("\n"))
157
+ if last_space >= int(budget * 0.65):
158
+ sliced = sliced[:last_space].rstrip()
159
+ return f"{sliced}{suffix}", True
160
+
161
+
162
+ def _is_google_news_wrapper_url(url: str) -> bool:
163
+ try:
164
+ host = (urlparse(url).hostname or "").lower()
165
+ except ValueError:
166
+ return False
167
+ return host == "news.google.com" or host.endswith(".news.google.com")
168
+
169
+
170
+ def _try_domain(raw: str | None) -> str | None:
171
+ if not raw or not str(raw).strip():
172
+ return None
173
+ try:
174
+ return normalize_domain(str(raw).strip())
175
+ except ValueError:
176
+ return None
177
+
178
+
179
+ def build_rag_news_bundle(
180
+ articles: Sequence[Mapping[str, Any]],
181
+ max_chars_per_article: int = 2500,
182
+ *,
183
+ include_snippet_fallback: bool = True,
184
+ deduplicate_urls: bool = True,
185
+ ) -> RagNewsBundle:
186
+ """Build structured LLM/RAG citations and clean Markdown blocks from Google News records."""
187
+ if max_chars_per_article < 80:
188
+ raise ValueError(f"max_chars_per_article must be >= 80, got {max_chars_per_article}.")
189
+
190
+ citations: list[RagCitation] = []
191
+ blocks: list[str] = []
192
+ seen_keys: set[str] = set()
193
+ full_text_count = 0
194
+ snippet_count = 0
195
+
196
+ for raw in articles:
197
+ if not isinstance(raw, Mapping):
198
+ continue
199
+ title = re.sub(r"\s+", " ", str(raw.get("title") or "").strip())
200
+ raw_url = str(raw.get("url") or "").strip()
201
+ if not title and not raw_url:
202
+ continue
203
+
204
+ dedup_key = (raw_url.lower().rstrip("/") if raw_url else "") or str(raw.get("articleId") or title.lower())
205
+ if deduplicate_urls and dedup_key in seen_keys:
206
+ continue
207
+ seen_keys.add(dedup_key)
208
+
209
+ article_text = _clean_text_block(raw.get("articleText"))
210
+ snippet_text = _clean_text_block(raw.get("snippet"))
211
+
212
+ if article_text:
213
+ body_raw = article_text
214
+ content_source = "full_text"
215
+ elif include_snippet_fallback and snippet_text:
216
+ body_raw = snippet_text
217
+ content_source = "snippet"
218
+ elif not include_snippet_fallback:
219
+ continue
220
+ else:
221
+ body_raw = ""
222
+ content_source = "headline_only"
223
+
224
+ excerpt, was_truncated = _truncate_cleanly(body_raw, max_chars_per_article) if body_raw else ("", False)
225
+ if content_source == "full_text":
226
+ full_text_count += 1
227
+ elif content_source == "snippet":
228
+ snippet_count += 1
229
+
230
+ idx = len(citations) + 1
231
+ article_id = str(raw.get("articleId") or f"art_{idx}").strip()
232
+ publisher = str(raw.get("publisher") or raw.get("publisherDomain") or "Unknown Publisher").strip()
233
+ pub_domain = _try_domain(raw.get("publisherDomain")) or (
234
+ _try_domain(raw_url) if raw_url and not _is_google_news_wrapper_url(raw_url) else None
235
+ )
236
+ is_canonical = bool(raw_url) and not _is_google_news_wrapper_url(raw_url)
237
+ published_at = (
238
+ str(raw.get("publishedDateIso") or raw.get("publishedAt") or raw.get("publishedAtText") or "").strip()
239
+ or None
240
+ )
241
+ author = str(raw.get("author") or "").strip() or None
242
+ raw_wc = raw.get("wordCount")
243
+ word_count = int(raw_wc) if isinstance(raw_wc, (int, float)) and not isinstance(raw_wc, bool) else None
244
+
245
+ citation = RagCitation(
246
+ index=idx,
247
+ article_id=article_id,
248
+ title=title or "Untitled Article",
249
+ publisher=publisher,
250
+ publisher_domain=pub_domain,
251
+ url=raw_url,
252
+ is_canonical_publisher_url=is_canonical,
253
+ published_at=published_at,
254
+ author=author,
255
+ word_count=word_count,
256
+ content_source=content_source,
257
+ excerpt=excerpt,
258
+ truncated=was_truncated,
259
+ )
260
+ citations.append(citation)
261
+
262
+ pub_line = (
263
+ f"{publisher} (`{pub_domain}`)"
264
+ if pub_domain and pub_domain.lower() != publisher.lower()
265
+ else publisher
266
+ )
267
+ meta_parts: list[str] = []
268
+ if published_at:
269
+ meta_parts.append(f"**Published:** {published_at}")
270
+ if author:
271
+ meta_parts.append(f"**Author:** {author}")
272
+ if word_count:
273
+ meta_parts.append(f"**Words:** {word_count}")
274
+ meta_parts.append(f"**Source Mode:** {content_source}")
275
+
276
+ header_lines = [
277
+ f"### [{idx}] {citation.title}",
278
+ f"- **Publisher:** {pub_line}",
279
+ ]
280
+ if raw_url:
281
+ url_label = "Canonical URL" if is_canonical else "Source URL"
282
+ header_lines.append(f"- **{url_label}:** {raw_url}")
283
+ header_lines.append(f"- {' | '.join(meta_parts)}")
284
+ blocks.append("\n".join(header_lines) + (f"\n\n{excerpt}" if excerpt else ""))
285
+
286
+ context_markdown = "\n\n---\n\n".join(blocks)
287
+ estimated_tokens = max(1, len(context_markdown) // 4) if context_markdown else 0
288
+ return RagNewsBundle(
289
+ total_articles=len(citations),
290
+ full_text_articles=full_text_count,
291
+ snippet_only_articles=snippet_count,
292
+ estimated_tokens=estimated_tokens,
293
+ context_markdown=context_markdown,
294
+ citations=citations,
295
+ )
296
+
297
+
298
+ def build_rag_context(
299
+ articles: Sequence[Mapping[str, Any]],
300
+ max_chars_per_article: int = 2500,
301
+ *,
302
+ include_snippet_fallback: bool = True,
303
+ deduplicate_urls: bool = True,
304
+ ) -> str:
305
+ """Format unwrapped canonical Google News articles and full text into clean LLM/RAG citation blocks."""
306
+ return build_rag_news_bundle(
307
+ articles,
308
+ max_chars_per_article=max_chars_per_article,
309
+ include_snippet_fallback=include_snippet_fallback,
310
+ deduplicate_urls=deduplicate_urls,
311
+ ).context_markdown
312
+
313
+
314
+ def _extract_news_key(record: Mapping[str, Any]) -> str | None:
315
+ for key in ("articleId", "url", "title"):
316
+ val = record.get(key)
317
+ if val is not None and str(val).strip():
318
+ return str(val).strip()
319
+ return None
320
+
321
+
322
+ class NewsNamespace:
323
+ """Google News search, topic feeds, and RAG context builder (`ub.news`)."""
324
+
325
+ def __init__(self, client: UnitBytes) -> None:
326
+ self._client = client
327
+
328
+ def search(
329
+ self,
330
+ queries: Sequence[str] | str | None = None,
331
+ *,
332
+ topics: Sequence[str] | str | None = None,
333
+ domains: Sequence[str] | str | None = None,
334
+ exact_phrase: str = "",
335
+ exclude_words: Sequence[str] | str | None = None,
336
+ time_range: NewsTimeRange = "any",
337
+ date_from: str | None = None,
338
+ date_to: str | None = None,
339
+ sort_by: NewsSortOption = "relevance",
340
+ country: str = "us",
341
+ language: str = "",
342
+ feed_mode: NewsFeedMode = "auto",
343
+ extract_article_content: bool = False,
344
+ decode_rss_urls: bool = True,
345
+ max_articles: int = 50,
346
+ proxy_configuration: Mapping[str, Any] | None = None,
347
+ only_new: bool = False,
348
+ state_file: str | os.PathLike[str] | None = None,
349
+ max_total_charge_usd: float | Decimal | None = None,
350
+ ) -> list[dict[str, Any]]:
351
+ """Search Google News articles or curated topic sections with unwrapped publisher URLs and optional full text."""
352
+ parsed_queries = _normalize_string_list(queries)
353
+ for q_item in parsed_queries:
354
+ if "://" in q_item[:12]:
355
+ validate_google_commerce_url(q_item, label="queries")
356
+
357
+ norm_topics = [normalize_news_topic(t) for t in _normalize_string_list(topics, split_commas=True)]
358
+ norm_domains = [normalize_domain(d) for d in _normalize_string_list(domains, split_commas=True)]
359
+ norm_excludes = _normalize_string_list(exclude_words, split_commas=True)
360
+ cleaned_phrase = str(exact_phrase or "").strip().strip('"')
361
+
362
+ if not parsed_queries and not norm_topics and not norm_domains and not cleaned_phrase:
363
+ raise ValueError("Provide at least one target via 'queries', 'topics', 'domains', or 'exact_phrase'.")
364
+
365
+ norm_time = str(time_range or "any").strip().lower()
366
+ if norm_time not in NEWS_TIME_RANGES:
367
+ raise ValueError(f"Invalid time_range {time_range!r}. Supported values: {sorted(NEWS_TIME_RANGES)}.")
368
+
369
+ norm_from = normalize_iso_date(date_from, field_name="date_from")
370
+ norm_to = normalize_iso_date(date_to, field_name="date_to")
371
+ if norm_from and norm_to and norm_from > norm_to:
372
+ raise ValueError(f"date_from ({norm_from}) cannot be later than date_to ({norm_to}).")
373
+
374
+ norm_sort = str(sort_by or "relevance").strip().lower()
375
+ if norm_sort not in NEWS_SORT_OPTIONS:
376
+ raise ValueError(f"Invalid sort_by {sort_by!r}. Supported values: {sorted(NEWS_SORT_OPTIONS)}.")
377
+
378
+ norm_feed = str(feed_mode or "auto").strip().lower()
379
+ if norm_feed not in NEWS_FEED_MODES:
380
+ raise ValueError(f"Invalid feed_mode {feed_mode!r}. Supported values: {sorted(NEWS_FEED_MODES)}.")
381
+
382
+ if int(max_articles) < 1 or int(max_articles) > 5000:
383
+ raise ValueError("max_articles must be between 1 and 5000.")
384
+
385
+ norm_country = str(country or "us").strip().lower()
386
+ if not norm_country:
387
+ raise ValueError("country cannot be empty.")
388
+
389
+ effective_decode = True if extract_article_content else bool(decode_rss_urls)
390
+
391
+ run_input: dict[str, Any] = {
392
+ "timeRange": norm_time,
393
+ "sortBy": norm_sort,
394
+ "country": norm_country,
395
+ "feedMode": norm_feed,
396
+ "extractArticleContent": bool(extract_article_content),
397
+ "decodeRssUrls": effective_decode,
398
+ "maxArticles": int(max_articles),
399
+ }
400
+ if parsed_queries:
401
+ run_input["queries"] = parsed_queries
402
+ if norm_topics:
403
+ run_input["topics"] = norm_topics
404
+ if norm_domains:
405
+ run_input["domains"] = norm_domains
406
+ if cleaned_phrase:
407
+ run_input["exactPhrase"] = cleaned_phrase
408
+ if norm_excludes:
409
+ run_input["excludeWords"] = norm_excludes
410
+ if norm_from:
411
+ run_input["dateFrom"] = norm_from
412
+ if norm_to:
413
+ run_input["dateTo"] = norm_to
414
+ if language and str(language).strip():
415
+ run_input["language"] = str(language).strip()
416
+ if proxy_configuration is not None:
417
+ run_input["proxyConfiguration"] = dict(proxy_configuration)
418
+
419
+ raw = self._client._transport.execute_operation(
420
+ service="news",
421
+ operation="search",
422
+ actor_slug=ACTOR_GOOGLE_NEWS,
423
+ actor_input=run_input,
424
+ http_method="POST",
425
+ json_body=run_input,
426
+ max_total_charge_usd=max_total_charge_usd,
427
+ )
428
+ articles = [a for a in unwrap_items_payload(raw) if not a.get("error")][: int(max_articles)]
429
+ if only_new:
430
+ articles = filter_unseen_by_key(
431
+ articles,
432
+ key_fn=_extract_news_key,
433
+ state_file=state_file or DEFAULT_NEWS_STATE_FILE,
434
+ max_return=int(max_articles),
435
+ )
436
+ return articles
437
+
438
+ def topics(
439
+ self,
440
+ topics: Sequence[str] | str = "TOP_HEADLINES",
441
+ *,
442
+ country: str = "us",
443
+ language: str = "",
444
+ extract_article_content: bool = False,
445
+ decode_rss_urls: bool = True,
446
+ max_articles: int = 50,
447
+ proxy_configuration: Mapping[str, Any] | None = None,
448
+ only_new: bool = False,
449
+ state_file: str | os.PathLike[str] | None = None,
450
+ max_total_charge_usd: float | Decimal | None = None,
451
+ ) -> list[dict[str, Any]]:
452
+ """Fetch curated Google News topic sections (`TOP_HEADLINES`, `TECHNOLOGY`, `BUSINESS`, `SCIENCE`, etc.)."""
453
+ return self.search(
454
+ topics=topics,
455
+ country=country,
456
+ language=language,
457
+ feed_mode="rss",
458
+ extract_article_content=extract_article_content,
459
+ decode_rss_urls=decode_rss_urls,
460
+ max_articles=max_articles,
461
+ proxy_configuration=proxy_configuration,
462
+ only_new=only_new,
463
+ state_file=state_file,
464
+ max_total_charge_usd=max_total_charge_usd,
465
+ )
466
+
467
+ @staticmethod
468
+ def build_rag_context(
469
+ articles: Sequence[Mapping[str, Any]],
470
+ max_chars_per_article: int = 2500,
471
+ *,
472
+ include_snippet_fallback: bool = True,
473
+ deduplicate_urls: bool = True,
474
+ ) -> str:
475
+ """Format unwrapped canonical publisher articles and full text into clean LLM/RAG citation blocks."""
476
+ return build_rag_context(
477
+ articles,
478
+ max_chars_per_article=max_chars_per_article,
479
+ include_snippet_fallback=include_snippet_fallback,
480
+ deduplicate_urls=deduplicate_urls,
481
+ )
482
+
483
+
484
+ __all__ = [
485
+ "NewsNamespace",
486
+ "RagCitation",
487
+ "RagNewsBundle",
488
+ "build_rag_context",
489
+ "build_rag_news_bundle",
490
+ "normalize_news_topic",
491
+ ]
unitbytes/py.typed ADDED
@@ -0,0 +1 @@
1
+ # PEP 561 marker file indicating inline type annotations.