|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Generate a source-linked news briefing from Currents Search API data.""" |
| 3 | + |
| 4 | +import argparse |
| 5 | +import json |
| 6 | +import os |
| 7 | +from datetime import datetime, timezone |
| 8 | +from pathlib import Path |
| 9 | + |
| 10 | + |
| 11 | +def parse_args(): |
| 12 | + parser = argparse.ArgumentParser(description=__doc__) |
| 13 | + parser.add_argument("--fixture", type=Path, help="Read a saved Search API response.") |
| 14 | + parser.add_argument("--keywords", default="artificial intelligence") |
| 15 | + parser.add_argument("--language", default="en") |
| 16 | + parser.add_argument("--output-dir", type=Path, default=Path("briefing-output")) |
| 17 | + parser.add_argument("--generated-at", help=argparse.SUPPRESS) |
| 18 | + return parser.parse_args() |
| 19 | + |
| 20 | + |
| 21 | +def normalize_article(article): |
| 22 | + return { |
| 23 | + "title": article.get("title") or "Untitled", |
| 24 | + "description": article.get("description") or "", |
| 25 | + "url": article.get("url") or "", |
| 26 | + "published": article.get("published") or "", |
| 27 | + "language": article.get("language") or "", |
| 28 | + "category": article.get("category") or [], |
| 29 | + } |
| 30 | + |
| 31 | + |
| 32 | +def load_fixture(path): |
| 33 | + return json.loads(path.read_text(encoding="utf-8")) |
| 34 | + |
| 35 | + |
| 36 | +def load_live_response(keywords, language): |
| 37 | + api_key = os.environ.get("CURRENTS_API_KEY") |
| 38 | + if not api_key: |
| 39 | + raise ValueError("CURRENTS_API_KEY is required for live mode") |
| 40 | + |
| 41 | + from currentsapi import CurrentsAPI |
| 42 | + |
| 43 | + return CurrentsAPI(api_key=api_key).search( |
| 44 | + keywords=keywords, |
| 45 | + language=language, |
| 46 | + ) |
| 47 | + |
| 48 | + |
| 49 | +def validate_response(response): |
| 50 | + if not isinstance(response, dict): |
| 51 | + raise ValueError("Search API response must be an object") |
| 52 | + if response.get("status") != "ok": |
| 53 | + raise ValueError("Search API response status must be 'ok'") |
| 54 | + if not isinstance(response.get("news"), list): |
| 55 | + raise ValueError("Search API response news must be a list") |
| 56 | + if any(not isinstance(article, dict) for article in response["news"]): |
| 57 | + raise ValueError("Every news item must be an object") |
| 58 | + |
| 59 | + |
| 60 | +def build_output(response, generated_at): |
| 61 | + validate_response(response) |
| 62 | + articles = [normalize_article(article) for article in response["news"]] |
| 63 | + articles.sort(key=lambda article: article["title"].casefold()) |
| 64 | + articles.sort(key=lambda article: article["published"], reverse=True) |
| 65 | + lines = ["# Source-Linked News Briefing", "", "Generated at: {}".format(generated_at), ""] |
| 66 | + for article in articles: |
| 67 | + title = article["title"] |
| 68 | + url = article["url"] |
| 69 | + lines.append("- {} - <{}>".format(title, url) if url else "- {}".format(title)) |
| 70 | + if article["published"]: |
| 71 | + lines.append(" - Published: {}".format(article["published"])) |
| 72 | + if article["description"]: |
| 73 | + lines.append(" - {}".format(article["description"])) |
| 74 | + return "\n".join(lines) + "\n", { |
| 75 | + "generated_at": generated_at, |
| 76 | + "articles": articles, |
| 77 | + } |
| 78 | + |
| 79 | + |
| 80 | +def main(): |
| 81 | + args = parse_args() |
| 82 | + |
| 83 | + try: |
| 84 | + response = ( |
| 85 | + load_fixture(args.fixture) |
| 86 | + if args.fixture |
| 87 | + else load_live_response(args.keywords, args.language) |
| 88 | + ) |
| 89 | + generated_at = args.generated_at or datetime.now(timezone.utc).isoformat() |
| 90 | + markdown, structured = build_output(response, generated_at) |
| 91 | + except (OSError, ValueError, json.JSONDecodeError) as exc: |
| 92 | + raise SystemExit("error: {}".format(exc)) |
| 93 | + |
| 94 | + args.output_dir.mkdir(parents=True, exist_ok=True) |
| 95 | + (args.output_dir / "briefing.md").write_text(markdown, encoding="utf-8") |
| 96 | + (args.output_dir / "briefing.json").write_text( |
| 97 | + json.dumps(structured, indent=2) + "\n", |
| 98 | + encoding="utf-8", |
| 99 | + ) |
| 100 | + print("Wrote {}".format(args.output_dir)) |
| 101 | + |
| 102 | + |
| 103 | +if __name__ == "__main__": |
| 104 | + main() |
0 commit comments