""" Free-text translator for BNA values that BNA itself doesn't translate (Description, Milestones, Principal works). Three-tier pipeline (each tier short-circuits if it has an answer): 1. Researcher overrides — the 'Free Text Overrides' sheet in TIE_Requirements.xlsx. Lets researchers pin specific translations for sentences they need to control. Highest priority. 2. Persistent JSON cache — translation results from prior runs are saved to resources/translation_cache.json so the same paragraph is never re-translated. Cache key is sha256(text|src|dst). 3. Live free API — MyMemory (api.mymemory.translated.net). No API key, no signup, ~10k words/day per IP. We chunk long text at sentence boundaries (≤450 chars per request) and rejoin. Design choices: - urllib only — no extra pip dependencies, no rebuild needed. - Chunked at sentence boundaries — preserves paragraph structure. - Graceful fallback — if API fails, return original text. Never crash. - Source-language detection trusts the BNA-detected language we already have at run time; falls back to 'en' if missing. - Cache file lives next to TIE_Requirements.xlsx so it ships with resources/ and gets updated in place. """ from __future__ import annotations import hashlib import json import os import re import threading import time import urllib.parse import urllib.request from typing import Dict, Optional CACHE_FILENAME = "translation_cache.json" CHUNK_SOFT_LIMIT = 450 # MyMemory hard cap is 500 — leave headroom API_TIMEOUT = 8 # seconds per request API_PAUSE = 0.10 # gentle throttle between calls PROVIDERS = ("mymemory", "google") # try MyMemory first, fall back to Google _lock = threading.Lock() # ---------------------------------------------------------------------- # Cache (JSON) # ---------------------------------------------------------------------- def _cache_path(tie_path: Optional[str]) -> Optional[str]: if not tie_path: return None folder = os.path.dirname(tie_path) return os.path.join(folder, CACHE_FILENAME) if folder else None def _load_cache(tie_path: Optional[str]) -> Dict[str, Dict[str, str]]: p = _cache_path(tie_path) if not p or not os.path.exists(p): return {} try: with open(p, "r", encoding="utf-8") as f: return json.load(f) or {} except Exception: return {} def _save_cache(tie_path: Optional[str], cache: Dict) -> None: p = _cache_path(tie_path) if not p: return try: os.makedirs(os.path.dirname(p), exist_ok=True) tmp = p + ".tmp" with open(tmp, "w", encoding="utf-8") as f: json.dump(cache, f, ensure_ascii=False, indent=2) os.replace(tmp, p) except Exception: pass def _cache_key(text: str, src: str, dst: str) -> str: h = hashlib.sha256() h.update(f"{src}|{dst}|{text}".encode("utf-8")) return h.hexdigest() # ---------------------------------------------------------------------- # Researcher overrides (TIE sheet) # ---------------------------------------------------------------------- def _override_lookup(tie, text: str, dst_lang: str) -> Optional[str]: """Look up text in the 'Free Text Overrides' TIE sheet. Match is exact on the trimmed English column. Returns the dst-lang cell or None if not present.""" if tie is None or not text: return None try: wb = getattr(tie, "wb", None) if wb is None or "Free Text Overrides" not in wb.sheetnames: return None ws = wb["Free Text Overrides"] norm = text.strip() col_idx = {"es": 2, "pt": 3}.get(dst_lang) if not col_idx: return None for i, row in enumerate(ws.iter_rows(values_only=True)): if i == 0: continue if not row or not row[0]: continue if str(row[0]).strip() == norm: v = row[col_idx - 1] if len(row) >= col_idx else None return str(v).strip() if v else None except Exception: return None return None # ---------------------------------------------------------------------- # MyMemory free API # ---------------------------------------------------------------------- def _mymemory(text: str, src: str, dst: str) -> Optional[str]: """Call MyMemory translation API. Returns translated text or None on any failure. Free, no API key, ~10k words/day per IP.""" if not text.strip(): return text try: params = { "q": text, "langpair": f"{src}|{dst}", } url = "https://api.mymemory.translated.net/get?" + urllib.parse.urlencode(params) with urllib.request.urlopen(url, timeout=API_TIMEOUT) as resp: data = json.loads(resp.read().decode("utf-8")) # Successful response shape: {"responseData": {"translatedText": "..."}, ...} out = ((data or {}).get("responseData") or {}).get("translatedText") if not out: return None # MyMemory sometimes returns the original on quota / unsupported pair. if out.strip().lower() == text.strip().lower(): return None return out except Exception: return None def _google_translate(text: str, src: str, dst: str) -> Optional[str]: """Call Google Translate via the unofficial public 'gtx' endpoint. No API key required. Returns translated text or None on failure. Used as a fallback when MyMemory is blocked / quota-exceeded.""" if not text.strip(): return text try: params = { "client": "gtx", "sl": src, "tl": dst, "dt": "t", "q": text, } url = "https://translate.googleapis.com/translate_a/single?" + urllib.parse.urlencode(params) req = urllib.request.Request(url, headers={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/120.0 Safari/537.36", }) with urllib.request.urlopen(req, timeout=API_TIMEOUT) as resp: data = json.loads(resp.read().decode("utf-8")) # Response shape: [[[ "translated", "src", null, null, 1 ], ...], ...] if not isinstance(data, list) or not data or not data[0]: return None parts = [] for seg in data[0]: if isinstance(seg, list) and seg and isinstance(seg[0], str): parts.append(seg[0]) out = "".join(parts).strip() if not out: return None if out.lower() == text.strip().lower(): return None return out except Exception: return None # ---------------------------------------------------------------------- # Chunking # ---------------------------------------------------------------------- def _chunks(text: str, limit: int = CHUNK_SOFT_LIMIT): """Split long text into <=limit-char chunks at sentence/newline boundaries. Preserves paragraph breaks for graceful rejoin.""" if not text: return [] if len(text) <= limit: return [text] # Split into paragraphs first paragraphs = text.split("\n") out = [] for para in paragraphs: if len(para) <= limit: out.append(para) continue # Sentence-aware split parts = re.split(r"(?<=[\.\!\?])\s+", para) buf = "" for s in parts: if not s: continue if len(buf) + len(s) + 1 <= limit: buf = (buf + " " + s).strip() if buf else s else: if buf: out.append(buf) if len(s) <= limit: buf = s else: # Last-resort hard split for i in range(0, len(s), limit): out.append(s[i:i + limit]) buf = "" if buf: out.append(buf) return out def _rejoin(original: str, chunks_in, chunks_out): """Rebuild the translated text by replacing each input chunk with its output. Preserves the original paragraph structure.""" if not chunks_in or not chunks_out: return original if len(chunks_in) != len(chunks_out): return original out = original # Replace longest-first so substring overlaps don't break replacement pairs = sorted(zip(chunks_in, chunks_out), key=lambda x: -len(x[0])) for src, dst in pairs: if dst and src in out: out = out.replace(src, dst, 1) return out # ---------------------------------------------------------------------- # Public entry point # ---------------------------------------------------------------------- def translate_free_text(text: str, src_lang: str, dst_lang: str, tie=None) -> str: """Translate `text` from src_lang to dst_lang. Returns text unchanged on any failure. Uses overrides → cache → live API. Caller doesn't need to wrap in try/except — every internal failure is swallowed.""" if not text or not text.strip(): return text if not dst_lang or src_lang == dst_lang: return text # Normalise lang codes src = (src_lang or "en").lower()[:2] dst = dst_lang.lower()[:2] # 1) Researcher override override = _override_lookup(tie, text, dst) if override: return override # 2) Persistent JSON cache tie_path = getattr(tie, "path", None) if tie else None with _lock: cache = _load_cache(tie_path) key = _cache_key(text, src, dst) cached = cache.get(key) if cached and isinstance(cached, dict) and cached.get("text"): return cached["text"] # 3) Live API — chunk, translate each, rejoin chunks = _chunks(text) out_chunks = [] failed = False provider_errors = [] for ch in chunks: translated = None for prov in PROVIDERS: if prov == "mymemory": translated = _mymemory(ch, src, dst) elif prov == "google": translated = _google_translate(ch, src, dst) if translated: break provider_errors.append(prov) time.sleep(API_PAUSE) if translated is None: failed = True out_chunks.append(ch) # keep original chunk else: out_chunks.append(translated) time.sleep(API_PAUSE) if failed and not any(o != c for o, c in zip(out_chunks, chunks)): # Nothing actually translated — log so the user sees that the # free-text was passed through untranslated. Write to a sidecar # log file next to translation_cache.json for visibility. try: if tie_path: logp = os.path.join(os.path.dirname(tie_path), "translation_failures.log") with open(logp, "a", encoding="utf-8") as fh: fh.write( f"[{int(time.time())}] {src}->{dst} " f"providers_tried={','.join(set(provider_errors))} " f"text={text[:120]!r}\n") except Exception: pass return text rebuilt = _rejoin(text, chunks, out_chunks) # Cache the result keyed by the FULL text (not per-chunk) with _lock: cache = _load_cache(tie_path) cache[key] = {"src": src, "dst": dst, "text": rebuilt, "ts": int(time.time())} _save_cache(tie_path, cache) return rebuilt