File size: 11,468 Bytes
27c9320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
"""
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