|
| 1 | +"""Translation memory lookup over this repo's .po files via agentic-retrieval. |
| 2 | +
|
| 3 | +Usage (run from anywhere; the repo root is always the index root):: |
| 4 | +
|
| 5 | + .scripts/translation_memory.sh index [--force] |
| 6 | + .scripts/translation_memory.sh query "<text>" [--top-k N] [--fetch N] |
| 7 | + [--include-fuzzy] [--include-untranslated] [--json] [--max-chars N] |
| 8 | +
|
| 9 | +Engine resolution: |
| 10 | +
|
| 11 | +1. ``AGENTIC_RETRIEVAL_ENGINE`` = path to an agentic-retrieval ``engine`` |
| 12 | + directory (needs ``uv``); run with ``uv run --frozen``. |
| 13 | +2. Otherwise a ``retrieval`` executable on ``PATH``. |
| 14 | +3. Otherwise exit with status 3. |
| 15 | +
|
| 16 | +The index lives in ``.agentic-retrieval/`` (gitignored). ``query`` always runs |
| 17 | +``index`` first so the cjk tokenizer is guaranteed; a fresh index is a cheap |
| 18 | +no-op. Exit codes: 0 ok, 2 usage error, 3 engine unavailable or failed. |
| 19 | +Supports macOS and Linux only. |
| 20 | +""" |
| 21 | + |
| 22 | +import argparse |
| 23 | +import json |
| 24 | +import os |
| 25 | +import shutil |
| 26 | +import subprocess |
| 27 | +import sys |
| 28 | +import time |
| 29 | +from pathlib import Path |
| 30 | +from typing import Any, Dict, List |
| 31 | + |
| 32 | +REPO_ROOT = Path(__file__).resolve().parents[2] |
| 33 | +ENV_VAR = "AGENTIC_RETRIEVAL_ENGINE" |
| 34 | +EXIT_UNAVAILABLE = 3 |
| 35 | + |
| 36 | + |
| 37 | +def fail(message: str) -> None: |
| 38 | + print(f"translation-memory: {message}", file=sys.stderr) |
| 39 | + sys.exit(EXIT_UNAVAILABLE) |
| 40 | + |
| 41 | + |
| 42 | +def resolve_engine_cmd() -> List[str]: |
| 43 | + engine = os.environ.get(ENV_VAR) |
| 44 | + if engine: |
| 45 | + if not (Path(engine) / "pyproject.toml").is_file(): |
| 46 | + fail( |
| 47 | + f"{ENV_VAR}={engine} is not an agentic-retrieval engine " |
| 48 | + "directory (no pyproject.toml)" |
| 49 | + ) |
| 50 | + if not shutil.which("uv"): |
| 51 | + fail( |
| 52 | + "'uv' not found on PATH (needed to run the engine from " |
| 53 | + f"{ENV_VAR})" |
| 54 | + ) |
| 55 | + return ["uv", "run", "--frozen", "--quiet", "--directory", engine, |
| 56 | + "retrieval"] |
| 57 | + found = shutil.which("retrieval") |
| 58 | + if found: |
| 59 | + return [found] |
| 60 | + fail( |
| 61 | + "agentic-retrieval engine not found. Either\n" |
| 62 | + f" export {ENV_VAR}=/path/to/agentic-retrieval/engine\n" |
| 63 | + "or install it so that 'retrieval' is on PATH." |
| 64 | + ) |
| 65 | + return [] # unreachable |
| 66 | + |
| 67 | + |
| 68 | +def run_engine(engine_cmd: List[str], args: List[str]) -> str: |
| 69 | + try: |
| 70 | + proc = subprocess.run( |
| 71 | + engine_cmd + args, capture_output=True, encoding="utf-8" |
| 72 | + ) |
| 73 | + except OSError as exc: |
| 74 | + fail(f"cannot run engine: {exc}") |
| 75 | + if proc.returncode != 0: |
| 76 | + sys.stderr.write(proc.stdout or "") |
| 77 | + sys.stderr.write(proc.stderr or "") |
| 78 | + fail(f"engine exited with status {proc.returncode}") |
| 79 | + return proc.stdout |
| 80 | + |
| 81 | + |
| 82 | +def run_index(engine_cmd: List[str], force: bool) -> None: |
| 83 | + args = ["index", "--root", str(REPO_ROOT), "--retriever", "lexical", |
| 84 | + "--tokenizer", "cjk"] |
| 85 | + if force: |
| 86 | + args.append("--force") |
| 87 | + out = run_engine(engine_cmd, args) |
| 88 | + if out.strip(): |
| 89 | + sys.stderr.write(out) |
| 90 | + |
| 91 | + |
| 92 | +def cmd_index(args: argparse.Namespace) -> int: |
| 93 | + start = time.monotonic() |
| 94 | + run_index(resolve_engine_cmd(), args.force) |
| 95 | + print( |
| 96 | + f"translation-memory: index ready in {time.monotonic() - start:.1f}s", |
| 97 | + file=sys.stderr, |
| 98 | + ) |
| 99 | + return 0 |
| 100 | + |
| 101 | + |
| 102 | +def keep_hit(meta: Dict[str, Any], args: argparse.Namespace) -> bool: |
| 103 | + if meta.get("kind") != "po_entry": |
| 104 | + return False |
| 105 | + if not args.include_untranslated and not meta.get("translated"): |
| 106 | + return False |
| 107 | + if not args.include_fuzzy and meta.get("fuzzy"): |
| 108 | + return False |
| 109 | + return True |
| 110 | + |
| 111 | + |
| 112 | +def collect_entries( |
| 113 | + hits: List[Dict[str, Any]], args: argparse.Namespace |
| 114 | +) -> List[Dict[str, Any]]: |
| 115 | + entries: List[Dict[str, Any]] = [] |
| 116 | + seen = set() |
| 117 | + for hit in hits: |
| 118 | + meta = hit.get("metadata") or {} |
| 119 | + if not keep_hit(meta, args): |
| 120 | + continue |
| 121 | + key = (meta.get("msgid"), meta.get("msgstr")) |
| 122 | + if key in seen: |
| 123 | + continue |
| 124 | + seen.add(key) |
| 125 | + path = hit.get("path", "") |
| 126 | + if os.path.isabs(path): |
| 127 | + path = os.path.relpath(path, REPO_ROOT) |
| 128 | + entry = { |
| 129 | + "path": path, |
| 130 | + "line": meta.get("line"), |
| 131 | + "msgid": meta.get("msgid", ""), |
| 132 | + "msgstr": meta.get("msgstr", ""), |
| 133 | + "fuzzy": bool(meta.get("fuzzy")), |
| 134 | + "translated": bool(meta.get("translated")), |
| 135 | + "references": meta.get("references") or [], |
| 136 | + } |
| 137 | + if meta.get("msgctxt"): |
| 138 | + entry["msgctxt"] = meta["msgctxt"] |
| 139 | + entries.append(entry) |
| 140 | + if len(entries) >= args.top_k: |
| 141 | + break |
| 142 | + return entries |
| 143 | + |
| 144 | + |
| 145 | +def compact(text: str, max_chars: int) -> str: |
| 146 | + text = " ".join(str(text).split()) |
| 147 | + if max_chars and len(text) > max_chars: |
| 148 | + return text[:max_chars].rstrip() + "..." |
| 149 | + return text |
| 150 | + |
| 151 | + |
| 152 | +def format_entry(entry: Dict[str, Any], max_chars: int) -> str: |
| 153 | + header = f"{entry['path']}:{entry['line']}" |
| 154 | + if entry["fuzzy"]: |
| 155 | + header += " [fuzzy]" |
| 156 | + if not entry["translated"]: |
| 157 | + header += " [untranslated]" |
| 158 | + lines = [header] |
| 159 | + if "msgctxt" in entry: |
| 160 | + lines.append(f" msgctxt: {compact(entry['msgctxt'], max_chars)}") |
| 161 | + lines.append(f" msgid: {compact(entry['msgid'], max_chars)}") |
| 162 | + lines.append(f" msgstr: {compact(entry['msgstr'], max_chars)}") |
| 163 | + return "\n".join(lines) |
| 164 | + |
| 165 | + |
| 166 | +def cmd_query(args: argparse.Namespace) -> int: |
| 167 | + engine_cmd = resolve_engine_cmd() |
| 168 | + run_index(engine_cmd, False) |
| 169 | + fetch = args.fetch or max(3 * args.top_k, 20) |
| 170 | + out = run_engine( |
| 171 | + engine_cmd, |
| 172 | + ["query", args.text, "--root", str(REPO_ROOT), "--retriever", |
| 173 | + "lexical", "--top-k", str(fetch), "--json", "--stale-ok"], |
| 174 | + ) |
| 175 | + try: |
| 176 | + hits = json.loads(out).get("results", []) |
| 177 | + except ValueError as exc: |
| 178 | + fail(f"engine returned invalid JSON: {exc}") |
| 179 | + entries = collect_entries(hits, args) |
| 180 | + if args.json: |
| 181 | + print(json.dumps(entries, ensure_ascii=False, indent=2)) |
| 182 | + elif entries: |
| 183 | + print("\n\n".join(format_entry(e, args.max_chars) for e in entries)) |
| 184 | + if not entries: |
| 185 | + print("translation-memory: no matching translated entries", |
| 186 | + file=sys.stderr) |
| 187 | + return 0 |
| 188 | + |
| 189 | + |
| 190 | +def build_parser() -> argparse.ArgumentParser: |
| 191 | + parser = argparse.ArgumentParser( |
| 192 | + description="Translation memory over this repo's .po files." |
| 193 | + ) |
| 194 | + sub = parser.add_subparsers(dest="command", required=True) |
| 195 | + p_index = sub.add_parser("index", help="build or refresh the index") |
| 196 | + p_index.add_argument("--force", action="store_true") |
| 197 | + p_index.set_defaults(func=cmd_index) |
| 198 | + p_query = sub.add_parser("query", help="find similar translated entries") |
| 199 | + p_query.add_argument("text") |
| 200 | + p_query.add_argument("--top-k", type=int, default=5) |
| 201 | + p_query.add_argument("--fetch", type=int, default=0, |
| 202 | + help="hits to fetch before filtering " |
| 203 | + "(default max(3*top-k, 20))") |
| 204 | + p_query.add_argument("--include-fuzzy", action="store_true") |
| 205 | + p_query.add_argument("--include-untranslated", action="store_true") |
| 206 | + p_query.add_argument("--json", action="store_true") |
| 207 | + p_query.add_argument("--max-chars", type=int, default=300, |
| 208 | + help="truncate each field (0 = no truncation)") |
| 209 | + p_query.set_defaults(func=cmd_query) |
| 210 | + return parser |
| 211 | + |
| 212 | + |
| 213 | +def main() -> int: |
| 214 | + args = build_parser().parse_args() |
| 215 | + return args.func(args) |
| 216 | + |
| 217 | + |
| 218 | +if __name__ == "__main__": |
| 219 | + sys.exit(main()) |
0 commit comments