Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / news / scripts / generate_source_catalog.py
generate_source_catalog.py123 lines · 4.6 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """Generate the news source-catalog asset from its readable source of truth. |
| 3 | |
| 4 | Source of truth (edit this, in catalog order): |
| 5 | news/catalog/source_catalog.tsv |
| 6 | Packed TSV: TAB-separated fields per record, records separated by |
| 7 | " ;; " and wrapped before 200 columns. Header lines starting with |
| 8 | "#" in that file define the field and code conventions. |
| 9 | |
| 10 | Output (generated; do not hand-edit): |
| 11 | news/src/main/resources/source_catalog.tsv.br |
| 12 | Brotli-compressed canonical TSV: one record per line, same fields, |
| 13 | with the badge dictionary expanded to full text. `SourceCatalog` |
| 14 | (domain) loads it from the classpath at first use, the same way |
| 15 | backup's Bip39 loads /bip39-english.txt; no Android APIs involved. |
| 16 | |
| 17 | Usage: |
| 18 | python3 news/scripts/generate_source_catalog.py # regenerate |
| 19 | python3 news/scripts/generate_source_catalog.py --check # verify only |
| 20 | |
| 21 | Compression uses the `brotli` Python module when available, else the |
| 22 | `brotli` command-line tool; either produces a standard Brotli stream |
| 23 | readable by org.brotli:dec at runtime. |
| 24 | """ |
| 25 | |
| 26 | import subprocess |
| 27 | import sys |
| 28 | from pathlib import Path |
| 29 | |
| 30 | BADGES = { |
| 31 | "M": "Metered: full article text was present in the raw HTML during " |
| 32 | "verification; some articles may still truncate.", |
| 33 | "G": "No paywall; article pages refused our datacentre verification " |
| 34 | "IP, so full text is verified on-device only.", |
| 35 | "H": "Links point at third-party sites; reader quality depends on " |
| 36 | "the linked site.", |
| 37 | } |
| 38 | KINDS = {"S", "R"} |
| 39 | CATEGORIES = {"W", "U", "T", "C", "L"} |
| 40 | SEPARATOR = " ;; " |
| 41 | |
| 42 | |
| 43 | def repo_paths() -> tuple[Path, Path]: |
| 44 | news_dir = Path(__file__).resolve().parent.parent |
| 45 | return news_dir / "catalog" / "source_catalog.tsv", \ |
| 46 | news_dir / "src" / "main" / "resources" / "source_catalog.tsv.br" |
| 47 | |
| 48 | |
| 49 | def canonical_tsv(source: Path) -> bytes: |
| 50 | records: list[str] = [] |
| 51 | for line in source.read_text(encoding="utf-8").splitlines(): |
| 52 | if not line or line.startswith("#"): |
| 53 | continue |
| 54 | for record in line.split(SEPARATOR): |
| 55 | fields = record.split("\t") |
| 56 | if len(fields) < 6: |
| 57 | raise ValueError(f"record has <6 fields: {record!r}") |
| 58 | if len(fields) > 8: |
| 59 | raise ValueError(f"record has >8 fields: {record!r}") |
| 60 | for field in fields: |
| 61 | if SEPARATOR in field or "\n" in field: |
| 62 | raise ValueError(f"field carries a separator: {record!r}") |
| 63 | if fields[3] not in KINDS: |
| 64 | raise ValueError(f"bad kind in record: {record!r}") |
| 65 | categories = fields[5].split(",") |
| 66 | if not fields[5] or any(c not in CATEGORIES for c in categories): |
| 67 | raise ValueError(f"bad categories in record: {record!r}") |
| 68 | if len(fields) >= 7: |
| 69 | fields[6] = BADGES.get(fields[6], fields[6]) |
| 70 | records.append("\t".join(fields)) |
| 71 | ids = [r.split("\t", 1)[0] for r in records] |
| 72 | if len(ids) != len(set(ids)): |
| 73 | raise ValueError("duplicate source id in catalog") |
| 74 | return ("\n".join(records) + "\n").encode("utf-8") |
| 75 | |
| 76 | |
| 77 | def compress(data: bytes) -> bytes: |
| 78 | try: |
| 79 | import brotli |
| 80 | return brotli.compress(data, quality=11) |
| 81 | except ImportError: |
| 82 | proc = subprocess.run( |
| 83 | ["brotli", "--force", "--quality=11", "--stdout"], |
| 84 | input=data, capture_output=True, |
| 85 | ) |
| 86 | if proc.returncode != 0: |
| 87 | sys.exit("brotli is required: pip install brotli, or install " |
| 88 | f"the brotli CLI ({proc.stderr.decode(errors='replace')})") |
| 89 | return proc.stdout |
| 90 | |
| 91 | |
| 92 | def decompress(data: bytes) -> bytes: |
| 93 | try: |
| 94 | import brotli |
| 95 | return brotli.decompress(data) |
| 96 | except ImportError: |
| 97 | proc = subprocess.run( |
| 98 | ["brotli", "--decompress", "--stdout"], |
| 99 | input=data, capture_output=True, |
| 100 | ) |
| 101 | if proc.returncode != 0: |
| 102 | raise ValueError("brotli decompress failed") |
| 103 | return proc.stdout |
| 104 | |
| 105 | |
| 106 | def main() -> int: |
| 107 | source, asset = repo_paths() |
| 108 | canonical = canonical_tsv(source) |
| 109 | if "--check" in sys.argv: |
| 110 | if not asset.exists() or decompress(asset.read_bytes()) != canonical: |
| 111 | print(f"STALE: {asset} does not match {source}; regenerate it") |
| 112 | return 1 |
| 113 | print(f"OK: {asset} matches {source} ({canonical.count(10)} records)") |
| 114 | return 0 |
| 115 | asset.parent.mkdir(parents=True, exist_ok=True) |
| 116 | asset.write_bytes(compress(canonical)) |
| 117 | print(f"wrote {asset}: {len(canonical)} canonical bytes, " |
| 118 | f"{asset.stat().st_size} compressed bytes") |
| 119 | return 0 |
| 120 | |
| 121 | |
| 122 | if __name__ == "__main__": |
| 123 | raise SystemExit(main()) |