|
| 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( |
| 15 | + "--keywords", |
| 16 | + default="artificial intelligence", |
| 17 | + help="Set the search terms for live mode.", |
| 18 | + ) |
| 19 | + parser.add_argument( |
| 20 | + "--language", |
| 21 | + default="en", |
| 22 | + help="Set the article language for live mode.", |
| 23 | + ) |
| 24 | + parser.add_argument( |
| 25 | + "--output-dir", |
| 26 | + type=Path, |
| 27 | + default=Path("briefing-output"), |
| 28 | + help="Choose where to write briefing.md and briefing.json.", |
| 29 | + ) |
| 30 | + parser.add_argument( |
| 31 | + "--generated-at", |
| 32 | + help="Set the output timestamp for a custom fixture.", |
| 33 | + ) |
| 34 | + return parser.parse_args() |
| 35 | + |
| 36 | + |
| 37 | +def normalize_article(article): |
| 38 | + return { |
| 39 | + "title": article.get("title") or "Untitled", |
| 40 | + "description": article.get("description") or "", |
| 41 | + "url": article.get("url") or "", |
| 42 | + "published": article.get("published") or "", |
| 43 | + "language": article.get("language") or "", |
| 44 | + "category": article.get("category") or [], |
| 45 | + } |
| 46 | + |
| 47 | + |
| 48 | +def load_fixture(path): |
| 49 | + return json.loads(path.read_text(encoding="utf-8")) |
| 50 | + |
| 51 | + |
| 52 | +def load_live_response(keywords, language): |
| 53 | + api_key = os.environ.get("CURRENTS_API_KEY") |
| 54 | + if not api_key: |
| 55 | + raise ValueError("CURRENTS_API_KEY is required for live mode") |
| 56 | + |
| 57 | + from currentsapi import CurrentsAPI |
| 58 | + |
| 59 | + return CurrentsAPI(api_key=api_key).search( |
| 60 | + keywords=keywords, |
| 61 | + language=language, |
| 62 | + ) |
| 63 | + |
| 64 | + |
| 65 | +def validate_response(response): |
| 66 | + if not isinstance(response, dict): |
| 67 | + raise ValueError("Search API response must be an object") |
| 68 | + if response.get("status") != "ok": |
| 69 | + raise ValueError("Search API response status must be 'ok'") |
| 70 | + if not isinstance(response.get("news"), list): |
| 71 | + raise ValueError("Search API response news must be a list") |
| 72 | + if any(not isinstance(article, dict) for article in response["news"]): |
| 73 | + raise ValueError("Every news item must be an object") |
| 74 | + for article in response["news"]: |
| 75 | + for field in ("title", "description", "url", "published", "language"): |
| 76 | + value = article.get(field) |
| 77 | + if value is not None and not isinstance(value, str): |
| 78 | + raise ValueError("news item {} must be a string".format(field)) |
| 79 | + category = article.get("category") |
| 80 | + if category is not None and ( |
| 81 | + not isinstance(category, list) |
| 82 | + or any(not isinstance(item, str) for item in category) |
| 83 | + ): |
| 84 | + raise ValueError("news item category must be a list of strings") |
| 85 | + |
| 86 | + |
| 87 | +def resolve_generated_at(args, response): |
| 88 | + if args.generated_at: |
| 89 | + return args.generated_at |
| 90 | + if args.fixture: |
| 91 | + fixture_time = response.get("_fixture_generated_at") |
| 92 | + if not isinstance(fixture_time, str) or not fixture_time: |
| 93 | + raise ValueError( |
| 94 | + "Fixture must include _fixture_generated_at or use --generated-at" |
| 95 | + ) |
| 96 | + return fixture_time |
| 97 | + return datetime.now(timezone.utc).isoformat() |
| 98 | + |
| 99 | + |
| 100 | +def build_output(response, generated_at): |
| 101 | + validate_response(response) |
| 102 | + articles = [normalize_article(article) for article in response["news"]] |
| 103 | + articles.sort(key=lambda article: article["title"].casefold()) |
| 104 | + articles.sort(key=lambda article: article["published"], reverse=True) |
| 105 | + lines = ["# Source-Linked News Briefing", "", "Generated at: {}".format(generated_at), ""] |
| 106 | + for article in articles: |
| 107 | + title = article["title"] |
| 108 | + url = article["url"] |
| 109 | + lines.append("- {} - <{}>".format(title, url) if url else "- {}".format(title)) |
| 110 | + if article["published"]: |
| 111 | + lines.append(" - Published: {}".format(article["published"])) |
| 112 | + if article["description"]: |
| 113 | + lines.append(" - {}".format(article["description"])) |
| 114 | + return "\n".join(lines) + "\n", { |
| 115 | + "generated_at": generated_at, |
| 116 | + "articles": articles, |
| 117 | + } |
| 118 | + |
| 119 | + |
| 120 | +def main(): |
| 121 | + args = parse_args() |
| 122 | + |
| 123 | + try: |
| 124 | + response = ( |
| 125 | + load_fixture(args.fixture) |
| 126 | + if args.fixture |
| 127 | + else load_live_response(args.keywords, args.language) |
| 128 | + ) |
| 129 | + validate_response(response) |
| 130 | + generated_at = resolve_generated_at(args, response) |
| 131 | + markdown, structured = build_output(response, generated_at) |
| 132 | + except (OSError, ValueError, json.JSONDecodeError) as exc: |
| 133 | + raise SystemExit("error: {}".format(exc)) |
| 134 | + |
| 135 | + args.output_dir.mkdir(parents=True, exist_ok=True) |
| 136 | + (args.output_dir / "briefing.md").write_text(markdown, encoding="utf-8") |
| 137 | + (args.output_dir / "briefing.json").write_text( |
| 138 | + json.dumps(structured, indent=2) + "\n", |
| 139 | + encoding="utf-8", |
| 140 | + ) |
| 141 | + print("Wrote {}".format(args.output_dir)) |
| 142 | + |
| 143 | + |
| 144 | +if __name__ == "__main__": |
| 145 | + main() |
0 commit comments