Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / scripts / i18n_audit.py

i18n_audit.py183 lines · 7.6 KiBRaw
1#!/usr/bin/env python3
2"""i18n coverage audit for Modern-Apps (stdlib-only, read-only).
3
4For every module with src/main/res/values/strings.xml, parse the English
5keys (string, string-array, plurals) and compare them against each
6values-XX/strings.xml sibling. Emits per app x locale counts:
7
8 translated keys present in the locale file
9 missing English keys absent from the locale file
10 suspect present keys whose value is identical to English
11 coverage translated / total English keys (%)
12
13Empty values-XX/ dirs are Weblate scaffolding and correctly report 0%.
14
15Usage:
16 python3 scripts/i18n_audit.py [--root DIR] [--app SUBSTR]
17 [--locale CODE] [--min-coverage PCT] [--csv] [--json PATH]
18
19Filters: --app is a case-insensitive substring match on the module path
20(repeat or comma-separate for several); --locale is an exact locale dir
21suffix (e.g. de, pt-rBR; case-insensitive); --min-coverage keeps only
22rows at or above that percentage. Exit code is 0 on success (malformed
23XML is reported in the output and does not abort the run). Never writes
24to the repo except the explicit --json path.
25"""
26
27import argparse
28import csv
29import json
30import re
31import sys
32import xml.etree.ElementTree as ET
33from pathlib import Path
34
35LOCALE_RE = re.compile(r"^[a-z]{2,3}(-r[A-Z]{2})?$|^b\+[a-zA-Z+]+$")
36XLIFF_G = "{urn:oasis:names:tc:xliff:document:1.2}g"
37
38
39def elem_text(elem) -> str:
40 """All text of an element, with <xliff:g> content inlined."""
41 parts = []
42 if elem.text:
43 parts.append(elem.text)
44 for child in elem:
45 if child.tag == XLIFF_G:
46 inner = elem_text(child)
47 parts.append(inner if inner else (child.get("example", "") or ""))
48 else:
49 parts.append(elem_text(child))
50 if child.tail:
51 parts.append(child.tail)
52 return "".join(parts).strip()
53
54
55def parse_strings(path: Path):
56 """Return (keys: dict[str, str], error: str | None).
57
58 Key value is the normalized text: joined items for string-array,
59 quantity-sorted item texts for plurals. translatable="false"
60 strings are excluded from the English denominator.
61 """
62 try:
63 root = ET.parse(path).getroot()
64 except ET.ParseError as exc:
65 return {}, f"malformed XML: {exc}"
66 except OSError as exc:
67 return {}, f"unreadable: {exc}"
68 keys = {}
69 for elem in root:
70 name = elem.get("name")
71 if not name:
72 continue
73 if elem.tag == "string":
74 if elem.get("translatable") == "false":
75 continue
76 keys[name] = elem_text(elem)
77 elif elem.tag == "string-array":
78 keys[name] = "\x1f".join(
79 elem_text(i) for i in elem if i.tag == "item")
80 elif elem.tag == "plurals":
81 items = sorted(
82 (i.get("quantity", ""), elem_text(i))
83 for i in elem if i.tag == "item")
84 keys[name] = "\x1f".join(f"{q}={t}" for q, t in items)
85 return keys, None
86
87
88def find_en_files(root: Path):
89 for path in sorted(root.rglob("values/strings.xml")):
90 if "build" in path.parts: # skip build/ output dirs
91 continue
92 if path.parent.parent.name == "res" and path.parent.parent.parent.name == "main":
93 yield path
94
95
96def main(argv=None) -> int:
97 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
98 ap.add_argument("--root", default=str(Path(__file__).resolve().parent.parent),
99 help="repo root (default: parent of scripts/)")
100 ap.add_argument("--app", action="append", default=[],
101 help="module substring filter (repeatable/comma-separated)")
102 ap.add_argument("--locale", action="append", default=[],
103 help="locale filter, e.g. de or pt-rBR (repeatable)")
104 ap.add_argument("--min-coverage", type=float, default=None,
105 help="only show rows with coverage >= PCT")
106 ap.add_argument("--csv", action="store_true", help="CSV to stdout")
107 ap.add_argument("--json", metavar="PATH", help="also write JSON report to PATH")
108 args = ap.parse_args(argv)
109
110 root = Path(args.root)
111 if not root.is_dir():
112 print(f"error: root not found: {root}", file=sys.stderr)
113 return 2
114 apps = [a.lower() for grp in args.app for a in grp.split(",") if a]
115 locales = [a.lower() for grp in args.locale for a in grp.split(",") if a]
116
117 rows, errors = [], []
118 for en_path in find_en_files(root):
119 res_dir = en_path.parent.parent
120 module = str(res_dir.parent.parent.parent.relative_to(root))
121 if apps and not any(a in module.lower() for a in apps):
122 continue
123 en_keys, err = parse_strings(en_path)
124 if err:
125 errors.append({"app": module, "locale": "(en)", "file": str(en_path), "error": err})
126 locale_dirs = sorted(
127 d for d in res_dir.iterdir()
128 if d.is_dir() and d.name.startswith("values-")
129 and LOCALE_RE.match(d.name[len("values-"):]))
130 for loc_dir in locale_dirs:
131 locale = loc_dir.name[len("values-"):]
132 if locales and locale.lower() not in locales:
133 continue
134 loc_file = loc_dir / "strings.xml"
135 loc_keys = {}
136 if loc_file.is_file():
137 loc_keys, err = parse_strings(loc_file)
138 if err:
139 errors.append({"app": module, "locale": locale,
140 "file": str(loc_file), "error": err})
141 total = len(en_keys)
142 present = [k for k in en_keys if k in loc_keys]
143 suspect = sum(1 for k in present if loc_keys[k] == en_keys[k])
144 coverage = (100.0 * len(present) / total) if total else 0.0
145 if args.min_coverage is not None and coverage < args.min_coverage:
146 continue
147 rows.append({"app": module, "locale": locale, "total": total,
148 "translated": len(present), "missing": total - len(present),
149 "suspect": suspect, "coverage": round(coverage, 1)})
150
151 rows.sort(key=lambda r: (r["coverage"], r["app"], r["locale"]))
152 tot = {"app": "TOTAL", "locale": f"{len({r['locale'] for r in rows})} locales",
153 "total": sum(r["total"] for r in rows),
154 "translated": sum(r["translated"] for r in rows),
155 "missing": sum(r["missing"] for r in rows),
156 "suspect": sum(r["suspect"] for r in rows)}
157 tot["coverage"] = round(100.0 * tot["translated"] / tot["total"], 1) if tot["total"] else 0.0
158
159 if args.json:
160 Path(args.json).write_text(json.dumps(
161 {"rows": rows, "total": tot, "errors": errors}, indent=2) + "\n")
162 if args.csv:
163 w = csv.writer(sys.stdout)
164 w.writerow(["app", "locale", "total", "translated", "missing", "suspect", "coverage_pct"])
165 for r in rows + [tot]:
166 w.writerow([r["app"], r["locale"], r["total"], r["translated"],
167 r["missing"], r["suspect"], r["coverage"]])
168 else:
169 hdr = f"{'app':<28} {'locale':<10} {'keys':>6} {'transl':>6} {'miss':>6} {'ident':>6} {'cover%':>7}"
170 print(hdr); print("-" * len(hdr))
171 for r in rows:
172 print(f"{r['app']:<28} {r['locale']:<10} {r['total']:>6} {r['translated']:>6} "
173 f"{r['missing']:>6} {r['suspect']:>6} {r['coverage']:>7}")
174 print("-" * len(hdr))
175 print(f"{tot['app']:<28} {tot['locale']:<10} {tot['total']:>6} {tot['translated']:>6} "
176 f"{tot['missing']:>6} {tot['suspect']:>6} {tot['coverage']:>7}")
177 for e in errors:
178 print(f"warning: {e['file']}: {e['error']}", file=sys.stderr)
179 return 0
180
181
182if __name__ == "__main__":
183 raise SystemExit(main())