#!/usr/bin/env python3 """Generate the news source-catalog asset from its readable source of truth. Source of truth (edit this, in catalog order): news/catalog/source_catalog.tsv Packed TSV: TAB-separated fields per record, records separated by " ;; " and wrapped before 200 columns. Header lines starting with "#" in that file define the field and code conventions. Output (generated; do not hand-edit): news/src/main/resources/source_catalog.tsv.br Brotli-compressed canonical TSV: one record per line, same fields, with the badge dictionary expanded to full text. `SourceCatalog` (domain) loads it from the classpath at first use, the same way backup's Bip39 loads /bip39-english.txt; no Android APIs involved. Usage: python3 news/scripts/generate_source_catalog.py # regenerate python3 news/scripts/generate_source_catalog.py --check # verify only Compression uses the `brotli` Python module when available, else the `brotli` command-line tool; either produces a standard Brotli stream readable by org.brotli:dec at runtime. """ import subprocess import sys from pathlib import Path BADGES = { "M": "Metered: full article text was present in the raw HTML during " "verification; some articles may still truncate.", "G": "No paywall; article pages refused our datacentre verification " "IP, so full text is verified on-device only.", "H": "Links point at third-party sites; reader quality depends on " "the linked site.", } KINDS = {"S", "R"} CATEGORIES = {"W", "U", "T", "C", "L"} SEPARATOR = " ;; " def repo_paths() -> tuple[Path, Path]: news_dir = Path(__file__).resolve().parent.parent return news_dir / "catalog" / "source_catalog.tsv", \ news_dir / "src" / "main" / "resources" / "source_catalog.tsv.br" def canonical_tsv(source: Path) -> bytes: records: list[str] = [] for line in source.read_text(encoding="utf-8").splitlines(): if not line or line.startswith("#"): continue for record in line.split(SEPARATOR): fields = record.split("\t") if len(fields) < 6: raise ValueError(f"record has <6 fields: {record!r}") if len(fields) > 8: raise ValueError(f"record has >8 fields: {record!r}") for field in fields: if SEPARATOR in field or "\n" in field: raise ValueError(f"field carries a separator: {record!r}") if fields[3] not in KINDS: raise ValueError(f"bad kind in record: {record!r}") categories = fields[5].split(",") if not fields[5] or any(c not in CATEGORIES for c in categories): raise ValueError(f"bad categories in record: {record!r}") if len(fields) >= 7: fields[6] = BADGES.get(fields[6], fields[6]) records.append("\t".join(fields)) ids = [r.split("\t", 1)[0] for r in records] if len(ids) != len(set(ids)): raise ValueError("duplicate source id in catalog") return ("\n".join(records) + "\n").encode("utf-8") def compress(data: bytes) -> bytes: try: import brotli return brotli.compress(data, quality=11) except ImportError: proc = subprocess.run( ["brotli", "--force", "--quality=11", "--stdout"], input=data, capture_output=True, ) if proc.returncode != 0: sys.exit("brotli is required: pip install brotli, or install " f"the brotli CLI ({proc.stderr.decode(errors='replace')})") return proc.stdout def decompress(data: bytes) -> bytes: try: import brotli return brotli.decompress(data) except ImportError: proc = subprocess.run( ["brotli", "--decompress", "--stdout"], input=data, capture_output=True, ) if proc.returncode != 0: raise ValueError("brotli decompress failed") return proc.stdout def main() -> int: source, asset = repo_paths() canonical = canonical_tsv(source) if "--check" in sys.argv: if not asset.exists() or decompress(asset.read_bytes()) != canonical: print(f"STALE: {asset} does not match {source}; regenerate it") return 1 print(f"OK: {asset} matches {source} ({canonical.count(10)} records)") return 0 asset.parent.mkdir(parents=True, exist_ok=True) asset.write_bytes(compress(canonical)) print(f"wrote {asset}: {len(canonical)} canonical bytes, " f"{asset.stat().st_size} compressed bytes") return 0 if __name__ == "__main__": raise SystemExit(main())