GopiBNA commited on
Commit
27c9320
·
verified ·
1 Parent(s): 23f32f1

Upload 11 files

Browse files
engine/batch_runner.py ADDED
@@ -0,0 +1,570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Batch runner for the BNA Comparator.
3
+
4
+ Reuses every comparison module (rules / transformer / scraper / comparator /
5
+ insights / translator / tie_loader) from this folder. Adds nothing new on
6
+ top of the comparison logic itself — only orchestration:
7
+
8
+ 1. Unzip the uploaded AI Excels into a working temp folder.
9
+ 2. For each AI Excel:
10
+ - Read its 'ProjectData' tab.
11
+ - Pick the permalink from the row whose Field is
12
+ 'Project Permalink' (or any of the multilingual aliases).
13
+ - Pick the project name from the 'Project Name' row.
14
+ - Build URL: https://app.bnamericas.com/project/section/all/content/<permalink>
15
+ 3. Log in to BNAmericas ONCE.
16
+ 4. For each project, load the page, scrape, compare, write outputs,
17
+ zip the per-project output folder.
18
+ 5. Write a batch_summary.xlsx at the end.
19
+
20
+ A single failure does NOT abort the batch — it is logged and the loop
21
+ moves on. The summary spreadsheet captures every row's outcome.
22
+
23
+ Performance:
24
+ * One browser context for the whole batch (login once, reuse).
25
+ * Per-project bna_fields dict is fresh (no state leak).
26
+ * TIE workbook is loaded once and reused across every project.
27
+ """
28
+ from __future__ import annotations
29
+ import os
30
+ import re
31
+ import shutil
32
+ import sys
33
+ import tempfile
34
+ import zipfile
35
+ from datetime import datetime
36
+ from typing import Callable, Dict, List, Optional
37
+
38
+ import openpyxl
39
+ from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
40
+
41
+ # Reuse comparator modules — they live alongside this file
42
+ from tie_loader import TIE
43
+ from scraper import BNAScraper
44
+ from comparator import read_ai_file, build_comparison_rows, write_outputs
45
+ import insights
46
+
47
+
48
+ BASE_URL_PREFIX = "https://app.bnamericas.com/project/section/all/content/"
49
+
50
+ # Field-name aliases (case-insensitive, EN/ES/PT) used to find the
51
+ # Permalink and Project Name rows inside each AI Excel's ProjectData.
52
+ PERMALINK_ALIASES = {
53
+ "project permalink", "permalink", "project permalink (slug)", "slug",
54
+ "permalink del proyecto", "permalink do projeto",
55
+ }
56
+ PROJECT_NAME_ALIASES = {
57
+ "project name", "name",
58
+ "nombre del proyecto", "nombre",
59
+ "nome do projeto", "nome",
60
+ }
61
+
62
+
63
+ # ----------------------------------------------------------------------
64
+ # Helpers
65
+ # ----------------------------------------------------------------------
66
+ def _slug(s: str) -> str:
67
+ """Filesystem-safe slug derived from a project name.
68
+ Kept short (<=40 chars) because Windows MAX_PATH=260 and the
69
+ full path here is: <output>/_tmp_BNA_<slug>_<ts>/Technical output
70
+ files/<long debug filename>.xlsx. Long Latin-American project names
71
+ blow past 260 instantly. 40 chars is plenty to recognise the project
72
+ when browsing the output folder."""
73
+ s = re.sub(r"[^\w\- ]+", "", str(s or "").strip())
74
+ s = re.sub(r"\s+", "_", s).strip("_-")
75
+ return s[:40] or "project"
76
+
77
+
78
+ def _norm_field(s) -> str:
79
+ return re.sub(r"\s+", " ", str(s or "")).strip().lower()
80
+
81
+
82
+ def _extract_meta_from_ai(ai_rows: List[dict]) -> Dict[str, str]:
83
+ """Return {'permalink': ..., 'name': ...} from an AI 'ProjectData' table.
84
+ Permalink: row whose Field is 'Project Permalink' (or alias).
85
+ Project Name: row whose Field is 'Project Name' (or alias)."""
86
+ out = {"permalink": "", "name": ""}
87
+ for r in ai_rows:
88
+ field_key = _norm_field(r.get("Field"))
89
+ val = r.get("Value")
90
+ if val is None:
91
+ continue
92
+ sval = str(val).strip()
93
+ if not sval:
94
+ continue
95
+ if not out["permalink"] and field_key in PERMALINK_ALIASES:
96
+ # If a full URL was pasted, strip the base.
97
+ if BASE_URL_PREFIX in sval:
98
+ sval = sval.split(BASE_URL_PREFIX, 1)[1]
99
+ out["permalink"] = sval.lstrip("/").strip()
100
+ elif not out["name"] and field_key in PROJECT_NAME_ALIASES:
101
+ out["name"] = sval
102
+ if out["permalink"] and out["name"]:
103
+ break
104
+ return out
105
+
106
+
107
+ def _lp(p: str) -> str:
108
+ """Prefix a Windows path with \\\\?\\ so it can exceed MAX_PATH (260).
109
+ No-op on non-Windows or when already prefixed."""
110
+ if os.name != "nt": return p
111
+ p = os.path.abspath(p)
112
+ if p.startswith("\\\\?\\"): return p
113
+ if p.startswith("\\\\"):
114
+ return "\\\\?\\UNC\\" + p.lstrip("\\")
115
+ return "\\\\?\\" + p
116
+
117
+
118
+ def _downloads_folder() -> str:
119
+ """Return the OS-native Downloads folder. Tries the Windows Shell
120
+ 'Known Folder' API first, then ~/Downloads, then the user home."""
121
+ home = os.path.expanduser("~")
122
+ if os.name == "nt":
123
+ try:
124
+ import ctypes
125
+ from ctypes import wintypes
126
+ FOLDERID_Downloads = "{374DE290-123F-4565-9164-39C4925E467B}"
127
+ SHGetKnownFolderPath = ctypes.windll.shell32.SHGetKnownFolderPath
128
+ SHGetKnownFolderPath.argtypes = [ctypes.c_char_p, wintypes.DWORD,
129
+ wintypes.HANDLE, ctypes.POINTER(ctypes.c_wchar_p)]
130
+ guid = (ctypes.c_byte * 16)()
131
+ ctypes.windll.ole32.IIDFromString(FOLDERID_Downloads, ctypes.byref(guid))
132
+ path_ptr = ctypes.c_wchar_p()
133
+ res = SHGetKnownFolderPath(ctypes.cast(guid, ctypes.c_char_p), 0, 0, ctypes.byref(path_ptr))
134
+ if res == 0 and path_ptr.value:
135
+ return path_ptr.value
136
+ except Exception:
137
+ pass
138
+ candidate = os.path.join(home, "Downloads")
139
+ if os.path.isdir(candidate):
140
+ return candidate
141
+ return home
142
+
143
+
144
+ def _can_write_to(folder: str) -> bool:
145
+ """Probe whether `folder` is actually writable. Returns True if a
146
+ small file can be created and deleted there, False otherwise."""
147
+ try:
148
+ os.makedirs(_lp(folder), exist_ok=True)
149
+ probe = os.path.join(folder, f".bna_probe_{os.getpid()}.tmp")
150
+ with open(_lp(probe), "w", encoding="utf-8") as f:
151
+ f.write("probe")
152
+ os.remove(_lp(probe))
153
+ return True
154
+ except Exception:
155
+ return False
156
+
157
+
158
+ def _zip_folder(src_folder: str, dst_zip: str) -> str:
159
+ """Zip every file in src_folder into dst_zip. Returns dst_zip path."""
160
+ with zipfile.ZipFile(_lp(dst_zip), "w", zipfile.ZIP_DEFLATED) as zf:
161
+ for root, _, files in os.walk(_lp(src_folder)):
162
+ for f in files:
163
+ full = os.path.join(root, f)
164
+ arc = os.path.relpath(full, _lp(src_folder))
165
+ zf.write(full, arc)
166
+ return dst_zip
167
+
168
+
169
+ def _write_summary(summary_path: str, rows: List[Dict], lang: str = "en"):
170
+ """Write batch_summary.xlsx with one row per project."""
171
+ labels = {
172
+ "en": {
173
+ "title": "Batch Summary",
174
+ "headers": ["#", "Project Name", "Permalink", "URL", "AI File",
175
+ "Status", "Output ZIP", "Matches", "Differs",
176
+ "Stale AI", "Missing on AI", "Missing on Both",
177
+ "Match Rate (%)", "Error"],
178
+ },
179
+ "es": {
180
+ "title": "Resumen del Lote",
181
+ "headers": ["#", "Nombre del Proyecto", "Permalink", "URL", "Archivo IA",
182
+ "Estado", "ZIP de Salida", "Coincidencias", "Diferencias",
183
+ "IA Antigua", "Falta en IA", "Falta en Ambos",
184
+ "Tasa de Coincidencia (%)", "Error"],
185
+ },
186
+ "pt": {
187
+ "title": "Resumo do Lote",
188
+ "headers": ["#", "Nome do Projeto", "Permalink", "URL", "Arquivo IA",
189
+ "Status", "ZIP de Saída", "Coincidências", "Diferenças",
190
+ "IA Antiga", "Falta em IA", "Falta em Ambos",
191
+ "Taxa de Coincidência (%)", "Erro"],
192
+ },
193
+ }
194
+ L = labels.get(lang, labels["en"])
195
+ wb = openpyxl.Workbook()
196
+ ws = wb.active
197
+ ws.title = L["title"][:31]
198
+ HEADER_FILL = PatternFill("solid", fgColor="1F4E78")
199
+ HEADER_FONT = Font(color="FFFFFF", bold=True)
200
+ OK_FILL = PatternFill("solid", fgColor="C6EFCE")
201
+ FAIL_FILL = PatternFill("solid", fgColor="FFC7CE")
202
+ THIN = Side(style="thin", color="BFBFBF")
203
+ BORDER = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
204
+ for i, h in enumerate(L["headers"], 1):
205
+ c = ws.cell(row=1, column=i, value=h)
206
+ c.fill = HEADER_FILL
207
+ c.font = HEADER_FONT
208
+ c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
209
+ c.border = BORDER
210
+ ws.row_dimensions[1].height = 28
211
+ for i, r in enumerate(rows, 2):
212
+ values = [
213
+ i - 1,
214
+ r.get("name", ""),
215
+ r.get("permalink", ""),
216
+ r.get("url", ""),
217
+ r.get("ai_file", ""),
218
+ r.get("status", ""),
219
+ r.get("output_zip", ""),
220
+ r.get("matches", ""),
221
+ r.get("differs", ""),
222
+ r.get("stale_ai", ""),
223
+ r.get("missing_on_ai", ""),
224
+ r.get("missing_on_both", ""),
225
+ r.get("match_rate", ""),
226
+ r.get("error", ""),
227
+ ]
228
+ for col, v in enumerate(values, 1):
229
+ c = ws.cell(row=i, column=col, value=v)
230
+ c.alignment = Alignment(wrap_text=True, vertical="top")
231
+ c.border = BORDER
232
+ fill = OK_FILL if r.get("status") == "OK" else FAIL_FILL
233
+ for col in range(1, len(values) + 1):
234
+ ws.cell(row=i, column=col).fill = fill
235
+ widths = [5, 32, 36, 60, 28, 10, 60, 10, 10, 10, 12, 14, 14, 40]
236
+ for i, w in enumerate(widths, 1):
237
+ ws.column_dimensions[ws.cell(row=1, column=i).column_letter].width = w
238
+ wb.save(_lp(summary_path))
239
+
240
+
241
+ # ----------------------------------------------------------------------
242
+ # Public entry point
243
+ # ----------------------------------------------------------------------
244
+ def run_batch(
245
+ ai_zip_path: str,
246
+ lang: str,
247
+ email: str,
248
+ password: str,
249
+ output_folder: str,
250
+ tie_path: str,
251
+ log: Callable[[str, str], None] = lambda lvl, m: None,
252
+ progress: Callable[[Dict], None] = lambda info: None,
253
+ headless: bool = True,
254
+ manual_login: bool = False,
255
+ bna_cookies: str = "",
256
+ ) -> Dict:
257
+ """Run the batch. Returns a summary dict with overall stats.
258
+
259
+ `ai_zip_path` may be EITHER:
260
+ - a path to a .zip file containing AI Excels (sub-folders inside the
261
+ ZIP are walked recursively), OR
262
+ - a path to a regular folder containing AI Excels (walked recursively).
263
+
264
+ The permalink + project name for each project are read from the
265
+ AI Excel itself ('Project Permalink' and 'Project Name' rows on the
266
+ ProjectData tab).
267
+
268
+ `log(level, message)` is the structured logger used by the GUI.
269
+ `progress(info)` is called once per project with a dict
270
+ {'index', 'total', 'name', 'status', 'output_zip', 'error',
271
+ 'metrics': <insights metrics dict>}
272
+ so the GUI can render a live progress list + dashboard.
273
+ """
274
+ ts_run = datetime.now().strftime("%Y%m%d_%H%M%S")
275
+ os.makedirs(_lp(output_folder), exist_ok=True)
276
+ summary_rows: List[Dict] = []
277
+
278
+ # 1) Resolve the AI source — accept either a ZIP file or a regular folder.
279
+ # For a ZIP: extract into a temp dir we clean up at the end.
280
+ # For a folder: walk it directly, no extraction, no temp dir.
281
+ temp_dir: Optional[str] = None
282
+ if not ai_zip_path or not os.path.exists(ai_zip_path):
283
+ raise RuntimeError(
284
+ f"AI source not found: {ai_zip_path!r}. "
285
+ f"Pass either a .zip file or a folder containing AI Excels.")
286
+ if os.path.isdir(ai_zip_path):
287
+ scan_dir = ai_zip_path
288
+ log("INFO", f"Reading AI Excels from folder: {scan_dir}")
289
+ else:
290
+ temp_dir = tempfile.mkdtemp(prefix="bna_batch_ai_")
291
+ log("INFO", f"Extracting AI Excels from ZIP to {temp_dir}")
292
+ try:
293
+ with zipfile.ZipFile(ai_zip_path, "r") as zf:
294
+ zf.extractall(temp_dir)
295
+ except zipfile.BadZipFile:
296
+ shutil.rmtree(temp_dir, ignore_errors=True)
297
+ raise RuntimeError(
298
+ f"'{ai_zip_path}' is neither a folder nor a valid .zip file.")
299
+ except Exception as e:
300
+ shutil.rmtree(temp_dir, ignore_errors=True)
301
+ raise RuntimeError(f"Could not extract AI ZIP: {e}")
302
+ scan_dir = temp_dir
303
+
304
+ # 2) Collect every AI Excel under scan_dir
305
+ ai_files: List[str] = []
306
+ for root, _, files in os.walk(scan_dir):
307
+ for f in files:
308
+ if f.lower().endswith((".xlsx", ".xls", ".xlsm")) and not f.startswith("~$"):
309
+ ai_files.append(os.path.join(root, f))
310
+ ai_files.sort()
311
+ total = len(ai_files)
312
+ src_label = "folder" if temp_dir is None else "ZIP"
313
+ log("INFO", f"{total} AI Excel files found in {src_label}.")
314
+ if total == 0:
315
+ if temp_dir is not None:
316
+ shutil.rmtree(temp_dir, ignore_errors=True)
317
+ raise RuntimeError(
318
+ f"No AI Excel files (.xlsx/.xls/.xlsm) found in {src_label} "
319
+ f"'{ai_zip_path}'. Check the path and try again.")
320
+
321
+ # 3) Load TIE once
322
+ log("INFO", f"Loading TIE workbook: {tie_path}")
323
+ tie = TIE(tie_path)
324
+ chip_list = None
325
+ try:
326
+ chip_list = list(dict.fromkeys(tie.company_chip_mapping.values()))
327
+ except Exception:
328
+ pass
329
+
330
+ # 4) Single scraper context — login once, reuse across every project.
331
+ # If the auto-login fails (Cloudflare bot detection / MFA / etc.)
332
+ # and the researcher hasn't already picked manual login, we fall
333
+ # back to manual login automatically: re-launch the browser
334
+ # visible and wait for them to sign in by hand once. Beats erroring
335
+ # out and making them restart from the GUI.
336
+ log("INFO", f"Launching browser (headless={headless})")
337
+ try:
338
+ with BNAScraper(
339
+ log=lambda m: log("INFO", m),
340
+ headless=headless,
341
+ manual_login=manual_login,
342
+ debug_dir=None,
343
+ company_chips=chip_list,
344
+ bna_lang=lang,
345
+ ) as sc:
346
+ # If the researcher handed us a session-cookie string from their
347
+ # already-signed-in browser, try that first. Falls through to
348
+ # credential login if the cookie is missing or has expired.
349
+ login_ok = False
350
+ if bna_cookies:
351
+ log("INFO", "Trying existing BNA session (cookies)...")
352
+ login_ok = sc.inject_cookies(bna_cookies)
353
+ if login_ok:
354
+ log("INFO", "Connected via existing session.")
355
+ else:
356
+ log("WARNING",
357
+ "Existing session not accepted -- falling back to "
358
+ "email + password.")
359
+ if not login_ok:
360
+ log("INFO", "Logging in to BNAmericas...")
361
+ login_ok = sc.login(email, password)
362
+ if not login_ok and not manual_login:
363
+ log("WARNING",
364
+ "Auto-login was blocked by BNAmericas (Cloudflare / MFA / "
365
+ "captcha). Re-launching browser in MANUAL login mode — "
366
+ "please sign in by hand in the window that opens; the "
367
+ "batch will continue automatically.")
368
+ # Close the current (headless) scraper and switch to a
369
+ # visible browser with manual login. The whole 'with' is
370
+ # nested so cleanup still happens.
371
+ try: sc.__exit__(None, None, None)
372
+ except Exception: pass
373
+ sc2 = BNAScraper(
374
+ log=lambda m: log("INFO", m),
375
+ headless=False,
376
+ manual_login=True,
377
+ debug_dir=None,
378
+ company_chips=chip_list,
379
+ bna_lang=lang,
380
+ ).__enter__()
381
+ try:
382
+ if not sc2.login(email, password):
383
+ raise RuntimeError("BNA login failed in both auto and manual modes.")
384
+ sc = sc2 # swap so the rest of the loop uses the new scraper
385
+ login_ok = True
386
+ except Exception:
387
+ try: sc2.__exit__(None, None, None)
388
+ except Exception: pass
389
+ raise
390
+ if not login_ok:
391
+ raise RuntimeError("BNA login failed.")
392
+
393
+ for i, ai_path in enumerate(ai_files, 1):
394
+ ai_basename = os.path.basename(ai_path)
395
+ row_summary = {
396
+ "name": "", "permalink": "", "url": "",
397
+ "ai_file": ai_basename, "status": "FAILED",
398
+ "output_zip": "", "error": "",
399
+ "matches": "", "differs": "", "stale_ai": "",
400
+ "missing_on_ai": "", "missing_on_both": "", "match_rate": "",
401
+ }
402
+ # Per-project log buffer — gets baked into the per-project
403
+ # Log.xlsx so each ZIP carries its own run log alongside
404
+ # the technical output files.
405
+ proj_log: List[str] = []
406
+ def _log_proj(level, message):
407
+ ts_msg = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
408
+ proj_log.append(f"{ts_msg}|{level}|{message}")
409
+ log(level, message)
410
+ log("INFO", f"[{i}/{total}] {ai_basename}")
411
+ _log_proj("INFO", f"Processing {ai_basename}")
412
+ try:
413
+ ai_rows = read_ai_file(ai_path)
414
+ if not ai_rows:
415
+ raise RuntimeError("AI file has no data rows.")
416
+ meta = _extract_meta_from_ai(ai_rows)
417
+ permalink = meta["permalink"]
418
+ name = meta["name"] or os.path.splitext(ai_basename)[0]
419
+ if not permalink:
420
+ raise RuntimeError(
421
+ "AI file is missing a 'Project Permalink' row. "
422
+ "Add a row with Field='Project Permalink' and "
423
+ "Value=<slug>."
424
+ )
425
+ url = BASE_URL_PREFIX + permalink.lstrip("/")
426
+ row_summary.update({"name": name, "permalink": permalink, "url": url})
427
+ _log_proj("INFO", f" Permalink: {permalink}")
428
+ _log_proj("INFO", f" URL: {url}")
429
+ _log_proj("INFO", f" {len(ai_rows)} AI fields loaded.")
430
+
431
+ # Create the per-project temp output folder up front so
432
+ # we have a place to drop Technical output files (the
433
+ # scraper's debug dumps + the rule trace). These are
434
+ # exactly the same artifacts the single-project app
435
+ # writes under 'Technical output files'.
436
+ proj_ts = datetime.now().strftime("%Y%m%d_%H%M%S")
437
+ base_name = f"BNA_{_slug(name)}"
438
+ # Stage all per-project work in TEMP so OneDrive (or
439
+ # any synced output folder) only ever sees the FINAL
440
+ # ZIP, not the hundreds of intermediate scrape /
441
+ # debug writes. This single change cuts OneDrive
442
+ # background sync activity by ~10x during batches.
443
+ project_out_dir = os.path.join(
444
+ tempfile.gettempdir(),
445
+ f"bna_proj_{_slug(name)}_{proj_ts}")
446
+ tech_folder = os.path.join(project_out_dir,
447
+ "Technical output files")
448
+ os.makedirs(_lp(tech_folder), exist_ok=True)
449
+
450
+ # Point the (already-running) scraper's debug_dir at
451
+ # this project's tech folder. Reusing the same browser
452
+ # session means we just mutate the attribute — no need
453
+ # to tear down the scraper per project.
454
+ sc.debug_dir = tech_folder
455
+
456
+ if not sc.load_project(url):
457
+ raise RuntimeError("Could not load project page.")
458
+ bna_fields = sc.extract_fields()
459
+ # Use the project name from the AI as authoritative for
460
+ # the 'Project Name' comparison row.
461
+ if name:
462
+ bna_fields["Project Name"] = name
463
+ rows = build_comparison_rows(ai_rows, bna_fields, tie,
464
+ lang=lang, debug_dir=tech_folder)
465
+ metrics = insights.compute(rows)
466
+ # Try writing to the user-selected output folder first.
467
+ # If anything fails (path too long, OneDrive lock,
468
+ # permission denied, disk full, ...), fall back to
469
+ # the user's local Downloads folder and emit a clear
470
+ # warning so they know where to find the files.
471
+ final_output_folder = output_folder
472
+ write_err = None
473
+ try:
474
+ write_outputs(
475
+ project_out_dir, rows, proj_log,
476
+ metrics, tie, base_name=base_name,
477
+ languages=(lang,),
478
+ project_url=url,
479
+ )
480
+ zip_path = os.path.join(output_folder,
481
+ f"{base_name}_{proj_ts}.zip")
482
+ _zip_folder(project_out_dir, zip_path)
483
+ except Exception as we:
484
+ write_err = we
485
+ if write_err is not None:
486
+ dl = _downloads_folder()
487
+ _log_proj("WARNING",
488
+ f" Could not write to '{output_folder}' "
489
+ f"({write_err.__class__.__name__}: {write_err}). "
490
+ f"Falling back to Downloads: {dl}")
491
+ final_output_folder = dl
492
+ # Rebuild output paths under Downloads
493
+ fb_project_dir = os.path.join(dl,
494
+ f"_t_{_slug(name)}_{proj_ts}")
495
+ fb_tech = os.path.join(fb_project_dir,
496
+ "Technical output files")
497
+ os.makedirs(_lp(fb_tech), exist_ok=True)
498
+ # Replay technical files into the fallback tech folder
499
+ try:
500
+ for fname in os.listdir(_lp(tech_folder)):
501
+ shutil.copy2(_lp(os.path.join(tech_folder, fname)),
502
+ _lp(os.path.join(fb_tech, fname)))
503
+ except Exception as ce:
504
+ _log_proj("WARNING", f" Tech copy partial: {ce}")
505
+ write_outputs(
506
+ fb_project_dir, rows, proj_log,
507
+ metrics, tie, base_name=base_name,
508
+ languages=(lang,),
509
+ project_url=url,
510
+ )
511
+ zip_path = os.path.join(dl,
512
+ f"{base_name}_{proj_ts}.zip")
513
+ _zip_folder(fb_project_dir, zip_path)
514
+ shutil.rmtree(fb_project_dir, ignore_errors=True)
515
+ _log_proj("WARNING",
516
+ f" Saved to Downloads instead: {zip_path}")
517
+ shutil.rmtree(project_out_dir, ignore_errors=True)
518
+
519
+ row_summary.update({
520
+ "status": "OK",
521
+ "output_zip": zip_path,
522
+ "matches": metrics.get("matches", 0),
523
+ "differs": metrics.get("differs", 0),
524
+ "stale_ai": metrics.get("stale_ai", 0),
525
+ "missing_on_ai": metrics.get("missing_on_ai", 0),
526
+ "missing_on_both": metrics.get("pending_disclosure", 0),
527
+ "match_rate": metrics.get("match_rate", 0),
528
+ })
529
+ _log_proj("INFO", f" OK -> {zip_path}")
530
+ progress({"index": i, "total": total, "name": name,
531
+ "status": "OK", "output_zip": zip_path, "error": "",
532
+ "metrics": metrics})
533
+ except Exception as e:
534
+ err = str(e)
535
+ _log_proj("ERROR", f" {err}")
536
+ row_summary["error"] = err
537
+ if not row_summary["name"]:
538
+ row_summary["name"] = os.path.splitext(ai_basename)[0]
539
+ progress({"index": i, "total": total,
540
+ "name": row_summary["name"],
541
+ "status": "FAILED", "output_zip": "", "error": err})
542
+ summary_rows.append(row_summary)
543
+ finally:
544
+ # Only clean up the temp dir if we created one (ZIP path). When the
545
+ # researcher pointed at a regular folder, leave it untouched.
546
+ if temp_dir is not None:
547
+ shutil.rmtree(temp_dir, ignore_errors=True)
548
+
549
+ # 5) Write batch summary — with Downloads fallback if the user's
550
+ # chosen folder rejects the write (locked, full, path too long).
551
+ summary_path = os.path.join(output_folder, f"batch_summary_{ts_run}.xlsx")
552
+ try:
553
+ _write_summary(summary_path, summary_rows, lang=lang)
554
+ log("INFO", f"Batch summary written: {summary_path}")
555
+ except Exception as se:
556
+ dl = _downloads_folder()
557
+ log("WARNING",
558
+ f"Could not write batch summary to '{output_folder}' "
559
+ f"({se.__class__.__name__}: {se}). Falling back to {dl}.")
560
+ summary_path = os.path.join(dl, f"batch_summary_{ts_run}.xlsx")
561
+ _write_summary(summary_path, summary_rows, lang=lang)
562
+ log("WARNING", f"Batch summary saved to Downloads: {summary_path}")
563
+
564
+ ok = sum(1 for r in summary_rows if r["status"] == "OK")
565
+ failed = total - ok
566
+ return {
567
+ "total": total, "ok": ok, "failed": failed,
568
+ "summary_path": summary_path,
569
+ "rows": summary_rows,
570
+ }
engine/comparator.py ADDED
@@ -0,0 +1,576 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Comparator: dispatches per-field rules from rules.py (TIE Logics.docx).
3
+ """
4
+ from __future__ import annotations
5
+ import os
6
+ import re
7
+ from datetime import datetime
8
+ from typing import Any, Dict, List, Optional
9
+ import openpyxl
10
+ from openpyxl.styles import Alignment, Font, PatternFill, Border, Side
11
+ from openpyxl.chart import PieChart, Reference
12
+ from openpyxl.worksheet.datavalidation import DataValidation
13
+
14
+ from tie_loader import TIE, _norm
15
+ import rules
16
+ import insights
17
+ import i18n
18
+ import translator as _translator
19
+
20
+
21
+ def read_ai_file(path):
22
+ """Open AI Excel even if it's locked by Excel/OneDrive — copy to temp first."""
23
+ import shutil, tempfile
24
+ src_path = path
25
+ try:
26
+ wb = openpyxl.load_workbook(src_path, data_only=True, read_only=True)
27
+ except (PermissionError, OSError):
28
+ # File may be open in Excel or sync-locked. Copy bytes to a temp file.
29
+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
30
+ tmp.close()
31
+ try:
32
+ with open(src_path, "rb") as fsrc, open(tmp.name, "wb") as fdst:
33
+ shutil.copyfileobj(fsrc, fdst)
34
+ except Exception:
35
+ # Last-ditch: shutil.copyfile (may also fail). Re-raise after.
36
+ shutil.copyfile(src_path, tmp.name)
37
+ wb = openpyxl.load_workbook(tmp.name, data_only=True, read_only=True)
38
+ if "ProjectData" not in wb.sheetnames:
39
+ raise ValueError("AI file missing 'ProjectData' tab")
40
+ ws = wb["ProjectData"]
41
+ headers = None
42
+ rows = []
43
+ for i, row in enumerate(ws.iter_rows(values_only=True)):
44
+ if i == 0:
45
+ headers = [str(h or "").strip() for h in row]; continue
46
+ if not row or not row[0]: continue
47
+ rows.append(dict(zip(headers, row)))
48
+ return rows
49
+
50
+
51
+ def _canon(s):
52
+ if s is None: return ""
53
+ return re.sub(r"\s+", " ", str(s)).strip().lower()
54
+
55
+
56
+ def _combine_ai_rows(ai_rows):
57
+ """Multi-row handling: when the AI Excel has several rows for the
58
+ same Field name, merge them into a single row. Values are joined
59
+ with ', '. Date is the most recent (max). Other metadata picks the
60
+ first non-empty value."""
61
+ merged = {}
62
+ order = []
63
+ for r in ai_rows:
64
+ field = r.get("Field") or ""
65
+ key = re.sub(r"\s+", " ", str(field)).strip().lower()
66
+ if key not in merged:
67
+ merged[key] = dict(r)
68
+ order.append(key)
69
+ continue
70
+ cur = merged[key]
71
+ # Combine value
72
+ v_old = "" if cur.get("Value") in (None, "") else str(cur.get("Value")).strip()
73
+ v_new = "" if r.get("Value") in (None, "") else str(r.get("Value")).strip()
74
+ if v_new and v_new not in v_old.split(", "):
75
+ cur["Value"] = (v_old + ", " + v_new) if v_old else v_new
76
+ # Pick the most recent date
77
+ from datetime import datetime as _dt
78
+ def _dparse(s):
79
+ if s is None: return None
80
+ if isinstance(s, _dt): return s
81
+ try:
82
+ from rules import parse_date as _pd
83
+ return _pd(s)
84
+ except Exception:
85
+ return None
86
+ d_old = _dparse(cur.get("Date"))
87
+ d_new = _dparse(r.get("Date"))
88
+ if d_new and (d_old is None or d_new > d_old):
89
+ cur["Date"] = r.get("Date")
90
+ # First non-empty fill for other metadata
91
+ for fk in ("Notes", "Confidence", "Strategy", "Source", "Source URL"):
92
+ if not cur.get(fk) and r.get(fk):
93
+ cur[fk] = r.get(fk)
94
+ return [merged[k] for k in order]
95
+
96
+
97
+ # Fields that are metadata, not data points — they appear in the output
98
+ # for context (so the researcher can see what URL was scraped) but they
99
+ # are NEVER compared against BNA. Verdict is left blank and they are
100
+ # excluded from the Match / Differ tallies.
101
+ _NO_COMPARE_FIELDS = {
102
+ "project permalink", "permalink",
103
+ "permalink del proyecto", "permalink do projeto",
104
+ "slug",
105
+ }
106
+
107
+
108
+ def build_comparison_rows(ai_rows, bna_fields, tie, lang="es", debug_dir=None):
109
+ out = []
110
+ trace_lines = []
111
+ ai_rows = _combine_ai_rows(ai_rows)
112
+ for r in ai_rows:
113
+ ai_field = r.get("Field") or ""
114
+ ai_value = r.get("Value")
115
+ ai_notes = r.get("Notes")
116
+ ai_conf = r.get("Confidence")
117
+ ai_strategy = r.get("Strategy")
118
+ ai_source = r.get("Source")
119
+ ai_source_url = r.get("Source URL")
120
+ ai_date = r.get("Date")
121
+
122
+ # Skip comparison for permalink-style metadata rows — they exist
123
+ # in the AI sheet purely so the batch app can navigate to the BNA
124
+ # URL. Show them in the output unchanged, with no verdict.
125
+ if str(ai_field).strip().lower() in _NO_COMPARE_FIELDS:
126
+ out.append({
127
+ "ai_field": ai_field, "ai_value": ai_value, "ai_notes": ai_notes,
128
+ "ai_confidence": ai_conf, "ai_strategy": ai_strategy,
129
+ "ai_source": ai_source, "ai_source_url": ai_source_url,
130
+ "ai_date": ai_date,
131
+ "transformed": "" if ai_value is None else str(ai_value),
132
+ "bna_value": "", "match": "", "reco": "",
133
+ })
134
+ continue
135
+
136
+ bna_data = _find_bna(ai_field, bna_fields, tie)
137
+ transformed, bna_value, match, reco = rules.apply_rule(
138
+ ai_field, ai_value, ai_date, bna_data, tie, lang,
139
+ bna_fields=bna_fields,
140
+ )
141
+ # Per-row trace for diagnostics
142
+ try:
143
+ bna_repr = repr(bna_data)[:300]
144
+ trace_lines.append(
145
+ f"AI_FIELD={ai_field!r}\n"
146
+ f" AI_VALUE={ai_value!r}\n"
147
+ f" AI_DATE={ai_date!r}\n"
148
+ f" BNA_DATA_FOUND={bna_repr}\n"
149
+ f" TRANSFORMED={transformed!r}\n"
150
+ f" BNA_VALUE_OUT={bna_value!r}\n"
151
+ f" MATCH={match}\n"
152
+ f" RECO={reco!r}\n"
153
+ )
154
+ except Exception: pass
155
+ out.append({
156
+ "ai_field": ai_field, "ai_value": ai_value, "ai_notes": ai_notes,
157
+ "ai_confidence": ai_conf, "ai_strategy": ai_strategy,
158
+ "ai_source": ai_source, "ai_source_url": ai_source_url,
159
+ "ai_date": ai_date, "transformed": transformed,
160
+ "bna_value": bna_value, "match": match, "reco": reco,
161
+ })
162
+ # Persist trace
163
+ if debug_dir:
164
+ try:
165
+ import os as _os
166
+ _os.makedirs(debug_dir, exist_ok=True)
167
+ with open(_os.path.join(debug_dir, "comparison_trace.txt"),
168
+ "w", encoding="utf-8") as f:
169
+ f.write("\n".join(trace_lines))
170
+ except Exception: pass
171
+ return out
172
+
173
+
174
+ FIELD_TO_BNA_LABELS = {
175
+ "owner company": ["Owner", "Owners"],
176
+ "concessionaire / operator company": ["Concessionaire/operator", "Concessionaire", "Operator"],
177
+ "contractor company": ["Main contractor", "Contractor", "EPC", "EPCM"],
178
+ "engineering company": ["Engineering"],
179
+ "equipment / technology provider": ["Technology provider", "Equipment"],
180
+ "consultancy company": ["Consultancy"],
181
+ "project name": ["Project Name", "Name"],
182
+ "project stage": ["Current stage", "Stage"],
183
+ "project description": ["Description", "Descripción", "Descrição"],
184
+ "description": ["Description", "Descripción", "Descrição"],
185
+ "descripción": ["Description", "Descripción", "Descrição"],
186
+ "descripción del proyecto": ["Description", "Descripción", "Descrição"],
187
+ "descrição": ["Description", "Descripción", "Descrição"],
188
+ "descrição do projeto": ["Description", "Descripción", "Descrição"],
189
+ "property type": ["Property Type"],
190
+ "development type": ["Development type"],
191
+ "capex": ["Capex", "CAPEX"],
192
+ "lifespan": ["Lifespan"],
193
+ "project type": ["Project Type", "Project Type and capacity"],
194
+ "milestones": ["Milestones"],
195
+ "announcement date": ["Project Announced"],
196
+ "completion_end of construction date": ["End of Construction"],
197
+ "construction start date": ["Start of Construction"],
198
+ "contractor tendering start date": ["Start of Main Contractor Tendering"],
199
+ "detailed engineering start date": ["Start of Detailed Engineering"],
200
+ "environmental approval date": ["Environmental and Social Approval"],
201
+ "environmental approval": ["Environmental and Social Approval"],
202
+ "environmental and social approval": ["Environmental and Social Approval"],
203
+ "environmental and social approval date": ["Environmental and Social Approval"],
204
+ "operations start date": ["Start of Operation"],
205
+ "tendering start date": ["Start of Main Contractor Tendering"],
206
+ "latitude and longitude": ["Coordinates", "Latitude", "Longitude"],
207
+ "main works description": ["Principal works", "Principal Works"],
208
+ "project documentation": [],
209
+ "project manager": ["Project Manager"],
210
+ "purchasing manager": ["Purchasing Manager"],
211
+ "engineering manager": ["Engineering Manager"],
212
+ "capacity": ["Capacity"],
213
+ }
214
+
215
+
216
+ def _find_bna(ai_field, bna_fields, tie=None):
217
+ if not bna_fields: return None
218
+ key = re.sub(r"\s+", " ", str(ai_field).strip().lower())
219
+
220
+ # Contact roles — preferred path: Contacts radio + Area chip click harvested
221
+ # names directly from the page into "manager::<Role>".
222
+ if key in ("project manager", "purchasing manager", "engineering manager"):
223
+ target_role = {"project manager": "Project Manager",
224
+ "purchasing manager": "Purchasing Manager",
225
+ "engineering manager": "Engineering Manager"}[key]
226
+ names = []
227
+ v = bna_fields.get(f"manager::{target_role}")
228
+ if v:
229
+ names = list(v) if isinstance(v, list) else [str(v)]
230
+ # Fallback to legacy bracket-position path
231
+ if not names and tie is not None:
232
+ for k, val in bna_fields.items():
233
+ if not str(k).startswith("position::"): continue
234
+ bracket = str(k)[len("position::"):]
235
+ mapped = tie.map_project_position_to_role(bracket)
236
+ if mapped and _canon(mapped) == _canon(target_role):
237
+ if isinstance(val, list): names.extend(val)
238
+ else: names.append(str(val))
239
+ # de-dupe preserving order
240
+ seen = set(); uniq = []
241
+ for n in names:
242
+ if n and n not in seen:
243
+ seen.add(n); uniq.append(n)
244
+ return uniq if uniq else None
245
+
246
+ # Company fields — preferred path: scraper harvested chip-by-chip into
247
+ # "company::<Chip>" using the editable TIE 'Company Chip Mapping' sheet.
248
+ if tie is not None:
249
+ chip = tie.map_ai_company_field_to_chip(ai_field)
250
+ if chip:
251
+ v = bna_fields.get(f"company::{chip}")
252
+ if v is not None:
253
+ return v if isinstance(v, list) else [str(v)]
254
+ # Fallback: any key whose canon equals the chip label.
255
+ for k, val in bna_fields.items():
256
+ if _canon(k) == _canon(chip):
257
+ return val if isinstance(val, list) else [str(val)]
258
+ return None # Chip configured but not harvested → Not Available
259
+
260
+ candidates = FIELD_TO_BNA_LABELS.get(key, [ai_field])
261
+ # Pass 1: exact canonical match — strongest signal, used everywhere.
262
+ for cand in candidates:
263
+ for k, v in bna_fields.items():
264
+ if _canon(k) == _canon(cand): return v
265
+ # Pass 2: substring fallback — but only for fields where it's safe.
266
+ # 'capacity' substring matches 'project type and capacity' which is the
267
+ # raw merged blob, not real capacity. For capacity, instead derive the
268
+ # numeric portion from the merged 'Project Type and capacity' field
269
+ # so the comparison never shows 'Not available' when the value is in
270
+ # fact present on the BNA page.
271
+ if key == "capacity":
272
+ blob_labels = ("project type and capacity",
273
+ "tipo y capacidad del proyecto",
274
+ "tipo de proyecto y capacidad",
275
+ "tipo e capacidade do projeto",
276
+ "tipo de projeto e capacidade")
277
+ for k, v in bna_fields.items():
278
+ kc = _canon(k)
279
+ if kc in blob_labels:
280
+ blob = str(v or "")
281
+ # Capture digit run + lowercase unit phrase. Stops at the
282
+ # next Capitalized word (BNA blob format is
283
+ # "<TypeName> <number><lower-unit> <TypeName>...").
284
+ m = re.search(
285
+ r"(\d[\d\.\,]*(?:\s+[a-zà-ÿ/]+){1,10})",
286
+ blob)
287
+ if m:
288
+ return m.group(1).strip()
289
+ return None
290
+ for cand in candidates:
291
+ for k, v in bna_fields.items():
292
+ if _canon(cand) and _canon(cand) in _canon(k): return v
293
+ return None
294
+
295
+
296
+ HEADER_FILL = PatternFill("solid", fgColor="1F4E78")
297
+ HEADER_FONT = Font(color="FFFFFF", bold=True)
298
+ MATCH_FILL = PatternFill("solid", fgColor="C6EFCE") # green
299
+ DIFFER_FILL = PatternFill("solid", fgColor="FFEB9C") # yellow
300
+ PENDING_FILL = PatternFill("solid", fgColor="DDDDDD") # grey - Missing on Both
301
+ MISSING_AI_FILL = PatternFill("solid", fgColor="D6E9FE") # light blue - Missing on AI
302
+ STALE_FILL = PatternFill("solid", fgColor="E9D5FF") # light purple - Stale AI
303
+ THIN = Side(style="thin", color="BFBFBF")
304
+ BORDER = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
305
+
306
+ NOT_AVAILABLE = {"es": "No disponible", "en": "Not Available", "pt": "Não disponível"}
307
+
308
+
309
+ def _style_header(ws, n):
310
+ for col in range(1, n + 1):
311
+ c = ws.cell(row=1, column=col)
312
+ c.fill = HEADER_FILL; c.font = HEADER_FONT
313
+ c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
314
+ c.border = BORDER
315
+ ws.row_dimensions[1].height = 28
316
+
317
+
318
+ def _autosize(ws, max_w=60):
319
+ """Compute column widths. Skips MergedCell instances which lack
320
+ .column / .column_letter (openpyxl quirk when a sheet contains
321
+ merged ranges, e.g. our BNA Project URL banner)."""
322
+ from openpyxl.utils import get_column_letter
323
+ for col_idx in range(1, ws.max_column + 1):
324
+ letter = get_column_letter(col_idx)
325
+ longest = 0
326
+ for r in range(1, ws.max_row + 1):
327
+ cell = ws.cell(row=r, column=col_idx)
328
+ # Skip MergedCells (no own value past the anchor)
329
+ if cell.__class__.__name__ == "MergedCell":
330
+ continue
331
+ v = "" if cell.value is None else str(cell.value)
332
+ lines = v.splitlines() if v else [""]
333
+ cur = max((len(s) for s in lines), default=0)
334
+ longest = max(longest, min(max_w, cur))
335
+ ws.column_dimensions[letter].width = max(12, min(longest + 2, max_w))
336
+
337
+
338
+ def write_comparison_sheet(ws, rows, lang, tie, reco_only=False, project_url=None):
339
+ base_headers = i18n.HEADERS[lang]
340
+ extra_headers = i18n.RECO_HEADERS_EXTRA[lang] if reco_only else []
341
+ headers = list(base_headers) + list(extra_headers)
342
+ # Row 1: BNA Project URL banner (merged across the whole header range)
343
+ url_label = "BNA Project URL: " + (project_url or "")
344
+ cell = ws.cell(row=1, column=1, value=url_label)
345
+ cell.font = Font(bold=True, color="1F4E78")
346
+ cell.alignment = Alignment(horizontal="left", vertical="center")
347
+ if len(headers) > 1:
348
+ ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=len(headers))
349
+ ws.row_dimensions[1].height = 22
350
+ # Row 2: column headers
351
+ for i, h in enumerate(headers, 1):
352
+ ws.cell(row=2, column=i, value=h)
353
+ for col in range(1, len(headers) + 1):
354
+ c = ws.cell(row=2, column=col)
355
+ c.fill = HEADER_FILL; c.font = HEADER_FONT
356
+ c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
357
+ c.border = BORDER
358
+ ws.row_dimensions[2].height = 28
359
+ r = 3
360
+ na = NOT_AVAILABLE.get(lang, "Not Available")
361
+ # Recommendations sheet includes rows that need researcher attention:
362
+ # 'Differ' (value mismatch) and 'Stale AI' (AI value older than BNA review).
363
+ # Visual fill colors keep the two categories separate (yellow vs purple).
364
+ RECO_VERDICTS = {"Differ", "Stale AI"}
365
+ for row in rows:
366
+ if reco_only and row["match"] not in RECO_VERDICTS:
367
+ continue
368
+ match_tr = i18n.MATCH_LABEL[lang].get(row["match"], row["match"])
369
+ bna_disp = row["bna_value"] if row["bna_value"] not in (None, "", []) else na
370
+ # Translate BNA enum values (Property Type / Development Type /
371
+ # Project Type / Stage) into the selected output language.
372
+ try:
373
+ if lang != "en" and bna_disp and bna_disp != na:
374
+ bna_disp = i18n.translate_bna_value(row["ai_field"], bna_disp, lang, tie)
375
+ except Exception:
376
+ pass
377
+ # Capacity unit-phrase translation (numbers stay; unit text is
378
+ # localised). Applies to both BNA value and AI Transformed.
379
+ try:
380
+ if lang != "en" and _norm(row.get("ai_field")) == "capacity":
381
+ if bna_disp and bna_disp != na:
382
+ bna_disp = i18n.translate_capacity_value(bna_disp, lang, tie)
383
+ # Capacity transformed gets handled below via transformed_disp
384
+ except Exception:
385
+ pass
386
+ # Translate the AI field name into the selected output language so
387
+ # the 'Campo IA / AI Field' column reads natively.
388
+ try:
389
+ field_disp = i18n.translate_field_name(row["ai_field"], lang, tie) if tie else row["ai_field"]
390
+ except Exception:
391
+ field_disp = row["ai_field"]
392
+ # Translate AI-side placeholder phrases first (Not Publicly Disclosed,
393
+ # Not yet disclosed, N/A, TBD, ...) into the selected output language.
394
+ def _tr_ph(v):
395
+ try:
396
+ return i18n.translate_placeholder(v, lang) if lang != "en" else v
397
+ except Exception:
398
+ return v
399
+ ai_value_disp = _tr_ph(row["ai_value"])
400
+ ai_source_disp = _tr_ph(row.get("ai_source") or "")
401
+ ai_date_disp = _tr_ph(row.get("ai_date") or "")
402
+ ai_source_url_disp = _tr_ph(row.get("ai_source_url") or "")
403
+ transformed_disp = row["transformed"]
404
+ # Capacity transformed translation
405
+ try:
406
+ if lang != "en" and _norm(row.get("ai_field")) == "capacity" and transformed_disp:
407
+ transformed_disp = i18n.translate_capacity_value(
408
+ transformed_disp, lang, tie)
409
+ except Exception:
410
+ pass
411
+ # Free-text translation (Description / Milestones / Principal works)
412
+ # via the three-tier translator (overrides → cache → MyMemory API).
413
+ try:
414
+ ai_field_norm = _norm(row.get("ai_field"))
415
+ FREE_TEXT_FIELDS = {
416
+ "project description", "description",
417
+ "descripción", "descripción del proyecto",
418
+ "descrição", "descrição do projeto",
419
+ "milestones", "hitos", "marcos",
420
+ "main works description",
421
+ "descripción de obras principales",
422
+ "descrição das obras principais",
423
+ "principal works", "obras principales", "obras principais",
424
+ }
425
+ if lang != "en" and ai_field_norm in FREE_TEXT_FIELDS:
426
+ if bna_disp and bna_disp != na and len(str(bna_disp).strip()) > 20:
427
+ bna_disp = _translator.translate_free_text(
428
+ str(bna_disp), src_lang="en", dst_lang=lang, tie=tie)
429
+ if ai_value_disp and len(str(ai_value_disp).strip()) > 20:
430
+ ai_value_disp = _translator.translate_free_text(
431
+ str(ai_value_disp), src_lang="en", dst_lang=lang, tie=tie)
432
+ if transformed_disp and len(str(transformed_disp).strip()) > 20:
433
+ transformed_disp = _translator.translate_free_text(
434
+ str(transformed_disp), src_lang="en", dst_lang=lang, tie=tie)
435
+ except Exception:
436
+ pass
437
+ # "Recommendation" column now carries the Match/Differ verdict directly.
438
+ values = [
439
+ field_disp, ai_value_disp, transformed_disp,
440
+ bna_disp, match_tr,
441
+ ai_source_disp,
442
+ ai_source_url_disp,
443
+ ai_date_disp,
444
+ ]
445
+ if reco_only:
446
+ values.extend(["", ""]) # Researcher Command, Researcher's Remark
447
+ for col, v in enumerate(values, 1):
448
+ cell = ws.cell(row=r, column=col, value=v)
449
+ cell.alignment = Alignment(wrap_text=True, vertical="top")
450
+ cell.border = BORDER
451
+ verdict = row["match"]
452
+ if verdict == "Match":
453
+ fill = MATCH_FILL
454
+ elif verdict == "Missing on Both":
455
+ fill = PENDING_FILL
456
+ elif verdict == "Missing on AI":
457
+ fill = MISSING_AI_FILL
458
+ elif verdict == "Stale AI":
459
+ fill = STALE_FILL
460
+ else:
461
+ fill = DIFFER_FILL
462
+ for col in range(1, len(headers) + 1):
463
+ ws.cell(row=r, column=col).fill = fill
464
+ r += 1
465
+ # Researcher Command dropdown on Recommendations sheet only
466
+ if reco_only and r > 3:
467
+ opts = ",".join(i18n.VALID_OPTIONS[lang])
468
+ dv = DataValidation(type="list", formula1=f'"{opts}"', allow_blank=True,
469
+ showDropDown=False)
470
+ dv.error = "Select Valid or Invalid"
471
+ dv.errorTitle = "Invalid value"
472
+ dv.prompt = "Pick Valid or Invalid"
473
+ dv.promptTitle = "Researcher Command"
474
+ col_letter = ws.cell(row=2, column=len(base_headers) + 1).column_letter
475
+ dv.add(f"{col_letter}3:{col_letter}{r-1}")
476
+ ws.add_data_validation(dv)
477
+ _autosize(ws)
478
+ ws.freeze_panes = "A3"
479
+
480
+
481
+ def write_insights_sheet(ws, metrics, lang):
482
+ headers = i18n.INSIGHTS_HEADERS[lang]
483
+ for i, h in enumerate(headers, 1):
484
+ ws.cell(row=1, column=i, value=h)
485
+ _style_header(ws, len(headers))
486
+ table = insights.to_table(metrics, lang=lang)
487
+ for i, (k, v) in enumerate(table, 2):
488
+ ws.cell(row=i, column=1, value=k).border = BORDER
489
+ ws.cell(row=i, column=2, value=v).border = BORDER
490
+ # Append verdict legend so leadership reading the Insights sheet has a
491
+ # reference for what each verdict means.
492
+ r = len(table) + 3
493
+ ws.cell(row=r, column=1, value=i18n.VERDICT_LEGEND_TITLE.get(lang, "Verdict legend")).font = Font(bold=True)
494
+ r += 1
495
+ for line in i18n.VERDICT_LEGEND_ITEMS.get(lang, []):
496
+ ws.cell(row=r, column=1, value=line).alignment = Alignment(wrap_text=True)
497
+ ws.merge_cells(start_row=r, start_column=1, end_row=r, end_column=2)
498
+ r += 1
499
+ _autosize(ws, max_w=80)
500
+
501
+
502
+ def write_log_sheet(ws, log_lines, lang):
503
+ headers = i18n.LOG_HEADERS[lang]
504
+ for i, h in enumerate(headers, 1):
505
+ ws.cell(row=1, column=i, value=h)
506
+ _style_header(ws, len(headers))
507
+ r = 2
508
+ for line in log_lines:
509
+ parts = line.split("|", 2)
510
+ if len(parts) == 3: ts, lvl, msg = parts
511
+ else: ts, lvl, msg = datetime.now().isoformat(timespec="seconds"), "INFO", line
512
+ ws.cell(row=r, column=1, value=ts.strip()).border = BORDER
513
+ ws.cell(row=r, column=2, value=lvl.strip()).border = BORDER
514
+ ws.cell(row=r, column=3, value=msg.strip()).border = BORDER
515
+ ws.cell(row=r, column=3).alignment = Alignment(wrap_text=True, vertical="top")
516
+ r += 1
517
+ _autosize(ws, max_w=80)
518
+ ws.freeze_panes = "A2"
519
+
520
+
521
+ SHEET_TITLES = {
522
+ "comparison": {"es": "Comparación", "en": "Comparison", "pt": "Comparação"},
523
+ "insights": {"es": "Indicadores", "en": "Insights", "pt": "Indicadores"},
524
+ "log": {"es": "Registro", "en": "Log", "pt": "Registro"},
525
+ "reco": {"es": "Recomendaciones", "en": "Recommendations", "pt": "Recomendações"},
526
+ }
527
+
528
+
529
+ def _long(p):
530
+ """Prefix the Windows long-path marker on `p` so paths over the
531
+ legacy 260-char MAX_PATH limit are accepted. No-op on non-Windows
532
+ or paths already carrying the marker."""
533
+ if os.name == "nt" and not str(p).startswith("\\\\?\\"):
534
+ return "\\\\?\\" + os.path.abspath(p)
535
+ return p
536
+
537
+
538
+ def _safe_save(wb, path):
539
+ # Ensure parent dir exists (defensive — gui.py creates it but if a
540
+ # long-path issue trims it, recreate here).
541
+ try:
542
+ os.makedirs(_long(os.path.dirname(path)), exist_ok=True)
543
+ except Exception:
544
+ pass
545
+ try:
546
+ wb.save(_long(path)); return path
547
+ except PermissionError:
548
+ stem, ext = os.path.splitext(path)
549
+ alt = f"{stem}_{datetime.now().strftime('%H%M%S')}{ext}"
550
+ wb.save(_long(alt)); return alt
551
+
552
+
553
+ def write_outputs(out_dir, rows, log_lines, metrics, tie,
554
+ base_name="BNA_Comparison", languages=("es",), project_url=None):
555
+ os.makedirs(_long(out_dir), exist_ok=True)
556
+ ts = datetime.now().strftime("%Y%m%d_%H%M%S")
557
+ written = []
558
+ for lang in languages:
559
+ wb = openpyxl.Workbook(); ws = wb.active
560
+ ws.title = SHEET_TITLES["comparison"][lang]
561
+ write_comparison_sheet(ws, rows, lang, tie, project_url=project_url)
562
+ ws_ins = wb.create_sheet(SHEET_TITLES["insights"][lang])
563
+ p1 = os.path.join(out_dir, f"{base_name}_Comparison_{lang}_{ts}.xlsx")
564
+ written.append(_safe_save(wb, p1))
565
+
566
+ wb = openpyxl.Workbook(); ws = wb.active
567
+ write_log_sheet(ws, log_lines, lang)
568
+ p2 = os.path.join(out_dir, f"{base_name}_Log_{lang}_{ts}.xlsx")
569
+ written.append(_safe_save(wb, p2))
570
+
571
+ wb = openpyxl.Workbook(); ws = wb.active
572
+ ws.title = SHEET_TITLES["reco"][lang]
573
+ write_comparison_sheet(ws, rows, lang, tie, reco_only=True, project_url=project_url)
574
+ p3 = os.path.join(out_dir, f"{base_name}_Recommendations_{lang}_{ts}.xlsx")
575
+ written.append(_safe_save(wb, p3))
576
+ return written
engine/currency.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Currency detection + USD conversion for Capex values.
3
+
4
+ Pipeline (per TIE Logics):
5
+ 1. Detect currency from the Agentic AI Capex string (USD, US$, BRL, R$, EUR, €, etc.)
6
+ 2. Parse the numeric amount and the unit multiplier (mn, bn, mil, mil millones, raw).
7
+ 3. Convert non-USD amounts to USD using the FX rate for the source publication
8
+ date. If that date is missing, use the BNA 'Last expert review' date.
9
+ 4. Express the result in MILLIONS of USD (BNA always uses USD millions).
10
+ 5. Round and format per the requested output language.
11
+
12
+ FX rates resolution order:
13
+ a) TIE 'FX Rates' sheet — exact (currency, date) match.
14
+ b) TIE 'FX Rates' sheet — closest date (same currency).
15
+ c) Live API call to frankfurter.app (works for major world currencies).
16
+ d) Hard-coded last-resort approximate rate.
17
+
18
+ The TIE sheet is the editable source of truth. Researchers can add rows there
19
+ without touching code.
20
+ """
21
+ from __future__ import annotations
22
+ import json
23
+ import re
24
+ import urllib.request
25
+ from datetime import datetime
26
+ from typing import Dict, List, Optional, Tuple
27
+
28
+
29
+ # ---------- Currency detection ----------
30
+ # Covers every currency that appears in the BNAmericas currency dropdown,
31
+ # plus a few common majors (GBP/CAD/AUD/JPY/CNY). Order matters: longer /
32
+ # more specific patterns first so 'CL$' matches as CLP before generic '$'.
33
+ CURRENCY_SYMBOLS = [
34
+ (r"US\s*\$|USD\b|U\.S\.\s*Dollars?\b", "USD"),
35
+ (r"R\$|BRL\b|reais\b|reais?\b", "BRL"),
36
+ (r"€|EUR\b|euros?\b", "EUR"),
37
+ (r"£|GBP\b|pounds?\s+sterling\b", "GBP"),
38
+ (r"AR\$|ARS\b|argentine\s+pesos?\b", "ARS"),
39
+ (r"CL\$|CLP\b|chilean\s+pesos?\b", "CLP"),
40
+ (r"CO\$|COP\b|colombian\s+pesos?\b", "COP"),
41
+ (r"MX\$|MXN\b|mexican\s+pesos?\b", "MXN"),
42
+ (r"PEN\b|S/\.|soles?\b|peruvian\s+sol\b", "PEN"),
43
+ (r"BOB\b|bolivian(?:os)?\b", "BOB"),
44
+ (r"PYG\b|guaran[ií]?es?\b", "PYG"),
45
+ (r"UYU\b|uruguayan\s+pesos?\b", "UYU"),
46
+ (r"VEF\b|venezuelan\s+bol[íi]var(?:\s+fuerte)?\b", "VEF"),
47
+ (r"VES\b|bol[íi]var(?:es)?(?:\s+soberano)?\b", "VES"),
48
+ (r"XCD\b|east\s+caribbean\s+dollars?\b", "XCD"),
49
+ (r"BSD\b|bahamian\s+dollars?\b", "BSD"),
50
+ (r"BBD\b|barbadian\s+dollars?\b|bds\$", "BBD"),
51
+ (r"CRC\b|costa\s+rican\s+col[óo]n(?:es)?\b", "CRC"),
52
+ (r"CUC\b|cuban\s+convertible\s+pesos?\b", "CUC"),
53
+ (r"GTQ\b|guatemalan\s+quetzal(?:es)?\b|quetzal(?:es)?\b", "GTQ"),
54
+ (r"GYD\b|guyanese\s+dollars?\b", "GYD"),
55
+ (r"HTG\b|haitian\s+gourdes?\b|gourdes?\b", "HTG"),
56
+ (r"HNL\b|honduran\s+lempiras?\b|lempiras?\b", "HNL"),
57
+ (r"BMD\b|bermudian\s+dollars?\b|bermudan\s+dollars?\b", "BMD"),
58
+ (r"KYD\b|cayman\s+islands?\s+dollars?\b", "KYD"),
59
+ (r"FKP\b|falkland\s+islands?\s+pounds?\b", "FKP"),
60
+ (r"JMD\b|jamaican\s+dollars?\b|J\$", "JMD"),
61
+ (r"NIO\b|nicaraguan\s+c[óo]rdobas?\b|c[óo]rdobas?\b", "NIO"),
62
+ (r"PAB\b|panamanian\s+balboas?\b|balboas?\b", "PAB"),
63
+ (r"DOP\b|dominican\s+pesos?\b|RD\$", "DOP"),
64
+ (r"SRD\b|surinamese\s+dollars?\b|SR\$", "SRD"),
65
+ (r"TTD\b|trinidad(?:\s+and\s+tobago)?\s+dollars?\b|TT\$", "TTD"),
66
+ (r"BZD\b|belize(?:an)?\s+dollars?\b|BZ\$", "BZD"),
67
+ (r"CAD\b|canadian\s+dollars?\b", "CAD"),
68
+ (r"AUD\b|australian\s+dollars?\b", "AUD"),
69
+ (r"JPY\b|yen\b", "JPY"),
70
+ (r"CNY\b|RMB\b|yuan\b", "CNY"),
71
+ # Generic "$" defaults to USD UNLESS preceded by a country code.
72
+ (r"\$", "USD"),
73
+ ]
74
+
75
+ # Unit multipliers expressed as "amount × multiplier = raw units"
76
+ # We always normalize to RAW UNITS first, then divide by 1e6 to get millions.
77
+ # Patterns handle English / Spanish / Portuguese with accents (ã, õ, ñ, é).
78
+ # Short-scale 'illion' multipliers. Listed largest→smallest so the regex
79
+ # engine sees the longer token first ('quattuordecillion' before
80
+ # 'decillion'). Each multiplier is 10^(3n+3) per the short scale.
81
+ UNIT_PATTERNS = [
82
+ # 10^54 — septemdecillion
83
+ (r"(?i)\bseptem(?:de)?cilli\w*\b", 10**54),
84
+ # 10^51 — sexdecillion
85
+ (r"(?i)\bsex(?:de)?cilli\w*\b", 10**51),
86
+ # 10^48 — quindecillion
87
+ (r"(?i)\bquin(?:de)?cilli\w*\b", 10**48),
88
+ # 10^45 — quattuordecillion
89
+ (r"(?i)\bquattuor(?:de)?cilli\w*\b", 10**45),
90
+ # 10^42 — tredecillion
91
+ (r"(?i)\btredecilli\w*\b", 10**42),
92
+ # 10^39 — duodecillion
93
+ (r"(?i)\bduodecilli\w*\b", 10**39),
94
+ # 10^36 — undecillion
95
+ (r"(?i)\bundecilli\w*\b", 10**36),
96
+ # 10^33 — decillion
97
+ (r"(?i)\bdecilli\w*\b", 10**33),
98
+ # 10^30 — nonillion
99
+ (r"(?i)\bnonilli\w*\b", 10**30),
100
+ # 10^27 — octillion
101
+ (r"(?i)\boctilli\w*\b", 10**27),
102
+ # 10^24 — septillion
103
+ (r"(?i)\bseptilli\w*\b", 10**24),
104
+ # 10^21 — sextillion
105
+ (r"(?i)\bsextilli\w*\b", 10**21),
106
+ # 10^18 — quintillion
107
+ (r"(?i)\bquintilli\w*\b", 10**18),
108
+ # 10^15 — quadrillion
109
+ (r"(?i)\bquadrilli\w*\b|\bcuatrill[oó]n(?:es)?\b", 10**15),
110
+ # 10^12 — trillion (es: trillón / pt: trilhão also = 10^12 short scale)
111
+ (r"(?i)(?:\btrillions?\b|\btn\b|\btrillon[eé]?s?\b|\btrilh\w*\b)", 10**12),
112
+ # 10^9 — billion / bn / b / mil millones / bilhão
113
+ (r"(?i)(?:\bbillions?\b|\bbn\b|\bb\b|\bmil\s+millones\b|\bbillon[eé]?s?\b|\bbilh\w*\b)", 10**9),
114
+ # 10^6 — million / mn / mm / m / millón / milhão
115
+ (r"(?i)(?:\bmillions?\b|\bmillon[eé]?s?\b|\bmn\b|\bmm\b|\bmilh\w*\b|\bm\b)", 10**6),
116
+ # 10^3 — thousand / k / mil / miles
117
+ (r"(?i)(?:\bthousands?\b|\bmiles\b|\bmil\b|\bk\b)", 10**3),
118
+ ]
119
+
120
+
121
+ def _detect_currency(s):
122
+ """Return ISO code for the currency in the string, or 'USD' if a generic
123
+ '$' appears, or None if no currency token is present."""
124
+ if not s: return None
125
+ for pat, code in CURRENCY_SYMBOLS:
126
+ if re.search(pat, s, re.IGNORECASE):
127
+ return code
128
+ return None
129
+
130
+
131
+ def _detect_unit_multiplier(s):
132
+ """Return integer multiplier (e.g. 1_000_000 for 'million'). Defaults to 1."""
133
+ if not s: return 1
134
+ low = s.lower()
135
+ for pat, mult in UNIT_PATTERNS:
136
+ if re.search(pat, low, re.IGNORECASE):
137
+ return mult
138
+ return 1
139
+
140
+
141
+ def _parse_numeric(s):
142
+ """Pull the FIRST decimal/integer number from a string. Handles:
143
+ - Plain integers of any length: '838000000' -> 838000000
144
+ - Grouped with thousands separators: '1,234,567' / '1.234.567'
145
+ - Mixed grouped + decimal: '1.234.567,89' or '1,234,567.89'
146
+ - Plain decimals: '1234.56'
147
+ The grouped pattern is tried FIRST so '1,234' parses as 1234 (US
148
+ thousands) rather than 1.234 (European decimal); if not grouped,
149
+ plain integer/decimal fallback runs."""
150
+ if s is None: return None
151
+ if isinstance(s, (int, float)): return float(s)
152
+ text = re.sub(r"[A-Za-z$€£¥/\\]", " ", str(s))
153
+ text = re.sub(r"\s+", " ", text).strip()
154
+ m = re.search(
155
+ r"-?(?:\d{1,3}(?:[.,\s]\d{3})+(?:[.,]\d+)?|\d+(?:[.,]\d+)?)",
156
+ text)
157
+ if not m: return None
158
+ raw = m.group(0)
159
+ has_comma = "," in raw
160
+ has_dot = "." in raw
161
+ if has_comma and has_dot:
162
+ # Whichever comes LAST is the decimal sep
163
+ if raw.rfind(",") > raw.rfind("."):
164
+ raw = raw.replace(".", "").replace(",", ".")
165
+ else:
166
+ raw = raw.replace(",", "")
167
+ elif has_comma:
168
+ # If exactly two digits after the last comma → decimal; else thousands
169
+ last = raw.rsplit(",", 1)
170
+ if len(last) == 2 and 1 <= len(last[1]) <= 2:
171
+ raw = raw.replace(",", ".")
172
+ else:
173
+ raw = raw.replace(",", "")
174
+ raw = raw.replace(" ", "")
175
+ try: return float(raw)
176
+ except ValueError: return None
177
+
178
+
179
+ def parse_capex_value(s):
180
+ """Parse '2,000 US$ mn' / '1.5 bilhões R$' / '€ 100 mn' style strings.
181
+ Returns dict {currency, amount_raw_units, amount, multiplier} or None.
182
+ """
183
+ if s is None or str(s).strip() == "": return None
184
+ text = str(s).strip()
185
+ currency = _detect_currency(text) or "USD"
186
+ multiplier = _detect_unit_multiplier(text)
187
+ amount = _parse_numeric(text)
188
+ if amount is None: return None
189
+ raw_units = amount * multiplier
190
+ return {
191
+ "currency": currency,
192
+ "amount": amount,
193
+ "multiplier": multiplier,
194
+ "raw_units": raw_units,
195
+ }
196
+
197
+
198
+ # ---------- FX rate resolution ----------
199
+
200
+ # Last-resort approximate rates (updated periodically). Only used when both
201
+ # the TIE sheet and the API are unreachable.
202
+ FALLBACK_RATES = {
203
+ "USD": 1.0,
204
+ "BRL": 0.18, # Brazilian Real
205
+ "ARS": 0.001, # Argentine Peso
206
+ "CLP": 0.001, # Chilean Peso
207
+ "COP": 0.00024, # Colombian Peso
208
+ "MXN": 0.05, # Mexican Peso
209
+ "PEN": 0.27, # Peruvian Sol
210
+ "EUR": 1.07,
211
+ "GBP": 1.26,
212
+ "BOB": 0.145,
213
+ "PYG": 0.00013,
214
+ "UYU": 0.025,
215
+ "VES": 0.027, # Bolívar Soberano
216
+ "VEF": 0.0000001, # Bolívar Fuerte (legacy, hyperinflated)
217
+ "XCD": 0.37, # East Caribbean Dollar (pegged ~2.70/USD)
218
+ "BSD": 1.0, # Bahamian Dollar (pegged 1:1 USD)
219
+ "BBD": 0.50, # Barbadian Dollar (pegged 2:1)
220
+ "CRC": 0.0019, # Costa Rican Colón
221
+ "CUC": 1.0, # Cuban Convertible (legacy 1:1)
222
+ "GTQ": 0.13, # Guatemalan Quetzal
223
+ "GYD": 0.0048, # Guyanese Dollar
224
+ "HTG": 0.0076, # Haitian Gourde
225
+ "HNL": 0.040, # Honduran Lempira
226
+ "BMD": 1.0, # Bermudian Dollar (pegged 1:1)
227
+ "KYD": 1.20, # Cayman Islands Dollar (pegged ~1.20)
228
+ "FKP": 1.26, # Falkland Pound (pegged to GBP)
229
+ "JMD": 0.0064, # Jamaican Dollar
230
+ "NIO": 0.027, # Nicaraguan Córdoba
231
+ "PAB": 1.0, # Panamanian Balboa (pegged 1:1)
232
+ "DOP": 0.017, # Dominican Peso
233
+ "SRD": 0.027, # Surinamese Dollar
234
+ "TTD": 0.15, # Trinidad & Tobago Dollar
235
+ "BZD": 0.50, # Belize Dollar (pegged 2:1)
236
+ "CAD": 0.73,
237
+ "AUD": 0.65,
238
+ "JPY": 0.0067,
239
+ "CNY": 0.14,
240
+ }
241
+
242
+
243
+ def _parse_date(s):
244
+ if not s: return None
245
+ if isinstance(s, datetime): return s
246
+ s = str(s).strip()
247
+ if not s: return None
248
+ s = re.sub(r"T\d{2}:\d{2}.*$", "", s)
249
+ for fmt in ("%Y-%m-%d","%Y/%m/%d","%Y.%m.%d","%d-%m-%Y","%d/%m/%Y","%d.%m.%Y"):
250
+ try: return datetime.strptime(s, fmt)
251
+ except ValueError: pass
252
+ # Try month-name parsing (e.g. "March 2024")
253
+ months = {"january":1,"february":2,"march":3,"april":4,"may":5,"june":6,
254
+ "july":7,"august":8,"september":9,"october":10,"november":11,"december":12,
255
+ "jan":1,"feb":2,"mar":3,"apr":4,"jun":6,"jul":7,"aug":8,"sep":9,"sept":9,
256
+ "oct":10,"nov":11,"dec":12,
257
+ "enero":1,"febrero":2,"marzo":3,"abril":4,"mayo":5,"junio":6,"julio":7,
258
+ "agosto":8,"septiembre":9,"octubre":10,"noviembre":11,"diciembre":12}
259
+ tokens = re.findall(r"[A-Za-zÀ-ÿ]+|\d+", s)
260
+ month = year = None
261
+ for t in tokens:
262
+ tl = t.lower()
263
+ if tl in months: month = months[tl]
264
+ elif t.isdigit() and len(t) == 4: year = int(t)
265
+ if month and year:
266
+ try: return datetime(year, month, 1)
267
+ except ValueError: return None
268
+ return None
269
+
270
+
271
+ # In-process cache: (currency, yyyy-mm-dd) -> rate
272
+ _RATE_CACHE: Dict[Tuple[str, str], float] = {}
273
+
274
+ def _rate_from_tie(currency, date_str, tie):
275
+ """Look up the rate from the TIE 'FX Rates' sheet. Tries exact match
276
+ first, then nearest date for the same currency."""
277
+ if tie is None: return None
278
+ rates: List[Tuple[str, datetime, float]] = getattr(tie, "fx_rates", None) or []
279
+ if not rates: return None
280
+ cur = (currency or "").upper()
281
+ target_dt = _parse_date(date_str)
282
+ if target_dt:
283
+ for c, dt, rate in rates:
284
+ if c.upper() == cur and dt.date() == target_dt.date():
285
+ return rate
286
+ same = [(dt, rate) for c, dt, rate in rates if c.upper() == cur]
287
+ if same and target_dt:
288
+ same.sort(key=lambda x: abs((x[0] - target_dt).days))
289
+ return same[0][1]
290
+ if same:
291
+ return same[0][1]
292
+ return None
293
+
294
+
295
+ def _rate_from_frankfurter(currency, date_str):
296
+ """Try multiple free FX APIs in order. Returns rate to multiply
297
+ `currency` by to get USD, or None if all sources fail.
298
+
299
+ Sources, in order:
300
+ 1. fawazahmed0/currency-api (broad coverage: COP, ARS, MXN, CLP,
301
+ PEN, etc. — historical via /YYYY-MM-DD/ or /latest/)
302
+ 2. Frankfurter (only ~33 majors — fallback for the few it covers)
303
+ """
304
+ cur = (currency or "").upper()
305
+ if cur == "USD": return 1.0
306
+ dt = _parse_date(date_str)
307
+ date_iso = dt.strftime("%Y-%m-%d") if dt else None
308
+
309
+ # Source 1: fawazahmed0 currency-api (covers ALL BNA dropdown currencies)
310
+ cur_lower = cur.lower()
311
+ urls_1 = []
312
+ if date_iso:
313
+ urls_1 += [
314
+ f"https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@{date_iso}/v1/currencies/{cur_lower}.json",
315
+ f"https://{date_iso}.currency-api.pages.dev/v1/currencies/{cur_lower}.json",
316
+ ]
317
+ urls_1 += [
318
+ f"https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/{cur_lower}.json",
319
+ f"https://latest.currency-api.pages.dev/v1/currencies/{cur_lower}.json",
320
+ ]
321
+ for url in urls_1:
322
+ try:
323
+ with urllib.request.urlopen(url, timeout=8) as resp:
324
+ data = json.loads(resp.read().decode("utf-8"))
325
+ rate = data.get(cur_lower, {}).get("usd")
326
+ if rate is not None:
327
+ return float(rate)
328
+ except Exception:
329
+ continue
330
+
331
+ # Source 2: Frankfurter (limited to majors but reliable)
332
+ if date_iso:
333
+ url = f"https://api.frankfurter.app/{date_iso}?from={cur}&to=USD"
334
+ else:
335
+ url = f"https://api.frankfurter.app/latest?from={cur}&to=USD"
336
+ try:
337
+ with urllib.request.urlopen(url, timeout=8) as resp:
338
+ data = json.loads(resp.read().decode("utf-8"))
339
+ rate = data.get("rates", {}).get("USD")
340
+ if rate is not None:
341
+ return float(rate)
342
+ except Exception:
343
+ pass
344
+ return None
345
+
346
+
347
+ def get_fx_rate(currency, date_str, tie=None):
348
+ """Return the rate to multiply the source amount by to get USD.
349
+
350
+ Order:
351
+ 1. Live frankfurter.app for the EXACT requested date — primary
352
+ source so historical rates align with the publication / review
353
+ date instead of being capped by stale TIE-sheet entries.
354
+ 2. TIE 'FX Rates' sheet — used only if the API call fails (e.g.
355
+ no internet, currency unsupported by Frankfurter).
356
+ 3. Hard-coded fallback rate.
357
+
358
+ The rate for each (currency, date) is cached per-process so we don't
359
+ hit the API repeatedly inside a single run."""
360
+ cur = (currency or "USD").upper()
361
+ cache_key = (cur, str(date_str or ""))
362
+ if cache_key in _RATE_CACHE:
363
+ return _RATE_CACHE[cache_key]
364
+ rate = _rate_from_frankfurter(cur, date_str)
365
+ if rate is None:
366
+ rate = _rate_from_tie(cur, date_str, tie)
367
+ if rate is None:
368
+ rate = FALLBACK_RATES.get(cur)
369
+ if rate is not None:
370
+ _RATE_CACHE[cache_key] = float(rate)
371
+ return rate
372
+
373
+
374
+ def to_usd_millions(parsed, date_for_fx, tie=None):
375
+ """Convert a parsed Capex dict to a USD millions float."""
376
+ if not parsed: return None, None, "could not parse amount"
377
+ raw_units = parsed["raw_units"]
378
+ cur = parsed["currency"]
379
+ rate = get_fx_rate(cur, date_for_fx, tie)
380
+ if rate is None:
381
+ return None, None, f"no FX rate for {cur} on {date_for_fx}"
382
+ usd_units = raw_units * rate
383
+ usd_millions = usd_units / 1_000_000.0
384
+ return usd_millions, rate, f"{cur}->USD @ {rate:.6f}"
385
+
386
+
387
+ def fmt_usd_millions(value, lang):
388
+ """Format the USD-millions number with the language-specific thousands /
389
+ decimal separator. Always appends 'US$ mn' to match BNAmericas style."""
390
+ if value is None: return ""
391
+ decimals = 0 if abs(value) >= 100 else (1 if abs(value) >= 1 else 2)
392
+ s = f"{value:,.{decimals}f}"
393
+ if lang in ("es", "pt"):
394
+ s = s.replace(",", "§").replace(".", ",").replace("§", ".")
395
+ return f"{s} US$ mn"
396
+
397
+
398
+ def normalize_to_usd_mn(value_str, date_for_fx=None, tie=None, lang="en"):
399
+ """Parse any capex string and return it formatted as a USD-millions
400
+ string. If parsing fails, return the original string."""
401
+ if value_str is None: return ""
402
+ s = str(value_str).strip()
403
+ if not s: return ""
404
+ parsed = parse_capex_value(s)
405
+ if not parsed: return s
406
+ usd_mn, rate, src = to_usd_millions(parsed, date_for_fx, tie)
407
+ if usd_mn is None: return s
408
+ return fmt_usd_millions(usd_mn, lang)
engine/i18n.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ i18n: headers, labels and confidence translations for outputs.
3
+ Only 6 columns now per TIE Logics spec.
4
+ """
5
+ from __future__ import annotations
6
+ from tie_loader import TIE, _norm
7
+
8
+ HEADERS = {
9
+ "es": ["Campo IA", "Valor IA", "Valor Transformado", "Valor BNA", "Recomendación", "Fuente IA", "URL Fuente IA", "Fecha de Fuente IA"],
10
+ "en": ["AI Field", "AI Value", "Transformed Value", "BNA Value", "Recommendation", "AI Source", "AI Source URL", "AI Source Date"],
11
+ "pt": ["Campo IA", "Valor IA", "Valor Transformado", "Valor BNA", "Recomendação", "Fonte IA", "URL Fonte IA", "Data da Fonte IA"],
12
+ }
13
+
14
+ # Extra reviewer columns appended only on the Recommendations sheet
15
+ RECO_HEADERS_EXTRA = {
16
+ "es": ["Comando Investigador (Válido/Inválido)", "Comentario del Investigador"],
17
+ "en": ["Researcher Command (Valid/Invalid)", "Researcher's Remark"],
18
+ "pt": ["Comando do Pesquisador (Válido/Inválido)", "Observação do Pesquisador"],
19
+ }
20
+
21
+ VALID_OPTIONS = {
22
+ "es": ["Válido", "Inválido"],
23
+ "en": ["Valid", "Invalid"],
24
+ "pt": ["Válido", "Inválido"],
25
+ }
26
+
27
+ INSIGHTS_HEADERS = {
28
+ "es": ["Métrica", "Valor"],
29
+ "en": ["Metric", "Value"],
30
+ "pt": ["Métrica", "Valor"],
31
+ }
32
+
33
+ LOG_HEADERS = {
34
+ "es": ["Marca de tiempo", "Nivel", "Mensaje"],
35
+ "en": ["Timestamp", "Level", "Message"],
36
+ "pt": ["Data/Hora", "Nível", "Mensagem"],
37
+ }
38
+
39
+ CONFIDENCE = {
40
+ "en": {"high": "High", "medium": "Medium", "low": "Low"},
41
+ "es": {"high": "Alta", "medium": "Media", "low": "Baja"},
42
+ "pt": {"high": "Alta", "medium": "Média", "low": "Baixa"},
43
+ }
44
+
45
+ VERDICT_LEGEND_TITLE = {
46
+ "es": "Leyenda de veredictos — qué significa cada indicador",
47
+ "en": "Verdict legend — what each indicator means",
48
+ "pt": "Legenda de veredictos — o que cada indicador significa",
49
+ }
50
+
51
+ VERDICT_LEGEND_ITEMS = {
52
+ "es": [
53
+ "Coincide — el valor de la IA coincide con BNA.",
54
+ "Difiere — IA y BNA tienen valores diferentes; se genera una recomendación.",
55
+ "Falta en Ambos — ni la IA ni BNA tienen el valor; nada que actualizar.",
56
+ "Falta en IA — BNA tiene el valor; la IA no lo extrajo. El equipo de IA puede revisar.",
57
+ "IA Antigua — los valores difieren, pero la fecha de la fuente IA es anterior a la última revisión BNA; BNA puede ya tener la información más reciente.",
58
+ ],
59
+ "en": [
60
+ "Match — AI value agrees with BNA.",
61
+ "Differ — AI and BNA both have values but they don't match; a recommendation is generated.",
62
+ "Missing on Both — neither AI nor BNA has the value; nothing to act on.",
63
+ "Missing on AI — BNA already has the value; AI didn't extract it. The AI team can investigate.",
64
+ "Stale AI — values differ but the AI source date is older than BNA's last expert review; BNA likely already has the more current value.",
65
+ ],
66
+ "pt": [
67
+ "Coincide — o valor da IA coincide com BNA.",
68
+ "Difere — IA e BNA têm valores, mas não coincidem; uma recomendação é gerada.",
69
+ "Falta em Ambos — nem IA nem BNA têm o valor; nada para atualizar.",
70
+ "Falta em IA — BNA tem o valor; a IA não extraiu. A equipe de IA pode revisar.",
71
+ "IA Antiga — os valores diferem, mas a data da fonte IA é anterior à última revisão BNA; BNA provavelmente já tem o valor mais recente.",
72
+ ],
73
+ }
74
+
75
+ MATCH_LABEL = {
76
+ "es": {
77
+ "Match": "Coincide", "Differ": "Difiere",
78
+ "Missing on Both": "Falta en Ambos",
79
+ "Missing on AI": "Falta en IA",
80
+ "Stale AI": "IA Antigua",
81
+ "": "",
82
+ },
83
+ "en": {
84
+ "Match": "Match", "Differ": "Differ",
85
+ "Missing on Both": "Missing on Both",
86
+ "Missing on AI": "Missing on AI",
87
+ "Stale AI": "Stale AI",
88
+ "": "",
89
+ },
90
+ "pt": {
91
+ "Match": "Coincide", "Differ": "Difere",
92
+ "Missing on Both": "Falta em Ambos",
93
+ "Missing on AI": "Falta em IA",
94
+ "Stale AI": "IA Antiga",
95
+ "": "",
96
+ },
97
+ }
98
+
99
+
100
+ def translate_confidence(value, lang):
101
+ if value is None: return ""
102
+ return CONFIDENCE.get(lang, CONFIDENCE["en"]).get(_norm(value), str(value))
103
+
104
+
105
+ # Built-in translations for the standard AI Excel field-name vocabulary.
106
+ # Keyed by lowercased English form. TIE-sheet lookups (current_stages,
107
+ FIELD_NAME_I18N = {
108
+ "project name": {"es": "Nombre del Proyecto", "pt": "Nome do Projeto"},
109
+ "owner company": {"es": "Empresa Propietaria", "pt": "Empresa Proprietária"},
110
+ "concessionaire / operator company": {"es": "Concesionario / Operador", "pt": "Concessionário / Operador"},
111
+ "contractor company": {"es": "Empresa Contratista", "pt": "Empresa Contratada"},
112
+ "engineering company": {"es": "Empresa de Ingeniería", "pt": "Empresa de Engenharia"},
113
+ "equipment / technology provider": {"es": "Proveedor de Equipos / Tecnología", "pt": "Fornecedor de Equipamentos / Tecnologia"},
114
+ "consultancy company": {"es": "Consultoría", "pt": "Consultoria"},
115
+ "project stage": {"es": "Etapa del Proyecto", "pt": "Fase do Projeto"},
116
+ "project description": {"es": "Descripción del Proyecto", "pt": "Descrição do Projeto"},
117
+ "property type": {"es": "Tipo de Propiedad", "pt": "Tipo de Propriedade"},
118
+ "development type": {"es": "Tipo de Desarrollo", "pt": "Tipo de Desenvolvimento"},
119
+ "capex": {"es": "Capex", "pt": "Capex"},
120
+ "lifespan": {"es": "Vida Útil", "pt": "Tempo de Vida"},
121
+ "project type": {"es": "Tipo de Proyecto", "pt": "Tipo de Projeto"},
122
+ "milestones": {"es": "Hitos", "pt": "Marcos"},
123
+ "announcement date": {"es": "Fecha de Anuncio", "pt": "Data de Anúncio"},
124
+ "completion_end of construction date": {"es": "Fecha de Finalización de la Construcción", "pt": "Data de Fim da Construção"},
125
+ "construction start date": {"es": "Fecha de Inicio de Construcción", "pt": "Data de Início da Construção"},
126
+ "contractor tendering start date": {"es": "Fecha de Inicio de Licitación de Contratista", "pt": "Data de Início da Licitação do Contratante"},
127
+ "detailed engineering start date": {"es": "Fecha de Inicio de Ingeniería Detallada", "pt": "Data de Início da Engenharia Detalhada"},
128
+ "environmental approval date": {"es": "Fecha de Aprobación Ambiental", "pt": "Data de Aprovação Ambiental"},
129
+ "operations start date": {"es": "Fecha de Inicio de Operación", "pt": "Data de Início de Operação"},
130
+ "tendering start date": {"es": "Fecha de Inicio de Licitación", "pt": "Data de Início da Licitação"},
131
+ "end of operation date": {"es": "Fecha de Fin de Operación", "pt": "Data de Fim de Operação"},
132
+ "environmental impact assessment submission_presentation date": {"es": "Fecha de Presentación del EIA", "pt": "Data de Apresentação do EIA"},
133
+ "feasibility studies start date": {"es": "Fecha de Inicio de Estudios de Factibilidad", "pt": "Data de Início dos Estudos de Viabilidade"},
134
+ "pre-feasibility studies start date": {"es": "Fecha de Inicio de Estudios de Pre-Factibilidad", "pt": "Data de Início dos Estudos de Pré-Viabilidade"},
135
+ "latitude and longitude": {"es": "Latitud y Longitud", "pt": "Latitude e Longitude"},
136
+ "main works description": {"es": "Descripción de Obras Principales", "pt": "Descrição das Obras Principais"},
137
+ "project documentation": {"es": "Documentación del Proyecto", "pt": "Documentação do Projeto"},
138
+ "project manager": {"es": "Gerente de Proyecto", "pt": "Gerente de Projeto"},
139
+ "purchasing manager": {"es": "Gerente de Compras", "pt": "Gerente de Compras"},
140
+ "engineering manager": {"es": "Gerente de Ingeniería", "pt": "Gerente de Engenharia"},
141
+ "capacity": {"es": "Capacidad", "pt": "Capacidade"},
142
+ "products required": {"es": "Productos Requeridos", "pt": "Produtos Necessários"},
143
+ "services required": {"es": "Servicios Requeridos", "pt": "Serviços Necessários"},
144
+ }
145
+
146
+
147
+ def translate_field_name(name, lang, tie: TIE):
148
+ if not name: return name
149
+ key = _norm(name)
150
+ if key in FIELD_NAME_I18N and lang in FIELD_NAME_I18N[key]:
151
+ return FIELD_NAME_I18N[key][lang]
152
+ for row in tie.current_stages:
153
+ if _norm(name) == _norm(row.get("substage")) or _norm(name) == _norm(row.get("en")):
154
+ return row.get(lang, name) or name
155
+ for enum_key, langs in tie.company_roles.items():
156
+ if _norm(name) == _norm(enum_key) or _norm(name) == _norm(langs.get("en", "")):
157
+ return langs.get(lang, name) or name
158
+ return name
159
+
160
+
161
+ RECO_TEMPLATE = {
162
+ "en": "{label} differs. Agentic AI value: {ai}. BNA Platform value: {bna}.",
163
+ "es": "{label} difiere. Valor de la IA Agéntica: {ai}. Valor de la Plataforma BNA: {bna}.",
164
+ "pt": "{label} difere. Valor da IA Agêntica: {ai}. Valor da Plataforma BNA: {bna}.",
165
+ }
166
+
167
+ RECO_MISSING_TEMPLATE = {
168
+ "en": "Missing information identified from Agentic AI output: {extra}",
169
+ "es": "Información faltante identificada en la salida de la IA Agéntica: {extra}",
170
+ "pt": "Informação ausente identificada na saída da IA Agêntica: {extra}",
171
+ }
172
+
173
+ NOT_AVAILABLE_LABEL = {
174
+ "en": "Not Available",
175
+ "es": "No disponible",
176
+ "pt": "Não disponível",
177
+ }
178
+
179
+
180
+ # Placeholder phrases the AI Excel commonly uses to mean 'no value'.
181
+ # When the user picks ES/PT, these are translated for display so the
182
+ # whole row reads natively. Lookup is case-insensitive on the trimmed
183
+ # value. Only triggers when the value is EXACTLY one of these phrases.
184
+ PLACEHOLDER_TRANSLATIONS = {
185
+ "not publicly disclosed": {"es": "No divulgado públicamente", "pt": "Não divulgado publicamente"},
186
+ "not yet disclosed": {"es": "Aún no divulgado", "pt": "Ainda não divulgado"},
187
+ "not disclosed": {"es": "No divulgado", "pt": "Não divulgado"},
188
+ "not available": {"es": "No disponible", "pt": "Não disponível"},
189
+ "to be determined": {"es": "Por determinar", "pt": "A ser determinado"},
190
+ "to be disclosed": {"es": "Por divulgar", "pt": "A ser divulgado"},
191
+ "tbd": {"es": "Por determinar", "pt": "A ser determinado"},
192
+ "n/a": {"es": "N/D", "pt": "N/D"},
193
+ "n.a.": {"es": "N/D", "pt": "N/D"},
194
+ "na": {"es": "N/D", "pt": "N/D"},
195
+ "none": {"es": "Ninguno", "pt": "Nenhum"},
196
+ "null": {"es": "Nulo", "pt": "Nulo"},
197
+ "no disponible": {"es": "No disponible", "pt": "Não disponível"},
198
+ "no divulgado": {"es": "No divulgado", "pt": "Não divulgado"},
199
+ }
200
+
201
+
202
+ def translate_placeholder(value, lang):
203
+ """If `value` is a known placeholder phrase, return its translation
204
+ in the target language. Otherwise return the original value."""
205
+ if not value or lang == "en": return value
206
+ key = str(value).strip().lower()
207
+ if not key: return value
208
+ tr = PLACEHOLDER_TRANSLATIONS.get(key, {}).get(lang)
209
+ return tr if tr else value
210
+
211
+
212
+ # Map AI field name -> which translation bucket to use for the BNA value.
213
+ # Keys are lowercased AI field names. The bucket name matches the key in
214
+ # tie.bna_translations (property_type / development_type / project_type /
215
+ # project_stage). Unmapped fields are left untranslated (free text).
216
+ _BNA_FIELD_BUCKET = {
217
+ "property type": "property_type",
218
+ "development type": "development_type",
219
+ "project type": "project_type",
220
+ "project stage": "project_stage",
221
+ "current stage": "project_stage",
222
+ }
223
+
224
+
225
+ def translate_capacity_value(text, lang, tie):
226
+ """Translate the unit phrases inside a capacity value to ES/PT
227
+ while keeping the numbers intact.
228
+ '8 Number of stations, 33 kilometers' -> '8 número de estaciones, 33 kilómetros'
229
+ Items are split on commas / semicolons; each item is parsed for its
230
+ leading number, the remaining unit text is looked up in the editable
231
+ 'Capacity Unit Translations' sheet. Falls back to original text if
232
+ no translation is found."""
233
+ if not text or lang == "en" or tie is None: return text
234
+ table = getattr(tie, "capacity_unit_translations", {}) or {}
235
+ if not table: return text
236
+ import re as _re
237
+ parts = _re.split(r"\s*[,;]\s*", str(text))
238
+ out = []
239
+ any_change = False
240
+ for p in parts:
241
+ s = p.strip()
242
+ if not s: continue
243
+ # Match optional number (with thousands sep / decimal) then unit
244
+ m = _re.match(r"^([\d.,\s]+)?\s*(.*)$", s, flags=_re.UNICODE)
245
+ if not m:
246
+ out.append(s); continue
247
+ num = (m.group(1) or "").strip()
248
+ unit = (m.group(2) or "").strip()
249
+ if not unit:
250
+ out.append(s); continue
251
+ key = _re.sub(r"\s+", " ", unit).strip().lower()
252
+ tr = table.get(key, {}).get(lang)
253
+ if tr and tr.lower() != unit.lower():
254
+ any_change = True
255
+ out.append((num + " " + tr).strip() if num else tr)
256
+ else:
257
+ out.append(s)
258
+ return ", ".join(out) if any_change else text
259
+
260
+ def translate_bna_value(ai_field, bna_value, lang, tie):
261
+ """Translate a BNA-platform value into the selected output language
262
+ using the editable translation sheets."""
263
+ if not bna_value or lang == "en" or tie is None:
264
+ return bna_value
265
+ bucket = _BNA_FIELD_BUCKET.get(_norm(ai_field))
266
+ if not bucket: return bna_value
267
+ table = (getattr(tie, "bna_translations", {}) or {}).get(bucket, {})
268
+ if not table: return bna_value
269
+ import re as _re
270
+ full_key = str(bna_value).strip().lower()
271
+ if full_key in table:
272
+ t = table[full_key].get(lang)
273
+ if t: return t
274
+ parts = _re.split(r"\s*,\s*", str(bna_value))
275
+ parts = _re.split(r"\s*,\s*", str(bna_value))
276
+ translated_parts = []
277
+ any_change = False
278
+ for p in parts:
279
+ key = p.strip().lower()
280
+ if key in table:
281
+ t = table[key].get(lang)
282
+ if t and t != p:
283
+ any_change = True
284
+ translated_parts.append(t or p)
285
+ continue
286
+ base = _re.sub(r"\s*\([^)]*\)\s*$", "", key).strip()
287
+ if base and base in table:
288
+ tail = _re.search(r"\s*\([^)]*\)\s*$", p)
289
+ t = table[base].get(lang) or p
290
+ if tail: t = (t + " " + tail.group(0).strip()).strip()
291
+ if t != p: any_change = True
292
+ translated_parts.append(t)
293
+ continue
294
+ translated_parts.append(p)
295
+ return ", ".join(translated_parts) if any_change else bna_value
engine/insights.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Insights: computes summary metrics from comparison rows.
3
+ Feeds the Tkinter dashboard and also writes an Insights sheet to outputs.
4
+ """
5
+ from __future__ import annotations
6
+ from collections import Counter
7
+ from datetime import datetime
8
+ from typing import Any, Dict, List
9
+
10
+
11
+ def compute(rows: List[Dict[str, Any]]) -> Dict[str, Any]:
12
+ def _verdict(r):
13
+ m = r.get("match")
14
+ if m is True: return "match"
15
+ if m is False: return "differ"
16
+ if isinstance(m, str): return m.lower()
17
+ return ""
18
+ # Exclude metadata rows (Project Permalink, etc.) where verdict is
19
+ # left blank — they should not inflate the total or appear in any
20
+ # KPI tile.
21
+ rows = [r for r in rows if _verdict(r)]
22
+ total = len(rows)
23
+ matches = sum(1 for r in rows if _verdict(r) == "match")
24
+ differs = sum(1 for r in rows if _verdict(r) == "differ")
25
+ pending = sum(1 for r in rows if _verdict(r) == "missing on both")
26
+ already = sum(1 for r in rows if _verdict(r) == "missing on ai")
27
+ stale = sum(1 for r in rows if _verdict(r) == "stale ai")
28
+ unknown = total - matches - differs - pending - already - stale
29
+
30
+ conf = Counter()
31
+ for r in rows:
32
+ c = (r.get("ai_confidence") or "").strip().lower()
33
+ if c:
34
+ conf[c.capitalize()] += 1
35
+
36
+ sources = Counter(((r.get("ai_source") or "").strip() or "Unknown") for r in rows)
37
+ with_ai_date = sum(1 for r in rows if r.get("ai_date_parsed"))
38
+ with_bna_review = sum(1 for r in rows if r.get("bna_review_parsed"))
39
+
40
+ avg_freshness_days = None
41
+ freshness_vals = []
42
+ now = datetime.utcnow()
43
+ for r in rows:
44
+ d = r.get("ai_date_parsed")
45
+ if d:
46
+ freshness_vals.append((now - d).days)
47
+ if freshness_vals:
48
+ avg_freshness_days = round(sum(freshness_vals) / len(freshness_vals), 1)
49
+
50
+ return {
51
+ "total_fields": total, "matches": matches, "differs": differs,
52
+ "pending_disclosure": pending,
53
+ "missing_on_ai": already,
54
+ "stale_ai": stale,
55
+ "unknown": unknown,
56
+ "match_rate": round((matches / total) * 100, 1) if total else 0,
57
+ "confidence_breakdown": dict(conf),
58
+ # Recommendations sheet includes Differ + Stale AI rows.
59
+ "replace_stale": differs,
60
+ "replace_no_source_high_conf": 0,
61
+ "keep": matches,
62
+ "recommendation_total": differs + stale,
63
+ "top_sources": dict(sources.most_common(5)),
64
+ "fields_with_ai_date": with_ai_date,
65
+ "fields_with_bna_review": with_bna_review,
66
+ "avg_ai_source_age_days": avg_freshness_days,
67
+ }
68
+
69
+
70
+ LABELS = {
71
+ "en": {
72
+ "total": "Total Fields", "matches": "Matches", "differs": "Differs",
73
+ "pending": "Missing on Both", "already": "Missing on AI",
74
+ "stale": "Stale AI",
75
+ "unknown": "Missing BNA value", "rate": "Match Rate (%)",
76
+ "rep_stale": "Replace-stale BNA", "rep_nosrc": "Replace-no AI date",
77
+ "rep_total": "Total Replace Recs", "keep": "Keep BNA",
78
+ "ai_dated": "Fields w AI Date", "bna_reviewed": "Fields w BNA Review",
79
+ "avg_age": "Avg AI Age (d)", "conf": "Confidence", "src": "Source",
80
+ },
81
+ "es": {
82
+ "total": "Total campos", "matches": "Coincidencias", "differs": "Diferencias",
83
+ "pending": "Falta en Ambos", "already": "Falta en IA",
84
+ "stale": "IA Antigua",
85
+ "unknown": "Sin valor BNA", "rate": "Tasa coincidencia (%)",
86
+ "rep_stale": "Reemplazar-BNA viejo", "rep_nosrc": "Reemplazar-sin fecha",
87
+ "rep_total": "Total recomendaciones", "keep": "Conservar BNA",
88
+ "ai_dated": "Campos c/fecha IA", "bna_reviewed": "Campos c/revision",
89
+ "avg_age": "Antiguedad IA (d)", "conf": "Confianza", "src": "Fuente",
90
+ },
91
+ "pt": {
92
+ "total": "Total campos", "matches": "Coincidencias", "differs": "Diferencas",
93
+ "pending": "Falta em Ambos", "already": "Falta em IA",
94
+ "stale": "IA Antiga",
95
+ "unknown": "Sem valor BNA", "rate": "Taxa coincidencia (%)",
96
+ "rep_stale": "Substituir-BNA velho", "rep_nosrc": "Substituir-sem data",
97
+ "rep_total": "Total recomendacoes", "keep": "Manter BNA",
98
+ "ai_dated": "Campos c/data IA", "bna_reviewed": "Campos c/revisao",
99
+ "avg_age": "Idade IA (d)", "conf": "Confianca", "src": "Fonte",
100
+ },
101
+ }
102
+
103
+
104
+ def to_table(metrics, lang="es"):
105
+ L = LABELS.get(lang, LABELS["es"])
106
+ rows = [
107
+ (L["total"], metrics["total_fields"]),
108
+ (L["matches"], metrics["matches"]),
109
+ (L["differs"], metrics["differs"]),
110
+ (L["pending"], metrics.get("pending_disclosure", 0)),
111
+ (L["already"], metrics.get("missing_on_ai", 0)),
112
+ (L["stale"], metrics.get("stale_ai", 0)),
113
+ (L["rate"], metrics["match_rate"]),
114
+ (L["rep_total"], metrics["recommendation_total"]),
115
+ (L["ai_dated"], metrics["fields_with_ai_date"]),
116
+ (L["avg_age"], metrics["avg_ai_source_age_days"] or "N/A"),
117
+ ]
118
+ for k, v in metrics["confidence_breakdown"].items():
119
+ rows.append((f"{L['conf']}: {k}", v))
120
+ for k, v in metrics["top_sources"].items():
121
+ rows.append((f"{L['src']}: {k}", v))
122
+ return rows
engine/rules.py ADDED
@@ -0,0 +1,1319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Per-field comparison rules per TIE Logics.docx.
3
+ Each rule returns: (transformed_value:str, bna_value_str:str, match:str, recommendation:str)
4
+ match values: "Match" | "Differ"
5
+ """
6
+ from __future__ import annotations
7
+ import re
8
+ import unicodedata
9
+ from datetime import datetime
10
+ from typing import Any, Dict, List, Optional, Tuple
11
+
12
+
13
+ def _strip_accents(s):
14
+ """Remove diacritics (accents) from a string. 'Águila' -> 'Aguila',
15
+ 'Peña' -> 'Pena'. Used by _norm_name so person/company name
16
+ comparison is accent-insensitive."""
17
+ if not s: return s
18
+ nfkd = unicodedata.normalize("NFKD", str(s))
19
+ return "".join(ch for ch in nfkd if not unicodedata.combining(ch))
20
+
21
+ LEGAL_SUFFIXES = {
22
+ "corporation", "corp", "corp.", "limited", "ltd", "ltd.",
23
+ "incorporated", "inc", "inc.", "company", "co", "co.",
24
+ "group", "holdings", "holding", "international", "intl",
25
+ "s.a.", "s.a", "sa", "ltda", "ltda.", "spa", "spa.",
26
+ "ag", "gmbh", "plc", "llc", "l.l.c", "l.l.c.",
27
+ "s.a.s", "sas", "n.v.", "nv", "lda", "lda.", "kk",
28
+ "p.c", "pty", "pte", "pvt", "ehf",
29
+ "the",
30
+ }
31
+ PUNCT_RE = re.compile(r"[.,!?;:'\"\(\)\[\]\{\}/\\]")
32
+ SPACES_RE = re.compile(r"\s+")
33
+ # Anchored: matches ONLY when the entire trimmed value is a placeholder.
34
+ # Previously this used .search() which falsely flagged long descriptive
35
+ # fields (milestones, descriptions) that happened to mention 'TBD' or
36
+ # 'not available' inside the body as blank.
37
+ NOT_DISCLOSED = re.compile(
38
+ r"^(?:not\s+(?:yet\s+|publicly\s+)?disclosed|not\s+available|n[/\.]?a|tbd|to\s+be\s+(?:determined|disclosed)|no\s+disponible|no\s+divulgado|n[ãa]o\s+dispon[íi]vel|n[ãa]o\s+divulgado|sin\s+divulgar)$",
39
+ re.IGNORECASE)
40
+
41
+
42
+ def _is_blank(v):
43
+ if v is None: return True
44
+ s = str(v).strip()
45
+ if s == "" or s.lower() in ("null", "none", "nan"): return True
46
+ if NOT_DISCLOSED.fullmatch(s): return True
47
+ return False
48
+
49
+
50
+ def _split_csv(v):
51
+ if _is_blank(v): return []
52
+ parts = re.split(r"\s*[,;|]\s*|\s*\n\s*", str(v))
53
+ return [p.strip() for p in parts if p.strip()]
54
+
55
+
56
+ def _norm_name(s):
57
+ if not s: return ""
58
+ # Accent-insensitive + case-insensitive: 'Aníbal Del Águila' and
59
+ # 'Aníbal del Aguila' both normalize to 'anibal del aguila'.
60
+ t = _strip_accents(s).lower().strip()
61
+ t = PUNCT_RE.sub(" ", t)
62
+ t = SPACES_RE.sub(" ", t)
63
+ tokens = [tok for tok in t.split(" ") if tok and tok not in LEGAL_SUFFIXES]
64
+ return " ".join(tokens).strip()
65
+
66
+
67
+ def _proper_case(s):
68
+ if not s: return ""
69
+ out = []
70
+ for word in s.split():
71
+ if word.isupper() and 2 <= len(word) <= 6:
72
+ out.append(word)
73
+ else:
74
+ out.append(word[:1].upper() + word[1:].lower() if word else word)
75
+ return " ".join(out)
76
+
77
+
78
+ # Date helpers
79
+ MONTHS_EN = ["January","February","March","April","May","June","July","August","September","October","November","December"]
80
+ MONTHS_ES = ["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"]
81
+ MONTHS_PT = ["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"]
82
+ ALL_MONTH_LOOKUP = {}
83
+ for arr in (MONTHS_EN, MONTHS_ES, MONTHS_PT):
84
+ for i, m in enumerate(arr, 1):
85
+ ALL_MONTH_LOOKUP[m.lower()] = i
86
+ # Short / abbreviated month names (English, Spanish, Portuguese)
87
+ for short, idx in {"jan":1,"feb":2,"mar":3,"apr":4,"may":5,"jun":6,"jul":7,
88
+ "aug":8,"sep":9,"sept":9,"oct":10,"nov":11,"dec":12,
89
+ "ene":1,"abr":4,"ago":8,"dic":12,
90
+ "fev":2,"abr":4,"ago":8,"set":9,"out":10,"dez":12}.items():
91
+ ALL_MONTH_LOOKUP[short] = idx
92
+
93
+
94
+ def parse_date(raw):
95
+ if raw is None or raw == "": return None
96
+ if isinstance(raw, datetime): return raw
97
+ s = str(raw).strip()
98
+ if not s: return None
99
+ s = re.sub(r"T\d{2}:\d{2}.*$", "", s)
100
+ for fmt in ("%Y-%m-%d","%Y/%m/%d","%Y.%m.%d","%d-%m-%Y","%d/%m/%Y","%d.%m.%Y","%Y-%m","%m-%Y","%m/%Y","%Y/%m"):
101
+ try: return datetime.strptime(s, fmt)
102
+ except ValueError: pass
103
+ tokens = re.findall(r"[A-Za-zÀ-ÿ]+|\d+", s)
104
+ month, year, day = None, None, 1
105
+ for t in tokens:
106
+ tl = t.lower()
107
+ if tl in ALL_MONTH_LOOKUP: month = ALL_MONTH_LOOKUP[tl]
108
+ elif t.isdigit():
109
+ n = int(t)
110
+ if len(t) == 4: year = n
111
+ elif day == 1 and 1 <= n <= 31: day = n
112
+ if month and year:
113
+ try: return datetime(year, month, day)
114
+ except ValueError: return datetime(year, month, 1)
115
+ return None
116
+
117
+
118
+ def fmt_month_year(dt, lang):
119
+ if not dt: return ""
120
+ if lang == "es": return f"{MONTHS_ES[dt.month-1]} {dt.year}"
121
+ if lang == "pt": return f"{MONTHS_PT[dt.month-1]} {dt.year}"
122
+ return f"{MONTHS_EN[dt.month-1]} {dt.year}"
123
+
124
+
125
+ # Number helpers
126
+ def parse_number(raw):
127
+ if raw is None or raw == "": return None
128
+ if isinstance(raw, (int, float)): return float(raw)
129
+ s = re.sub(r"[^\d,.\-]", "", str(raw))
130
+ if not s: return None
131
+ if "," in s and "." in s:
132
+ if s.rfind(",") > s.rfind("."):
133
+ s = s.replace(".", "").replace(",", ".")
134
+ else:
135
+ s = s.replace(",", "")
136
+ elif "," in s:
137
+ parts = s.split(",")
138
+ if len(parts) == 2 and len(parts[-1]) <= 2:
139
+ s = s.replace(",", ".")
140
+ else:
141
+ s = s.replace(",", "")
142
+ elif "." in s:
143
+ # ES/PT thousand-separator: '3.600.000' (multiple dots) or
144
+ # '1.234' followed by 3+ digits — treat dots as thousand sep.
145
+ parts = s.split(".")
146
+ if len(parts) >= 3 or (len(parts) == 2 and len(parts[-1]) == 3 and len(parts[0]) <= 3):
147
+ s = s.replace(".", "")
148
+ try: return float(s)
149
+ except ValueError: return None
150
+
151
+
152
+ # Multiplier suffixes commonly seen in capacity values, both EN and ES/PT.
153
+ _MULTIPLIERS = {
154
+ "thousand": 1_000, "thousands": 1_000,
155
+ "mil": 1_000, "miles": 1_000,
156
+ "million": 1_000_000, "millions": 1_000_000,
157
+ "millón": 1_000_000, "millon": 1_000_000,
158
+ "millones": 1_000_000, "milhão": 1_000_000,
159
+ "milhao": 1_000_000, "milhões": 1_000_000, "milhoes": 1_000_000,
160
+ "billion": 1_000_000_000, "billions": 1_000_000_000,
161
+ "mil millones": 1_000_000_000, "bilhão": 1_000_000_000, "bilhao": 1_000_000_000,
162
+ }
163
+
164
+
165
+ def _extract_multiplier(text):
166
+ """Return (multiplier, remaining_text). Default multiplier 1."""
167
+ if not text: return 1, ""
168
+ t = str(text).strip()
169
+ low = t.lower()
170
+ # Match longest first
171
+ for word in sorted(_MULTIPLIERS, key=len, reverse=True):
172
+ pat = re.compile(rf"\b{re.escape(word)}\b", re.IGNORECASE)
173
+ m = pat.search(low)
174
+ if m:
175
+ stripped = (t[:m.start()] + " " + t[m.end():]).strip()
176
+ stripped = re.sub(r"\s+", " ", stripped)
177
+ return _MULTIPLIERS[word], stripped
178
+ return 1, t
179
+
180
+
181
+ def fmt_capex(value, lang):
182
+ if value is None: return ""
183
+ decimals = 1 if value <= 99 else 0
184
+ s = f"{value:,.{decimals}f}" if decimals else f"{value:,.0f}"
185
+ if lang in ("es", "pt"):
186
+ s = s.replace(",", "§").replace(".", ",").replace("§", ".")
187
+ return s + " USD"
188
+
189
+
190
+ def normalize_capacity_number(raw):
191
+ n = parse_number(raw)
192
+ if n is None: return None
193
+ if abs(n - round(n)) < 1e-9:
194
+ return float(int(round(n)))
195
+ return n
196
+
197
+
198
+ def extract_numbers(text):
199
+ if not text: return []
200
+ nums = re.findall(r"\d+(?:[.,]\d+)?", text)
201
+ out = []
202
+ for n in nums:
203
+ v = parse_number(n)
204
+ if v is not None: out.append(v)
205
+ return out
206
+
207
+
208
+ def _meaningful_diff(ai_text, bna_text, min_overlap=0.6):
209
+ if _is_blank(ai_text): return False
210
+ if _is_blank(bna_text): return True
211
+ a = set(re.findall(r"[A-Za-zÀ-ÿ0-9]+", ai_text.lower()))
212
+ b = set(re.findall(r"[A-Za-zÀ-ÿ0-9]+", bna_text.lower()))
213
+ if not a: return False
214
+ return (len(a & b) / len(a)) < min_overlap
215
+
216
+
217
+ def parse_latlon(raw):
218
+ if _is_blank(raw): return None
219
+ m = re.findall(r"([+-]?\d+\.?\d*)\s*°?\s*([NSEW])?", str(raw), re.IGNORECASE)
220
+ if not m: return None
221
+ coords = []
222
+ for num, dirc in m[:4]:
223
+ try: v = float(num)
224
+ except ValueError: continue
225
+ if dirc and dirc.upper() in ("S","W"): v = -abs(v)
226
+ elif dirc and dirc.upper() in ("N","E"): v = abs(v)
227
+ coords.append(v)
228
+ return (coords[0], coords[1]) if len(coords) >= 2 else None
229
+
230
+
231
+ def reco_text(label, ai_orig, transformed, bna_value, lang="en"):
232
+ """Localised recommendation text. Each rule now passes the output
233
+ language through (or defaults to 'en')."""
234
+ try:
235
+ import i18n as _i18n
236
+ tpl = _i18n.RECO_TEMPLATE.get(lang, _i18n.RECO_TEMPLATE["en"])
237
+ na = _i18n.NOT_AVAILABLE_LABEL.get(lang, "Not Available")
238
+ # Translate the field-name label too (e.g. 'Capex' is shared,
239
+ # but 'Project Name' becomes 'Nombre del Proyecto' in ES).
240
+ try:
241
+ label_tr = _i18n.FIELD_NAME_I18N.get(str(label).strip().lower(), {}).get(lang, label)
242
+ except Exception:
243
+ label_tr = label
244
+ except Exception:
245
+ tpl = "{label} differs. Agentic AI value: {ai}. BNA Platform value: {bna}."
246
+ na = "Not Available"
247
+ label_tr = label
248
+ bna = bna_value if bna_value else na
249
+ ai_orig = ai_orig if ai_orig else ""
250
+ ai_disp = f"{ai_orig}/{transformed}" if transformed and transformed != ai_orig else ai_orig
251
+ return tpl.format(label=label_tr, ai=ai_disp, bna=bna)
252
+
253
+
254
+ def reco_missing(extra, lang="en"):
255
+ try:
256
+ import i18n as _i18n
257
+ tpl = _i18n.RECO_MISSING_TEMPLATE.get(lang, _i18n.RECO_MISSING_TEMPLATE["en"])
258
+ except Exception:
259
+ tpl = "Missing information identified from Agentic AI output: {extra}"
260
+ return tpl.format(extra=extra).strip()
261
+
262
+
263
+ def _val(bd):
264
+ if bd is None: return ""
265
+ if isinstance(bd, dict): return str(bd.get("value", "") or "")
266
+ if isinstance(bd, list): return ", ".join(str(x) for x in bd)
267
+ return str(bd)
268
+
269
+
270
+ # ---- Rules ----
271
+ def rule_project_name(ai, x, b, tie, lang):
272
+ if _is_blank(ai): return "", _val(b), "Match", ""
273
+ a = str(ai).strip(); bn = _val(b)
274
+ if not bn: return a, "", "Differ", reco_text("Project Name", a, a, "")
275
+ if _norm_name(a) == _norm_name(bn): return a, bn, "Match", ""
276
+ return a, bn, "Differ", reco_text("Project Name", a, a, bn)
277
+
278
+
279
+ def _company_match(ai_norm, bna_norms):
280
+ """Check whether the normalised AI company name matches any of the
281
+ normalised BNA company names. Order of fallbacks:
282
+ 1. Exact equality after legal-suffix stripping.
283
+ 2. Substring containment (one fully inside the other) for names
284
+ with at least 4 characters of meat — handles 'Equinox Gold'
285
+ vs 'Equinox Gold Mining'.
286
+ 3. Token-set overlap of >= 60% with at least 2 shared tokens —
287
+ handles minor word reorderings or extra branding tokens.
288
+ """
289
+ if not ai_norm: return False
290
+ ai_tokens = set(t for t in ai_norm.split() if len(t) >= 2)
291
+ for bn in bna_norms:
292
+ if not bn: continue
293
+ if ai_norm == bn: return True
294
+ if len(ai_norm) >= 4 and (ai_norm in bn or bn in ai_norm):
295
+ return True
296
+ bn_tokens = set(t for t in bn.split() if len(t) >= 2)
297
+ if len(ai_tokens) >= 2 and len(bn_tokens) >= 2:
298
+ shared = ai_tokens & bn_tokens
299
+ denom = min(len(ai_tokens), len(bn_tokens))
300
+ if denom and len(shared) / denom >= 0.6 and len(shared) >= 2:
301
+ return True
302
+ return False
303
+
304
+
305
+ def _company_role(label, ai, b):
306
+ """Many-to-many comparison.
307
+ - AI value is comma-split into individual company names.
308
+ - BNA value is a list of company names harvested chip-by-chip.
309
+ - For every AI company, check whether ANY BNA company matches
310
+ (using _company_match: norm-equal, substring, or token overlap).
311
+ - AI items that match a BNA item are 'already in BNA' — ignore.
312
+ - AI items WITHOUT a match are flagged as missing.
313
+ - Field-level result: Match if every AI item has a match; otherwise
314
+ Differ, with the missing AI items shown in the recommendation.
315
+ """
316
+ bna_names = b if isinstance(b, list) else _split_csv(_val(b))
317
+ if _is_blank(ai): return "", ", ".join(bna_names), "Match", ""
318
+ ai_names = _split_csv(ai)
319
+ transformed_list = [_proper_case(n) for n in ai_names]
320
+ transformed = ", ".join(transformed_list)
321
+ bna_str = ", ".join(bna_names)
322
+ if not bna_names:
323
+ return transformed, "", "Differ", reco_text(label, str(ai), transformed, "")
324
+ bna_norms = [_norm_name(b2) for b2 in bna_names]
325
+ unmatched = [t for t in transformed_list
326
+ if not _company_match(_norm_name(t), bna_norms)]
327
+ if not unmatched:
328
+ return transformed, bna_str, "Match", ""
329
+ return transformed, bna_str, "Differ", reco_text(label, str(ai), ", ".join(unmatched), bna_str)
330
+
331
+
332
+ def rule_owner(ai, x, b, tie, lang): return _company_role("Owner", ai, b)
333
+ def rule_concession(ai, x, b, tie, lang): return _company_role("Concessionaire/Operator", ai, b)
334
+ def rule_contractor(ai, x, b, tie, lang): return _company_role("Contractor", ai, b)
335
+ def rule_engineering_co(ai, x, b, tie, lang): return _company_role("Engineering Company", ai, b)
336
+ def rule_equipment_co(ai, x, b, tie, lang): return _company_role("Equipment / Technology Provider", ai, b)
337
+ def rule_consultancy_co(ai, x, b, tie, lang): return _company_role("Consultancy Company", ai, b)
338
+
339
+
340
+ def _canonical_stage_en(token, tie):
341
+ """Resolve a project stage token (in any language) to its canonical
342
+ English form. Tries TIE Stage Mapping first, then walks the Current
343
+ Stage sheet (which has substage_en / substage_es / substage_pt
344
+ columns), then the Project Stage Translations table. Falls back to
345
+ the input."""
346
+ if not token or tie is None: return token
347
+ t = _strip_accents(str(token)).strip().lower()
348
+ if not t: return token
349
+ # 1) Stage Mapping (External Term -> BNA Stage)
350
+ try:
351
+ mapped = tie.lookup_mapping(tie.stage_mapping, token)
352
+ if mapped: return mapped
353
+ except Exception:
354
+ pass
355
+ # 2) Current Stage sheet (substage code + en/es/pt)
356
+ try:
357
+ for row in getattr(tie, "current_stages", []) or []:
358
+ for fld in ("substage", "en", "es", "pt"):
359
+ v = (row.get(fld) or "").strip()
360
+ if v and _strip_accents(v).lower() == t:
361
+ return row.get("en") or v
362
+ except Exception:
363
+ pass
364
+ # 3) Project Stage Translations (en -> {es, pt})
365
+ try:
366
+ table = (getattr(tie, "bna_translations", {}) or {}).get("project_stage", {})
367
+ for en_key, langs in table.items():
368
+ if _strip_accents(en_key).lower() == t: return en_key
369
+ es = (langs.get("es") or "")
370
+ pt = (langs.get("pt") or "")
371
+ if _strip_accents(es).lower() == t or _strip_accents(pt).lower() == t:
372
+ return en_key
373
+ except Exception:
374
+ pass
375
+ return token
376
+
377
+
378
+ def _display_stage(canonical_en, tie, lang):
379
+ """Translate a canonical English stage to display language. Looks up
380
+ Current Stage sheet first (more authoritative), then Project Stage
381
+ Translations. Falls back to the canonical EN."""
382
+ if not canonical_en or lang not in ("es", "pt") or tie is None:
383
+ return canonical_en
384
+ key = _strip_accents(str(canonical_en)).strip().lower()
385
+ try:
386
+ for row in getattr(tie, "current_stages", []) or []:
387
+ en = (row.get("en") or "")
388
+ if en and _strip_accents(en).lower() == key:
389
+ v = (row.get(lang) or "").strip()
390
+ if v: return v
391
+ except Exception:
392
+ pass
393
+ try:
394
+ table = (getattr(tie, "bna_translations", {}) or {}).get("project_stage", {})
395
+ entry = table.get(canonical_en.strip().lower())
396
+ if entry:
397
+ v = entry.get(lang)
398
+ if v: return v
399
+ except Exception:
400
+ pass
401
+ return canonical_en
402
+
403
+
404
+ def _is_known_stage(token, tie):
405
+ """Returns True if the token (in any language) resolves to a known
406
+ Stage Mapping / Current Stage / Project Stage Translations entry —
407
+ i.e. it's a stage name in its own right (so comma-split would be wrong)."""
408
+ if not token or tie is None: return False
409
+ t = _strip_accents(str(token)).strip().lower()
410
+ if not t: return False
411
+ try:
412
+ if tie.lookup_mapping(tie.stage_mapping, token): return True
413
+ except Exception: pass
414
+ try:
415
+ for row in getattr(tie, "current_stages", []) or []:
416
+ for fld in ("substage", "en", "es", "pt"):
417
+ v = (row.get(fld) or "").strip()
418
+ if v and _strip_accents(v).lower() == t: return True
419
+ except Exception: pass
420
+ try:
421
+ table = (getattr(tie, "bna_translations", {}) or {}).get("project_stage", {})
422
+ for en_key, langs in table.items():
423
+ if _strip_accents(en_key).lower() == t: return True
424
+ es = (langs.get("es") or ""); pt = (langs.get("pt") or "")
425
+ if _strip_accents(es).lower() == t or _strip_accents(pt).lower() == t:
426
+ return True
427
+ except Exception: pass
428
+ return False
429
+
430
+
431
+ def _known_stage_labels(tie):
432
+ """Return a list of (display_label, canonical_en) for every known
433
+ stage in any language. Sorted longest-first so 'Design, Feasibility
434
+ and Basic Engineering' matches before 'Design'."""
435
+ out = []
436
+ try:
437
+ for row in getattr(tie, "current_stages", []) or []:
438
+ canon_en = (row.get("en") or "").strip()
439
+ if not canon_en: continue
440
+ for fld in ("en", "es", "pt", "substage"):
441
+ v = (row.get(fld) or "").strip()
442
+ if v: out.append((v, canon_en))
443
+ except Exception: pass
444
+ try:
445
+ table = (getattr(tie, "bna_translations", {}) or {}).get("project_stage", {})
446
+ for en_key, langs in table.items():
447
+ out.append((en_key, en_key))
448
+ for fld in ("es", "pt"):
449
+ v = (langs.get(fld) or "").strip()
450
+ if v: out.append((v, en_key))
451
+ except Exception: pass
452
+ try:
453
+ for ext, bna in (getattr(tie, "stage_mapping", {}) or {}).items():
454
+ if ext and bna: out.append((ext, bna))
455
+ except Exception: pass
456
+ # Dedupe preserving first occurrence, longest-first
457
+ seen = set(); deduped = []
458
+ for label, en in sorted(out, key=lambda x: -len(x[0])):
459
+ k = _strip_accents(label).strip().lower()
460
+ if not k or k in seen: continue
461
+ seen.add(k); deduped.append((label, en))
462
+ return deduped
463
+
464
+
465
+ def _scan_stages_in_string(s, tie):
466
+ """Scan input string for known stage names (in any language). Returns
467
+ a list of canonical EN stages in order of first occurrence. Handles
468
+ the case where a stage name contains commas internally, e.g.
469
+ 'Design, Feasibility and Basic Engineering'."""
470
+ if not s or not tie: return []
471
+ haystack = _strip_accents(str(s)).lower()
472
+ labels = _known_stage_labels(tie)
473
+ found = []
474
+ seen_positions = set()
475
+ for label, canonical_en in labels:
476
+ needle = _strip_accents(label).lower()
477
+ if not needle: continue
478
+ start = 0
479
+ while True:
480
+ idx = haystack.find(needle, start)
481
+ if idx == -1: break
482
+ # Must be on a word boundary (or punctuation)
483
+ left_ok = idx == 0 or not haystack[idx-1].isalnum()
484
+ end = idx + len(needle)
485
+ right_ok = end == len(haystack) or not haystack[end].isalnum()
486
+ if left_ok and right_ok:
487
+ # Avoid double-counting overlapping matches
488
+ overlap = any(a <= idx < b for a, b in seen_positions)
489
+ if not overlap:
490
+ seen_positions.add((idx, end))
491
+ found.append((idx, canonical_en))
492
+ start = idx + 1
493
+ found.sort(key=lambda x: x[0])
494
+ # Dedup canonical names while preserving order
495
+ seen_canon = set(); out = []
496
+ for _, c in found:
497
+ kc = _strip_accents(c).lower()
498
+ if kc in seen_canon: continue
499
+ seen_canon.add(kc); out.append(c)
500
+ return out
501
+
502
+
503
+ def _split_stages(s, tie):
504
+ """Split a stage string into individual stages. Some BNA stages
505
+ legitimately contain commas (e.g. 'Design, Feasibility and Basic
506
+ Engineering'). Strategy: split first on semicolon / pipe / newline
507
+ (these are unambiguous). Only fall back to comma-split when the
508
+ whole string does NOT resolve to a known stage."""
509
+ if not s: return []
510
+ raw = str(s).strip()
511
+ if not raw: return []
512
+ # Pass 1: semicolon / pipe / newline split — never ambiguous
513
+ parts = re.split(r"\s*[;|]\s*|\n+", raw)
514
+ parts = [p.strip() for p in parts if p.strip()]
515
+ # Pass 2: comma split each part only if the part is NOT a known stage
516
+ out = []
517
+ for p in parts:
518
+ if "," in p and not _is_known_stage(p, tie):
519
+ sub = [s2.strip() for s2 in p.split(",") if s2.strip()]
520
+ # Only accept comma split if every sub-part is a known stage
521
+ if sub and all(_is_known_stage(s2, tie) for s2 in sub):
522
+ out.extend(sub)
523
+ else:
524
+ out.append(p)
525
+ else:
526
+ out.append(p)
527
+ return out
528
+
529
+
530
+ def rule_project_stage(ai, x, b, tie, lang):
531
+ """Project Stage comparison — multi-value + language-agnostic.
532
+ Both AI and BNA values are split via _split_stages (which respects
533
+ commas inside known canonical stage names). Each token is mapped
534
+ to canonical English form so PT/ES/EN compare correctly.
535
+ Match if every AI stage appears in BNA stages (set containment)."""
536
+ if _is_blank(ai): return "", _val(b), "Match", ""
537
+ a = str(ai).strip()
538
+ # Try the scan-known-stages path first — it handles stage names that
539
+ # legitimately contain commas (e.g. 'Design, Feasibility and Basic
540
+ # Engineering'). Fall back to delimiter splitting if nothing matches.
541
+ ai_canonical_en = _scan_stages_in_string(a, tie)
542
+ if not ai_canonical_en:
543
+ ai_items = _split_stages(a, tie)
544
+ ai_canonical_en = [_canonical_stage_en(t, tie) for t in ai_items]
545
+ transformed_items = [_display_stage(t, tie, lang) for t in ai_canonical_en]
546
+ transformed = ", ".join(transformed_items)
547
+ bn = _val(b)
548
+ if not bn:
549
+ return transformed, "", "Differ", reco_text("Project Stage", a, transformed, "")
550
+ bna_canonical_en = _scan_stages_in_string(bn, tie)
551
+ if not bna_canonical_en:
552
+ bna_items = _split_stages(bn, tie)
553
+ bna_canonical_en = [_canonical_stage_en(t, tie) for t in bna_items]
554
+ # Set-based comparison (accent + case insensitive)
555
+ def _key(s): return _strip_accents(str(s or "")).strip().lower()
556
+ ai_set = {_key(t) for t in ai_canonical_en}
557
+ bna_set = {_key(t) for t in bna_canonical_en}
558
+ if ai_set and ai_set.issubset(bna_set):
559
+ return transformed, bn, "Match", ""
560
+ # Substring containment fallback — if every AI stage label appears
561
+ # as a substring of SOME BNA stage label (case + accent insensitive),
562
+ # treat as Match. Handles cases like AI 'Factibilidad' subset of BNA
563
+ # 'Diseño, factibilidad e ingeniería básica' or AI 'Feasibility'
564
+ # subset of BNA 'Design, Feasibility and Basic Engineering'. Also
565
+ # scans against the RAW BNA string so even when scan-known-stages
566
+ # didn't pick up the BNA stage, a textual hit still counts.
567
+ if ai_set:
568
+ raw_b = _key(bn)
569
+ # Build a flat "haystack" out of every canonical BNA token plus
570
+ # the raw BNA text. Any AI token that appears in this haystack
571
+ # is considered present in BNA.
572
+ haystack_parts = list(bna_set) + [raw_b]
573
+ all_in = True
574
+ for ai_tok in ai_set:
575
+ if not ai_tok:
576
+ continue
577
+ hit = any(ai_tok and (ai_tok in h or h in ai_tok) for h in haystack_parts if h)
578
+ if not hit:
579
+ all_in = False
580
+ break
581
+ if all_in:
582
+ return transformed, bn, "Match", ""
583
+ # Last-ditch whole-string equality (case + accent insensitive)
584
+ if _key(a) == _key(bn):
585
+ return transformed, bn, "Match", ""
586
+ return transformed, bn, "Differ", reco_text("Project Stage", a, transformed, bn)
587
+
588
+
589
+ def rule_project_description(ai, x, b, tie, lang):
590
+ a = "" if _is_blank(ai) else str(ai).strip()
591
+ bn = _val(b)
592
+ if not a: return "", bn, "Match", ""
593
+ if not bn: return a, "", "Differ", reco_missing(a)
594
+ if _meaningful_diff(a, bn):
595
+ ai_sents = re.split(r"(?<=[\.\!\?])\s+", a)
596
+ bna_low = bn.lower()
597
+ new_bits = [s.strip() for s in ai_sents
598
+ if s.strip() and not all(tok in bna_low for tok in re.findall(r"[a-z]+", s.lower())[:3])]
599
+ extra = " ".join(new_bits) or a
600
+ return a, bn, "Differ", reco_missing(extra)
601
+ return a, bn, "Match", ""
602
+
603
+
604
+ def _strip_paren(s):
605
+ """Drop trailing parenthetical qualifiers like 'Public (PPP/PFI)' -> 'Public'."""
606
+ if s is None: return ""
607
+ return re.sub(r"\s*\([^)]*\)\s*", " ", str(s)).strip()
608
+
609
+
610
+ def rule_property_type(ai, x, b, tie, lang):
611
+ if _is_blank(ai): return "", _val(b), "Match", ""
612
+ a = str(ai).strip()
613
+ transformed = (tie.lookup_mapping(tie.ownership_type_mapping, a) or a) if tie else a
614
+ bn = _val(b)
615
+ if not bn: return transformed, "", "Differ", reco_text("Property Type", a, transformed, "")
616
+ if transformed.strip().lower() == bn.strip().lower():
617
+ return transformed, bn, "Match", ""
618
+ # Tolerate parenthetical qualifiers on either side:
619
+ # 'Public' ↔ 'Public (PPP/PFI)' should be a Match.
620
+ if _strip_paren(transformed).lower() == _strip_paren(bn).lower():
621
+ return transformed, bn, "Match", ""
622
+ return transformed, bn, "Differ", reco_text("Property Type", a, transformed, bn)
623
+
624
+
625
+ def rule_development_type(ai, x, b, tie, lang):
626
+ if _is_blank(ai): return "", _val(b), "Match", ""
627
+ a = str(ai).strip()
628
+ transformed = (tie.lookup_mapping(tie.development_type_mapping, a) or a) if tie else a
629
+ bn = _val(b)
630
+ if not bn: return transformed, "", "Differ", reco_text("Development Type", a, transformed, "")
631
+ if transformed.strip().lower() == bn.strip().lower():
632
+ return transformed, bn, "Match", ""
633
+ return transformed, bn, "Differ", reco_text("Development Type", a, transformed, bn)
634
+
635
+
636
+ def rule_capex(ai, ai_date, b, tie, lang, bna_fields=None):
637
+ """Capex comparison per TIE Logics:
638
+ 1. Convert AI value to USD millions using FX rate at the source
639
+ publication date (or BNA Last Expert Review if missing).
640
+ 2. Round, format per language, then compare to BNA value.
641
+ 3. If both are blank -> Match (no recommendation).
642
+ 4. If BNA is blank but AI has a value -> Differ + add to recommendation.
643
+ 5. If values differ numerically -> Differ + recommendation showing the
644
+ transformed USD value.
645
+ """
646
+ import currency as _cur
647
+
648
+ bn = _val(b)
649
+
650
+ # Both blank -> nothing to compare
651
+ if _is_blank(ai) and _is_blank(bn):
652
+ return "", "", "Match", ""
653
+
654
+ # AI blank, BNA has a value -> match (no AI claim to validate)
655
+ if _is_blank(ai):
656
+ return "", bn, "Match", ""
657
+
658
+ # Parse AI Capex value (currency + amount + unit)
659
+ parsed = _cur.parse_capex_value(ai)
660
+ if parsed is None:
661
+ return str(ai), bn, "Differ", reco_text("Capex", str(ai), "", bn)
662
+
663
+ # FX dates: AI uses its OWN source date; BNA uses Last Expert Review.
664
+ # Each side is converted at the rate that was current on its date.
665
+ ai_fx_date = ai_date if ai_date else None
666
+ bna_fx_date = None
667
+ if bna_fields:
668
+ for k, v in bna_fields.items():
669
+ if str(k).strip().lower() == "last expert review":
670
+ bna_fx_date = v; break
671
+ # Last-resort fallback if a side has no own date
672
+ if not ai_fx_date: ai_fx_date = bna_fx_date
673
+ if not bna_fx_date: bna_fx_date = ai_fx_date
674
+
675
+ usd_mn, rate, src = _cur.to_usd_millions(parsed, ai_fx_date, tie)
676
+ if usd_mn is None:
677
+ # Conversion failed — fall back to raw amount as USD
678
+ usd_mn = parsed["raw_units"] / 1_000_000.0
679
+
680
+ transformed = _cur.fmt_usd_millions(usd_mn, lang)
681
+
682
+ # BNA missing -> recommend adding the AI value
683
+ if not bn:
684
+ return transformed, "", "Differ", reco_text("Capex", str(ai), transformed, "Not Available")
685
+
686
+ # Convert BNA value to USD millions using the BNA review date.
687
+ bna_parsed = _cur.parse_capex_value(bn)
688
+ bna_usd_mn = None
689
+ if bna_parsed:
690
+ bna_usd_mn, _, _ = _cur.to_usd_millions(bna_parsed, bna_fx_date, tie)
691
+ if bna_usd_mn is None and bna_parsed["currency"] == "USD":
692
+ bna_usd_mn = bna_parsed["raw_units"] / 1_000_000.0
693
+ bn_display = _cur.fmt_usd_millions(bna_usd_mn, lang) if bna_usd_mn is not None else bn
694
+
695
+ # Compare numerically.
696
+ bn_n = bna_usd_mn if bna_usd_mn is not None else parse_number(bn)
697
+ if bn_n is not None:
698
+ # Tolerate small rounding noise: 1 mn absolute OR 1% relative.
699
+ diff = abs(bn_n - usd_mn)
700
+ denom = max(1.0, abs(usd_mn), abs(bn_n))
701
+ if diff < 1.0 or (diff / denom) < 0.01:
702
+ return transformed, bn_display, "Match", ""
703
+ return transformed, bn_display, "Differ", reco_text("Capex", str(ai), transformed, bn_display)
704
+
705
+
706
+ def rule_lifespan(ai, x, b, tie, lang):
707
+ """Lifespan compare: extract the numeric value from each side, round to a
708
+ whole number, and compare. Symbols like '+', '~', 'approx', 'around', and
709
+ the unit word (years / year / años / año / anos / ano) are ignored. The
710
+ unit word is compared case-insensitively. If both AI and BNA round to the
711
+ same whole-number, return Match."""
712
+ if _is_blank(ai) and _is_blank(b):
713
+ return "", "", "Match", ""
714
+ bn = _val(b)
715
+ if _is_blank(ai):
716
+ return "", bn, "Match", ""
717
+
718
+ a = str(ai).strip()
719
+ if not bn:
720
+ # Format AI as 'N years' for the recommendation
721
+ n = _lifespan_to_int(a)
722
+ transformed = _fmt_lifespan(n, lang) if n is not None else a
723
+ return transformed, "", "Differ", reco_text("Lifespan", a, transformed, "")
724
+
725
+ a_int = _lifespan_to_int(a)
726
+ b_int = _lifespan_to_int(bn)
727
+ transformed = _fmt_lifespan(a_int, lang) if a_int is not None else a
728
+
729
+ if a_int is not None and b_int is not None and a_int == b_int:
730
+ return transformed, bn, "Match", ""
731
+ return transformed, bn, "Differ", reco_text("Lifespan", a, transformed, bn)
732
+
733
+
734
+ def _lifespan_to_int(raw):
735
+ """Extract the first numeric value from a lifespan string and round to
736
+ whole years. Returns None if no number found.
737
+ Strips '+', '~', 'approx', 'around', and trailing 'years/años/anos'."""
738
+ if raw is None: return None
739
+ s = str(raw).strip()
740
+ if not s: return None
741
+ # Drop common qualifying words (case-insensitive)
742
+ s = re.sub(r"(?i)\b(?:approx(?:imately)?|around|about|over|more\s+than|m[áa]s\s+de|cerca\s+de)\b", " ", s)
743
+ # Drop signs and ranges: '+', '~', '>', '>=', etc.
744
+ s = re.sub(r"[+~>]", " ", s)
745
+ # If a range like "25-30", take the first number
746
+ m = re.search(r"-?\d+(?:[.,]\d+)?", s)
747
+ if not m: return None
748
+ raw_num = m.group(0).replace(",", ".")
749
+ try:
750
+ n = float(raw_num)
751
+ except ValueError:
752
+ return None
753
+ return int(round(n))
754
+
755
+
756
+ def _fmt_lifespan(n, lang):
757
+ if n is None: return ""
758
+ word = {"es": "años", "pt": "anos", "en": "years"}.get(lang, "years")
759
+ # Singular form for 1
760
+ if n == 1:
761
+ word = {"es": "año", "pt": "ano", "en": "year"}.get(lang, "year")
762
+ return f"{n} {word}"
763
+
764
+
765
+ def _strip_hierarchy(token):
766
+ """AI sometimes emits 'Sector > Type | Sector > Type'. Keep only the
767
+ leaf token after the last '>' so the TIE mapping matches the type
768
+ label, not the hierarchical path."""
769
+ s = str(token or "").strip()
770
+ if ">" in s:
771
+ s = s.rsplit(">", 1)[-1].strip()
772
+ return s
773
+
774
+
775
+ def _norm_pt_key(s):
776
+ """Normalise a Project Type key for translation lookup. Lower-case,
777
+ collapse whitespace, AND treat ' - ' / ' / ' / '-' / '/' as the same
778
+ separator so 'Road paving - rehabilitation' matches the TIE entry
779
+ 'Road paving / rehabilitation'."""
780
+ if s is None: return ""
781
+ out = re.sub(r"\s+", " ", str(s)).strip().lower()
782
+ # Unify separator: turn '-' or '/' (with surrounding spaces) into ' / '
783
+ out = re.sub(r"\s*[-/]\s*", " / ", out)
784
+ return out
785
+
786
+
787
+ def _translate_pt_via_tie(canonical_en, tie, lang):
788
+ """Translate a canonical EN project type to lang (es/pt) using
789
+ tie.bna_translations['project_type']. Falls back to canonical.
790
+ Lookup is dash/slash-insensitive, so a researcher who wrote
791
+ 'Road paving / rehabilitation' will match BNA's 'Road paving -
792
+ rehabilitation' display."""
793
+ if not canonical_en or lang not in ("es", "pt") or tie is None:
794
+ return canonical_en
795
+ try:
796
+ table = (getattr(tie, "bna_translations", {}) or {}).get("project_type", {})
797
+ if not table:
798
+ return canonical_en
799
+ key = canonical_en.strip().lower()
800
+ entry = table.get(key)
801
+ if not entry:
802
+ for en_key, langs in table.items():
803
+ if (langs.get("es") or "").lower() == key or (langs.get("pt") or "").lower() == key:
804
+ entry = langs
805
+ break
806
+ if entry:
807
+ tr = entry.get(lang)
808
+ if tr: return tr
809
+ except Exception:
810
+ pass
811
+ return canonical_en
812
+
813
+
814
+ def rule_project_type(ai, x, b, tie, lang):
815
+ """Many-to-many Project Type comparison.
816
+ AI value is split on comma/semicolon/pipe into individual project types.
817
+ Each token's hierarchical prefix ('Sector > ') is stripped, then mapped
818
+ to canonical English via TIE 'Project Type' sheet, then translated to
819
+ the selected display language via 'Project Type Translations'.
820
+
821
+ Matching always uses the canonical English form so a PT/ES display
822
+ language doesn't break comparison against the BNA value (also normalized).
823
+ """
824
+ if _is_blank(ai): return "", _val(b), "Match", ""
825
+ # Always split on , ; | regardless of which is present
826
+ items = _split_csv(ai) if any(c in str(ai) for c in ",;|") else [str(ai)]
827
+ # Strip 'Sector > ' prefix per token
828
+ leaf_items = [_strip_hierarchy(t) for t in items]
829
+ # Map each leaf to canonical English (TIE Project Type sheet)
830
+ canonical_en_items = [(tie.lookup_mapping(tie.project_type_mapping, t) or t) if tie else t
831
+ for t in leaf_items]
832
+ # Translate each canonical to display language
833
+ transformed_items = [_translate_pt_via_tie(t, tie, lang) for t in canonical_en_items]
834
+ transformed = ", ".join(transformed_items)
835
+ bn = _val(b)
836
+ if not bn:
837
+ return transformed, "", "Differ", reco_text("Project Type", str(ai), transformed, "")
838
+ bna_items = _split_csv(bn)
839
+ # Normalize each BNA item: strip hierarchy, reverse-translate ES/PT
840
+ # back to canonical English so the comparison is language-agnostic.
841
+ bna_canonical_en = []
842
+ for bx in bna_items:
843
+ leaf = _strip_hierarchy(bx)
844
+ # Reverse lookup via translation table (if value is ES/PT)
845
+ rev_en = _translate_pt_via_tie(leaf, tie, "en") if False else None
846
+ # Use the existing project_type_mapping; if not mapped, the value
847
+ # itself may already be canonical. The reverse-lookup inside
848
+ # _translate_pt_via_tie sets canonical_en when input matches an
849
+ # ES/PT cell — re-run with explicit reverse via the table.
850
+ canonical = leaf
851
+ try:
852
+ table = (getattr(tie, "bna_translations", {}) or {}).get("project_type", {})
853
+ key = leaf.strip().lower()
854
+ if key not in table:
855
+ for en_key, langs in table.items():
856
+ if (langs.get("es") or "").lower() == key or (langs.get("pt") or "").lower() == key:
857
+ canonical = en_key
858
+ break
859
+ except Exception:
860
+ pass
861
+ # Also try TIE Project Type external-term mapping
862
+ mapped = tie.lookup_mapping(tie.project_type_mapping, canonical) if tie else None
863
+ bna_canonical_en.append(mapped or canonical)
864
+
865
+ def _depluralise(tok):
866
+ # crude EN singularisation — drop trailing 's' / 'es' on tokens
867
+ # >=4 chars so "Runways" matches "Runway", "Terminals" matches
868
+ # "Terminal", "Concessions" matches "Concession".
869
+ if len(tok) >= 4 and tok.endswith("es") and tok[-3] not in "aeiou":
870
+ return tok[:-2]
871
+ if len(tok) >= 4 and tok.endswith("s"):
872
+ return tok[:-1]
873
+ return tok
874
+
875
+ def _norm_pt(s):
876
+ # lowercase, strip leading 'Main ', collapse whitespace, drop trailing
877
+ # punctuation. Plural-insensitive token form for comparison.
878
+ s = re.sub(r"^\s*main\s+", "", str(s or "").strip(), flags=re.IGNORECASE)
879
+ s = _strip_accents(s) if "_strip_accents" in globals() else s
880
+ s = re.sub(r"\s+", " ", s).strip().lower()
881
+ # Tokenise and depluralise each token, then rejoin
882
+ toks = [_depluralise(t) for t in s.split() if t]
883
+ return " ".join(toks)
884
+
885
+ # Compare on canonical-English forms so display language doesn't break match
886
+ bna_norm = [_norm_pt(bx) for bx in bna_canonical_en]
887
+
888
+ def _matches_any(ai_item):
889
+ a = _norm_pt(ai_item)
890
+ if not a: return True # blank AI item — nothing to validate
891
+ for bn_n in bna_norm:
892
+ if not bn_n: continue
893
+ if a == bn_n: return True
894
+ if len(a) >= 4 and (a in bn_n or bn_n in a):
895
+ return True
896
+ # Token overlap — already plural-insensitive (see _norm_pt)
897
+ atok = set(t for t in a.split() if len(t) >= 2)
898
+ btok = set(t for t in bn_n.split() if len(t) >= 2)
899
+ if len(atok) >= 1 and len(btok) >= 1:
900
+ shared = atok & btok
901
+ denom = min(len(atok), len(btok))
902
+ # 0.5 ratio is enough — "passenger terminal" (2) vs
903
+ # "airport passenger terminal" (3) shares 2/2 after
904
+ # depluralisation, so this Matches.
905
+ if denom and len(shared) / denom >= 0.5 and len(shared) >= 1:
906
+ return True
907
+ return False
908
+
909
+ # Translate BNA tokens to the target display language so the
910
+ # output sheet shows them in ES/PT alongside the AI transformed value.
911
+ bna_display_items = [_translate_pt_via_tie(t, tie, lang) for t in bna_canonical_en]
912
+ bna_display = ", ".join(bna_display_items) if bna_display_items else bn
913
+ unmatched_en = [t for t in canonical_en_items if not _matches_any(t)]
914
+ if not unmatched_en:
915
+ return transformed, bna_display, "Match", ""
916
+ unmatched_display = [_translate_pt_via_tie(t, tie, lang) for t in unmatched_en]
917
+ return transformed, bna_display, "Differ", reco_text("Project Type", str(ai), ", ".join(unmatched_display), bna_display)
918
+
919
+
920
+ def rule_milestones(ai, x, b, tie, lang):
921
+ if _is_blank(ai): return "", _val(b), "Match", ""
922
+ a = str(ai).strip(); bn = _val(b)
923
+ items = [s.strip() for s in re.split(r"\n|;", bn) if s.strip()]
924
+ latest = items[-1] if items else ""
925
+ if not latest: return a, "", "Differ", reco_missing(a)
926
+ if _meaningful_diff(a, latest): return a, latest, "Differ", reco_missing(a)
927
+ return a, latest, "Match", ""
928
+
929
+
930
+ def _year_only(raw):
931
+ """Return int(year) if the input looks like a bare year (e.g. '2024',
932
+ 'Year 2024', '2024.0'); otherwise None. Months/days disqualify it."""
933
+ if raw is None: return None
934
+ s = str(raw).strip()
935
+ if not s: return None
936
+ # Strip trailing .0 from Excel-numeric years
937
+ s = re.sub(r"\.0+$", "", s)
938
+ # If any month name (en/es/pt, full or short) appears -> not year-only
939
+ low = s.lower()
940
+ for token in re.findall(r"[a-zà-ÿ]+", low):
941
+ if token in ALL_MONTH_LOOKUP: return None
942
+ digits = re.findall(r"\d+", s)
943
+ if not digits: return None
944
+ # Year-only inputs have exactly one number, 4 digits long, in plausible range
945
+ if len(digits) == 1 and len(digits[0]) == 4:
946
+ y = int(digits[0])
947
+ if 1900 <= y <= 2100: return y
948
+ return None
949
+
950
+
951
+ def _bna_year(raw):
952
+ """Pull the year from a BNA date string. Returns int or None."""
953
+ dt = parse_date(raw)
954
+ if dt: return dt.year
955
+ if raw is None: return None
956
+ m = re.search(r"\b(19|20)\d{2}\b", str(raw))
957
+ return int(m.group(0)) if m else None
958
+
959
+
960
+ def rule_schedule_date(label):
961
+ """Compare AI date and BNA date by Month+Year only (ignore day)."""
962
+ def _r(ai, x, b, tie, lang):
963
+ if _is_blank(ai): return "", _val(b), "Match", ""
964
+ dt = parse_date(ai)
965
+ ai_year_only = _year_only(ai)
966
+ if dt:
967
+ transformed = fmt_month_year(dt, lang)
968
+ elif ai_year_only:
969
+ transformed = str(ai_year_only)
970
+ else:
971
+ transformed = str(ai).strip()
972
+ bn = _val(b)
973
+ if _is_blank(bn): return transformed, "", "Differ", reco_text(label, str(ai), transformed, "")
974
+ bn_dt = parse_date(bn)
975
+ # Year-only AI: match if year aligns with BNA's year
976
+ if ai_year_only:
977
+ bna_y = _bna_year(bn)
978
+ if bna_y and bna_y == ai_year_only:
979
+ return transformed, bn, "Match", ""
980
+ # Month+Year comparison
981
+ if dt and bn_dt and dt.year == bn_dt.year and dt.month == bn_dt.month:
982
+ return transformed, bn, "Match", ""
983
+ # If both parse to the same Month-Year string in any of the languages, also Match
984
+ if dt and bn_dt:
985
+ for L in ("en", "es", "pt"):
986
+ if fmt_month_year(dt, L).lower() == fmt_month_year(bn_dt, L).lower():
987
+ return transformed, bn, "Match", ""
988
+ # String fallback
989
+ if transformed.strip().lower() == bn.strip().lower():
990
+ return transformed, bn, "Match", ""
991
+ return transformed, bn, "Differ", reco_text(label, str(ai), transformed, bn)
992
+ return _r
993
+
994
+
995
+ def rule_pass_through(label):
996
+ def _r(ai, x, b, tie, lang):
997
+ if _is_blank(ai):
998
+ return "", "", "Match", ""
999
+ a = str(ai).strip()
1000
+ # 'Not in BNA' translated to selected language for the BNA cell
1001
+ not_in_bna = {"en": "Not in BNA", "es": "No está en BNA", "pt": "Não está em BNA"}.get(lang, "Not in BNA")
1002
+ return a, not_in_bna, "Differ", reco_text(label, a, a, not_in_bna, lang=lang)
1003
+ return _r
1004
+
1005
+
1006
+ def rule_latlon(ai, x, b, tie, lang):
1007
+ if _is_blank(ai): return "", _val(b), "Match", ""
1008
+ p = parse_latlon(ai)
1009
+ transformed = f"{p[0]}, {p[1]}" if p else str(ai)
1010
+ bn = _val(b); bp = parse_latlon(bn) if bn else None
1011
+ if not bp: return transformed, "", "Differ", reco_text("Latitude and Longitude", str(ai), transformed, "")
1012
+ if p and abs(p[0]-bp[0]) < 0.001 and abs(p[1]-bp[1]) < 0.001:
1013
+ return transformed, bn, "Match", ""
1014
+ return transformed, bn, "Differ", reco_text("Latitude and Longitude", str(ai), transformed, bn)
1015
+
1016
+
1017
+ def rule_main_works(ai, x, b, tie, lang):
1018
+ return rule_project_description(ai, x, b, tie, lang)
1019
+
1020
+
1021
+ def rule_documentation(ai, x, b, tie, lang):
1022
+ if _is_blank(ai): return "", "", "Match", ""
1023
+ a = str(ai).strip()
1024
+ return a, "Informational only", "Differ", f"Project Documentation (informational): {a}"
1025
+
1026
+
1027
+ def _strip_contact_decoration(s):
1028
+ """Strip trailing parentheticals from a person name:
1029
+ - email: 'Jane Doe (jane@x.com)' -> 'Jane Doe'
1030
+ - phone: 'John (+51 9 1234 5678)' -> 'John'
1031
+ - role: 'Ana (Manager, Procurement)' -> 'Ana'
1032
+ Only strips trailing '(...)' segments. Keeps inline parens that
1033
+ don't sit at the end (rare for person names)."""
1034
+ if not s: return s
1035
+ out = re.sub(r"\s*\([^()]*\)\s*$", "", str(s)).strip()
1036
+ # Repeat once in case there are two trailing parentheticals
1037
+ out = re.sub(r"\s*\([^()]*\)\s*$", "", out).strip()
1038
+ return out or str(s).strip()
1039
+
1040
+
1041
+ def _contact_role(label):
1042
+ def _r(ai, x, b, tie, lang):
1043
+ if _is_blank(ai): return "", _val(b), "Match", ""
1044
+ a_raw = str(ai).strip()
1045
+ # Strip trailing email/phone parenthetical from AI value before
1046
+ # comparison and display, e.g. 'GIAN CARLO SILVA ANCCO
1047
+ # (gsilva@proinversion.gob.pe)' -> 'GIAN CARLO SILVA ANCCO'.
1048
+ a = _strip_contact_decoration(a_raw)
1049
+ bna_names = b if isinstance(b, list) else _split_csv(_val(b))
1050
+ bna_names = [_strip_contact_decoration(n) for n in bna_names if n]
1051
+ if not bna_names: return a, "", "Differ", reco_text(label, a, a, "")
1052
+ a_n = _norm_name(a)
1053
+ if any(_norm_name(bb) == a_n for bb in bna_names):
1054
+ return a, ", ".join(bna_names), "Match", ""
1055
+ return a, ", ".join(bna_names), "Differ", reco_text(label, a, a, ", ".join(bna_names))
1056
+ return _r
1057
+
1058
+
1059
+ def _strip_plural(s):
1060
+ """Drop trailing 's' from each token so 'megawatts' compares equal to
1061
+ 'megawatt', 'tonnes' to 'tonne', etc. Keeps tokens shorter than 4 chars
1062
+ untouched (avoid stripping 't', 'kw', 'mw')."""
1063
+ if not s: return s
1064
+ out = []
1065
+ for tok in str(s).split():
1066
+ if len(tok) >= 4 and tok.endswith("s"):
1067
+ out.append(tok[:-1])
1068
+ else:
1069
+ out.append(tok)
1070
+ return " ".join(out)
1071
+
1072
+
1073
+ def _capacity_canonical_unit(text, tie):
1074
+ """Look up the canonical UNIT for a capacity unit phrase using the
1075
+ editable 'Capacity Units' sheet. Returns the canonical short form
1076
+ (e.g. 'b/d') or the lowercased input if no alias exists.
1077
+
1078
+ Consults 'Capacity Unit Translations' so an ES/PT phrase
1079
+ (e.g. 'quilômetros', 'kilómetros') reverse-maps to the English
1080
+ phrase first, then resolves via the alias table.
1081
+
1082
+ Also tries a plural-insensitive fallback ('megawatts' → 'megawatt')
1083
+ so BNA's plural form matches the singular alias in the TIE sheet."""
1084
+ if not text: return ""
1085
+ aliases = getattr(tie, "capacity_unit_aliases", None) or {}
1086
+ key = re.sub(r"\s+", " ", str(text)).strip().lower()
1087
+ if key in aliases:
1088
+ return aliases[key]
1089
+ cleaned = re.sub(r"\s*\([^)]+\)\s*$", "", key).strip()
1090
+ if cleaned in aliases:
1091
+ return aliases[cleaned]
1092
+ # Plural → singular fallback
1093
+ sing_key = _strip_plural(key)
1094
+ if sing_key != key and sing_key in aliases:
1095
+ return aliases[sing_key]
1096
+ sing_cleaned = _strip_plural(cleaned)
1097
+ if sing_cleaned != cleaned and sing_cleaned in aliases:
1098
+ return aliases[sing_cleaned]
1099
+ # ES/PT reverse-lookup via Capacity Unit Translations
1100
+ trans = getattr(tie, "capacity_unit_translations", None) or {}
1101
+ for en_key, langs in trans.items():
1102
+ es = (langs.get("es") or "").strip().lower()
1103
+ pt = (langs.get("pt") or "").strip().lower()
1104
+ if key == es or key == pt or cleaned == es or cleaned == pt:
1105
+ if en_key in aliases:
1106
+ return aliases[en_key]
1107
+ return en_key
1108
+ # Plural-insensitive translation lookup
1109
+ if sing_key == _strip_plural(es) or sing_key == _strip_plural(pt):
1110
+ if en_key in aliases: return aliases[en_key]
1111
+ return en_key
1112
+ return cleaned or key
1113
+
1114
+
1115
+ _CAPACITY_HEDGES = re.compile(
1116
+ r"\b(?:estimated|estimate|estimated:|estimate:|potential|potentially|"
1117
+ r"approximately|approx\.?|approxim|about|around|up\s*to|target(?:ed)?|"
1118
+ r"estimado|estimada|aproximadamente|hasta|cerca\s+de|"
1119
+ r"estimada?|aproximadamente|at[ée]\s+|cerca\s+de)\b\s*:?",
1120
+ re.IGNORECASE)
1121
+
1122
+
1123
+ def _strip_capacity_hedges(s):
1124
+ """Drop leading hedging words like 'Potential', 'Estimated', 'Approximately'
1125
+ from a capacity expression. Leaves the number+unit intact."""
1126
+ if not s: return s
1127
+ out = _CAPACITY_HEDGES.sub("", str(s)).strip(" ,;:-")
1128
+ out = re.sub(r"\s+", " ", out)
1129
+ return out
1130
+
1131
+
1132
+ def _trim_capacity_unit(unit_text):
1133
+ """Drop trailing 'of <product>' / 'de <product>' phrases from a unit
1134
+ string so 't/y of lithium carbonate' compares equal to 't/y'."""
1135
+ if not unit_text: return unit_text
1136
+ out = re.split(r"\s+(?:of|de|do|da|dos|das)\s+", str(unit_text), maxsplit=1,
1137
+ flags=re.IGNORECASE)[0]
1138
+ return out.strip(" ,;:-")
1139
+
1140
+
1141
+ def _parse_capacity_item(item, tie):
1142
+ """Parse one capacity expression (e.g. '750 megawatt hour',
1143
+ '4,800 t/y', 'Copper 1,000 tonnes per year', 'Potential 15,600 t/y
1144
+ of lithium carbonate') into (number, canonical unit).
1145
+ Returns (None, '') if no number is present.
1146
+
1147
+ Hedging words ('Potential', 'Estimated', 'Approximately', etc.) and
1148
+ trailing 'of <product>' tails are stripped before parsing so AI and
1149
+ BNA expressions match on number + canonical unit regardless of how
1150
+ they phrased the value."""
1151
+ if item is None: return None, ""
1152
+ s = _strip_capacity_hedges(str(item).strip())
1153
+ if not s: return None, ""
1154
+ m = re.search(r"-?\d[\d.,\s]*", s)
1155
+ if not m: return None, ""
1156
+ num_raw = m.group(0).strip()
1157
+ num = parse_number(num_raw)
1158
+ if num is None: return None, ""
1159
+ after = s[m.end():].strip(" ,;:-")
1160
+ before = s[:m.start()].strip(" ,;:-")
1161
+ mult, after = _extract_multiplier(after)
1162
+ if mult == 1 and before:
1163
+ mult, before = _extract_multiplier(before)
1164
+ num = num * mult
1165
+ raw_unit = (after or before).strip(" ,;:-")
1166
+ # Try canonical lookup with the FULL unit text first (handles
1167
+ # 'number of passengers per year' which contains 'of' but is itself
1168
+ # a known canonical alias). Only fall back to 'of/de' splitting when
1169
+ # the full phrase doesn't resolve.
1170
+ canonical = _capacity_canonical_unit(raw_unit, tie)
1171
+ if canonical == raw_unit.strip().lower() or not canonical:
1172
+ unit_text = _trim_capacity_unit(raw_unit)
1173
+ canonical = _capacity_canonical_unit(unit_text, tie)
1174
+ return num, canonical
1175
+
1176
+
1177
+ def rule_capacity(ai, x, b, tie, lang):
1178
+ """Capacity comparison.
1179
+
1180
+ Both sides are split into items (comma / semicolon / newline). Each
1181
+ item is parsed as (number, canonical_unit) using the 'Capacity Units'
1182
+ TIE sheet. Many-to-many comparison: if any AI item matches any BNA
1183
+ item (number within 0.1% AND canonical unit equal), the row is a
1184
+ Match. Transformed AI value preserves the original text.
1185
+ """
1186
+ if _is_blank(ai): return "", _val(b), "Match", ""
1187
+ transformed = str(ai).strip()
1188
+ bn = _val(b)
1189
+
1190
+ ai_items = _split_csv(ai) if any(c in str(ai) for c in ",;\n") else [str(ai)]
1191
+ bn_items = _split_csv(bn) if any(c in str(bn) for c in ",;\n") else ([bn] if bn else [])
1192
+
1193
+ ai_pairs = [_parse_capacity_item(it, tie) for it in ai_items]
1194
+ ai_pairs = [p for p in ai_pairs if p[0] is not None]
1195
+ bn_pairs = [_parse_capacity_item(it, tie) for it in bn_items]
1196
+ bn_pairs = [p for p in bn_pairs if p[0] is not None]
1197
+
1198
+ if not bn_pairs:
1199
+ return transformed, "", "Differ", reco_text("Capacity", str(ai), transformed, "")
1200
+
1201
+ def _match(a_num, a_unit, b_num, b_unit):
1202
+ if a_num is None or b_num is None: return False
1203
+ denom = max(1.0, abs(a_num), abs(b_num))
1204
+ if abs(a_num - b_num) / denom > 0.001: return False
1205
+ # Units match if either canonical equal OR one is empty (be lenient)
1206
+ if not a_unit or not b_unit: return True
1207
+ return a_unit == b_unit
1208
+
1209
+ # Many-to-many: every AI item must find SOME matching BNA item
1210
+ if not ai_pairs:
1211
+ return transformed, bn, "Differ", reco_text("Capacity", str(ai), transformed, bn)
1212
+ all_matched = all(
1213
+ any(_match(an, au, bnum, bu) for bnum, bu in bn_pairs)
1214
+ for an, au in ai_pairs
1215
+ )
1216
+ if all_matched:
1217
+ return transformed, bn, "Match", ""
1218
+ return transformed, bn, "Differ", reco_text("Capacity", str(ai), transformed, bn)
1219
+
1220
+
1221
+ RULES = {
1222
+ "project name": rule_project_name,
1223
+ "owner company": rule_owner,
1224
+ "concessionaire / operator company": rule_concession,
1225
+ "contractor company": rule_contractor,
1226
+ "engineering company": rule_engineering_co,
1227
+ "equipment / technology provider": rule_equipment_co,
1228
+ "consultancy company": rule_consultancy_co,
1229
+ "project stage": rule_project_stage,
1230
+ "project description": rule_project_description,
1231
+ "description": rule_project_description,
1232
+ "descripción": rule_project_description,
1233
+ "descripción del proyecto": rule_project_description,
1234
+ "descrição": rule_project_description,
1235
+ "descrição do projeto": rule_project_description,
1236
+ "property type": rule_property_type,
1237
+ "development type": rule_development_type,
1238
+ "capex": rule_capex,
1239
+ "lifespan": rule_lifespan,
1240
+ "project type": rule_project_type,
1241
+ "milestones": rule_milestones,
1242
+ "announcement date": rule_schedule_date("Announcement Date"),
1243
+ "completion_end of construction date": rule_schedule_date("Completion / End of Construction Date"),
1244
+ "construction start date": rule_schedule_date("Construction Start Date"),
1245
+ "contractor tendering start date": rule_schedule_date("Contractor Tendering Start Date"),
1246
+ "detailed engineering start date": rule_schedule_date("Detailed Engineering Start Date"),
1247
+ "environmental approval date": rule_schedule_date("Environmental Approval Date"),
1248
+ "environmental approval": rule_schedule_date("Environmental Approval Date"),
1249
+ "environmental and social approval": rule_schedule_date("Environmental Approval Date"),
1250
+ "environmental and social approval date": rule_schedule_date("Environmental Approval Date"),
1251
+ "tendering start date": rule_schedule_date("Tendering Start Date"),
1252
+ # All Month+Year date fields use rule_schedule_date so AI value and BNA
1253
+ # value match when (year, month) align — irrespective of language
1254
+ # (DICIEMBRE 2030 == Dezembro 2030 == December 2030) and irrespective
1255
+ # of "Estimated:" / "Confirmado:" prefixes.
1256
+ "operations start date": rule_schedule_date("Operations Start Date"),
1257
+ "start of operation date": rule_schedule_date("Operations Start Date"),
1258
+ "end of operation date": rule_schedule_date("End of Operation Date"),
1259
+ "environmental impact assessment submission_presentation date": rule_schedule_date("EIA Submission/Presentation Date"),
1260
+ "feasibility studies start date": rule_schedule_date("Feasibility Studies Start Date"),
1261
+ "pre-feasibility studies start date": rule_schedule_date("Pre-feasibility Studies Start Date"),
1262
+ "latitude and longitude": rule_latlon,
1263
+ "main works description": rule_main_works,
1264
+ "project manager": _contact_role("Project Manager"),
1265
+ "purchasing manager": _contact_role("Purchasing Manager"),
1266
+ "engineering manager": _contact_role("Engineering Manager"),
1267
+ "capacity": rule_capacity,
1268
+ "products required": rule_pass_through("Products required"),
1269
+ "services required": rule_pass_through("Services required"),
1270
+ }
1271
+
1272
+
1273
+ def _key(s):
1274
+ return re.sub(r"\s+", " ", str(s or "").strip().lower())
1275
+
1276
+
1277
+ def _bna_last_expert_review(bna_fields):
1278
+ if not bna_fields: return None
1279
+ for k, v in bna_fields.items():
1280
+ if str(k).strip().lower() == "last expert review":
1281
+ return v
1282
+ return None
1283
+
1284
+
1285
+ def _maybe_downgrade_to_stale(verdict, ai_extra, bna_fields):
1286
+ if verdict != "Differ": return verdict
1287
+ if _is_blank(ai_extra): return verdict
1288
+ bna_review = _bna_last_expert_review(bna_fields)
1289
+ if _is_blank(bna_review): return verdict
1290
+ ai_dt = parse_date(ai_extra)
1291
+ bna_dt = parse_date(bna_review)
1292
+ if ai_dt is None or bna_dt is None: return verdict
1293
+ if ai_dt <= bna_dt:
1294
+ return "Stale AI"
1295
+ return verdict
1296
+
1297
+
1298
+ def apply_rule(field_name, ai_value, ai_extra, bna_data, tie, lang, bna_fields=None):
1299
+ key = _key(field_name)
1300
+ if _is_blank(ai_value):
1301
+ bn_disp = _val(bna_data)
1302
+ if not bn_disp or _is_blank(bn_disp):
1303
+ return "", "", "Missing on Both", ""
1304
+ return "", bn_disp, "Missing on AI", ""
1305
+ fn = RULES.get(key)
1306
+ if fn is None:
1307
+ ai = "" if _is_blank(ai_value) else str(ai_value).strip()
1308
+ bn = _val(bna_data)
1309
+ if not ai and not bn: return "", "", "Match", ""
1310
+ if not bn:
1311
+ verdict = _maybe_downgrade_to_stale("Differ", ai_extra, bna_fields)
1312
+ return ai, "", verdict, reco_text(str(field_name), ai, ai, "", lang=lang)
1313
+ if ai.strip().lower() == bn.strip().lower():
1314
+ return ai, bn, "Match", ""
1315
+ verdict = _maybe_downgrade_to_stale("Differ", ai_extra, bna_fields)
1316
+ return ai, bn, verdict, reco_text(str(field_name), ai, ai, bn, lang=lang)
1317
+ transformed, bna_value, match, reco = fn(ai_value, ai_extra, bna_data, tie, lang)
1318
+ new_match = _maybe_downgrade_to_stale(match, ai_extra, bna_fields)
1319
+ return transformed, bna_value, new_match, reco
engine/run_batch_cli.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CLI wrapper around batch_runner.run_batch.
2
+
3
+ Streamlit's main process holds Playwright's sync API in a poisoned
4
+ state after the first use (event loop closes; second call fails).
5
+ The cleanest workaround is to run each batch in a brand-new Python
6
+ subprocess, which gets a fresh Playwright instance every time.
7
+
8
+ Invocation (called by app.py, not by humans):
9
+ python run_batch_cli.py <output_json> <log_jsonl>
10
+
11
+ Config is read from stdin as a single JSON object. Keeping it off the
12
+ command line prevents the BNA password from appearing in `ps aux`.
13
+
14
+ `output_json` is where the summary dict is written when the run finishes
15
+ `log_jsonl` is appended to as the run progresses, one JSON line per
16
+ log message; the Streamlit side tails this file to update
17
+ the live log view
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import sys
23
+ import traceback
24
+ from pathlib import Path
25
+
26
+ HERE = Path(__file__).resolve().parent
27
+ sys.path.insert(0, str(HERE))
28
+ import batch_runner # noqa: E402
29
+
30
+
31
+ def _redact(text: str, secret: str) -> str:
32
+ if not secret or not text:
33
+ return text
34
+ return text.replace(secret, "***REDACTED***")
35
+
36
+
37
+ def main() -> int:
38
+ if len(sys.argv) != 3:
39
+ print("Usage: run_batch_cli.py <output_json> <log_jsonl>",
40
+ file=sys.stderr)
41
+ return 2
42
+
43
+ out_path = Path(sys.argv[1])
44
+ log_path = Path(sys.argv[2])
45
+
46
+ # Config + credentials come in on stdin so the password never
47
+ # appears in the process list or in a file path readable to other
48
+ # processes.
49
+ cfg = json.loads(sys.stdin.read())
50
+ bna_password = cfg.get("password", "")
51
+
52
+ def _log(level: str, message: str) -> None:
53
+ with log_path.open("a", encoding="utf-8") as fh:
54
+ fh.write(json.dumps({"type": "log",
55
+ "level": level,
56
+ "message": _redact(message, bna_password)}) + "\n")
57
+
58
+ def _progress(info) -> None:
59
+ with log_path.open("a", encoding="utf-8") as fh:
60
+ fh.write(json.dumps({"type": "progress",
61
+ "info": info},
62
+ default=str) + "\n")
63
+
64
+ try:
65
+ summary = batch_runner.run_batch(
66
+ ai_zip_path=cfg["ai_zip_path"],
67
+ lang=cfg.get("lang", "es"),
68
+ email=cfg.get("email", ""),
69
+ password=cfg.get("password", ""),
70
+ output_folder=cfg["output_folder"],
71
+ tie_path=cfg["tie_path"],
72
+ log=_log,
73
+ progress=_progress,
74
+ headless=cfg.get("headless", True),
75
+ manual_login=cfg.get("manual_login", False),
76
+ bna_cookies=cfg.get("bna_cookies", ""),
77
+ )
78
+ out_path.write_text(
79
+ json.dumps({"ok": True, "summary": summary}, default=str),
80
+ encoding="utf-8",
81
+ )
82
+ return 0
83
+ except Exception as e:
84
+ # Scrub the password from any traceback before persisting it,
85
+ # so we never leak it via the error-details expander or HF logs.
86
+ tb = _redact(traceback.format_exc(), bna_password)
87
+ err = _redact(f"{type(e).__name__}: {e}", bna_password)
88
+ out_path.write_text(
89
+ json.dumps({"ok": False, "error": err, "traceback": tb}),
90
+ encoding="utf-8",
91
+ )
92
+ return 1
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
engine/scraper.py ADDED
The diff for this file is too large to render. See raw diff
 
engine/tie_loader.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ TIE Loader: Reads TIE Requirements.xlsx at runtime.
3
+ Per TIE Logics.docx: ignore General tab. Load reference tabs only.
4
+ """
5
+ from __future__ import annotations
6
+ import os
7
+ import re
8
+ from datetime import datetime
9
+ from typing import Dict, List, Optional, Tuple
10
+ import openpyxl
11
+
12
+
13
+ def _norm(s):
14
+ if s is None: return ""
15
+ return str(s).strip().lower()
16
+
17
+
18
+ class TIE:
19
+ def __init__(self, path: str):
20
+ self.path = path
21
+ self.wb = openpyxl.load_workbook(path, data_only=True)
22
+ self.stage_mapping: Dict[str, str] = {}
23
+ self.project_type_mapping: Dict[str, str] = {}
24
+ self.region_mapping: Dict[str, str] = {}
25
+ self.ownership_type_mapping: Dict[str, str] = {}
26
+ self.development_type_mapping: Dict[str, str] = {}
27
+ self.project_position_mapping: Dict[str, str] = {}
28
+ self.company_roles: Dict[str, Dict[str, str]] = {}
29
+ self.current_stages: List[Dict[str, str]] = []
30
+ self.capacity_by_type: Dict[str, List[str]] = {}
31
+ # Capacity Units: phrase → canonical short unit. Built from the
32
+ # editable 'Capacity Units' sheet (UNIT, NAME UNIT columns) so
33
+ # researchers can extend mappings without code changes.
34
+ self.capacity_unit_aliases: Dict[str, str] = {}
35
+ # BNA enum-value translations: english_lower → {'es': ..., 'pt': ...}
36
+ # Used to display BNA values in the selected output language even
37
+ # when BNA stores the underlying enum in English. Editable via the
38
+ # '*** Translations' sheets in TIE_Requirements.xlsx.
39
+ self.bna_translations: Dict[str, Dict[str, Dict[str, str]]] = {
40
+ "property_type": {},
41
+ "development_type": {},
42
+ "project_type": {},
43
+ "project_stage": {},
44
+ }
45
+ # Capacity unit phrase translations: english_lower → {'es','pt'}.
46
+ # Editable via the 'Capacity Unit Translations' sheet.
47
+ self.capacity_unit_translations: Dict[str, Dict[str, str]] = {}
48
+ self.date_examples: List[Tuple[str, str]] = []
49
+ # Company Chip Mapping: AI field name -> BNA chip label.
50
+ # Loaded from the editable 'Company Chip Mapping' sheet so the
51
+ # researcher can extend mappings without code changes.
52
+ self.company_chip_mapping: Dict[str, str] = {}
53
+ # FX Rates: list of (currency, date, rate_to_usd) tuples loaded from
54
+ # the editable 'FX Rates' sheet. Used by currency.py for Capex conv.
55
+ self.fx_rates: List = []
56
+
57
+ self._load_mapping("Stage Mapping", self.stage_mapping)
58
+ self._load_mapping("Project Type", self.project_type_mapping)
59
+ self._load_mapping("Region", self.region_mapping)
60
+ self._load_mapping("Ownership Type", self.ownership_type_mapping)
61
+ self._load_mapping("Development Type", self.development_type_mapping)
62
+ self._load_project_position()
63
+ self._load_company_roles()
64
+ self._load_company_chip_mapping()
65
+ self._load_fx_rates()
66
+ self._load_current_stages()
67
+ self._load_capacity()
68
+ self._load_capacity_units()
69
+ self._load_bna_translations()
70
+ self._load_capacity_unit_translations()
71
+ self._load_dates()
72
+
73
+ def _load_mapping(self, sheet, target):
74
+ if sheet not in self.wb.sheetnames: return
75
+ ws = self.wb[sheet]
76
+ for i, row in enumerate(ws.iter_rows(values_only=True)):
77
+ if i == 0: continue
78
+ if not row or len(row) < 2: continue
79
+ ext, bna = row[0], row[1]
80
+ if ext is None or bna is None: continue
81
+ target[_norm(ext)] = str(bna).strip()
82
+
83
+ def _load_project_position(self):
84
+ """Project Position sheet: maps standard role -> BNA position term.
85
+ We invert it: bracket-extracted BNA term -> standard role."""
86
+ if "Project Position" not in self.wb.sheetnames: return
87
+ ws = self.wb["Project Position"]
88
+ for i, row in enumerate(ws.iter_rows(values_only=True)):
89
+ if i == 0: continue
90
+ if not row or len(row) < 2: continue
91
+ std_role, bna_term = row[0], row[1]
92
+ if std_role is None or bna_term is None: continue
93
+ # invert: bna term -> std role
94
+ self.project_position_mapping[_norm(bna_term)] = str(std_role).strip()
95
+
96
+ def _load_company_roles(self):
97
+ if "Company Mapping (Roles)" not in self.wb.sheetnames: return
98
+ ws = self.wb["Company Mapping (Roles)"]
99
+ headers = None
100
+ for i, row in enumerate(ws.iter_rows(values_only=True)):
101
+ if i == 0:
102
+ headers = [str(h or "").strip() for h in row]; continue
103
+ if not row or not row[0]: continue
104
+ enum_key = str(row[0]).strip()
105
+ self.company_roles[enum_key] = {
106
+ "es": str(row[1] or "").strip() if len(row) > 1 else "",
107
+ "en": str(row[2] or "").strip() if len(row) > 2 else "",
108
+ "pt": str(row[3] or "").strip() if len(row) > 3 else "",
109
+ }
110
+
111
+ def _load_current_stages(self):
112
+ if "Current Stage" not in self.wb.sheetnames: return
113
+ ws = self.wb["Current Stage"]
114
+ for i, row in enumerate(ws.iter_rows(values_only=True)):
115
+ if i == 0: continue
116
+ if not row or not row[1]: continue
117
+ self.current_stages.append({
118
+ "order": row[0],
119
+ "substage": str(row[1]).strip(),
120
+ "es": str(row[2] or "").strip() if len(row) > 2 else "",
121
+ "en": str(row[3] or "").strip() if len(row) > 3 else "",
122
+ "pt": str(row[4] or "").strip() if len(row) > 4 else "",
123
+ })
124
+
125
+ def _load_capacity(self):
126
+ if "Capacity" not in self.wb.sheetnames: return
127
+ ws = self.wb["Capacity"]
128
+ for i, row in enumerate(ws.iter_rows(values_only=True)):
129
+ if i == 0: continue
130
+ if not row or not row[1]: continue
131
+ project_type = _norm(row[1])
132
+ units = []
133
+ for idx in (2, 4, 6, 8):
134
+ if idx < len(row) and row[idx]:
135
+ units.append(str(row[idx]).strip())
136
+ self.capacity_by_type[project_type] = units
137
+
138
+ def _load_capacity_units(self):
139
+ """Load 'Capacity Units' sheet. Two columns: UNIT, NAME UNIT.
140
+ Both forms become aliases that map to the canonical (UNIT) value
141
+ — e.g. 'barrels per day' -> 'b/d', 'b/d' -> 'b/d'. Lookup is
142
+ case-insensitive and whitespace-insensitive."""
143
+ if "Capacity Units" not in self.wb.sheetnames: return
144
+ ws = self.wb["Capacity Units"]
145
+ def _key(s):
146
+ if s is None: return ""
147
+ return re.sub(r"\s+", " ", str(s)).strip().lower()
148
+ for i, row in enumerate(ws.iter_rows(values_only=True)):
149
+ if i == 0: continue
150
+ if not row or len(row) < 2: continue
151
+ unit, name_unit = row[0], row[1]
152
+ if unit is None and name_unit is None: continue
153
+ canonical = _key(unit) or _key(name_unit)
154
+ if not canonical: continue
155
+ if unit:
156
+ self.capacity_unit_aliases[_key(unit)] = canonical
157
+ if name_unit:
158
+ self.capacity_unit_aliases[_key(name_unit)] = canonical
159
+
160
+ def _load_bna_translations(self):
161
+ """Load the four BNA enum-value translation sheets. Each row is
162
+ (English, Spanish, Portuguese). Stored keyed by lowercased English
163
+ for case-insensitive lookup. Researchers can add rows to extend
164
+ coverage without touching code."""
165
+ sheet_to_field = {
166
+ "Property Type Translations": "property_type",
167
+ "Development Type Translations": "development_type",
168
+ "Project Type Translations": "project_type",
169
+ "Project Stage Translations": "project_stage",
170
+ }
171
+ for sheet, field_key in sheet_to_field.items():
172
+ if sheet not in self.wb.sheetnames: continue
173
+ ws = self.wb[sheet]
174
+ for i, row in enumerate(ws.iter_rows(values_only=True)):
175
+ if i == 0: continue # header
176
+ if not row or not row[0]: continue
177
+ en = str(row[0]).strip()
178
+ if not en: continue
179
+ es = str(row[1] or "").strip() if len(row) > 1 else ""
180
+ pt = str(row[2] or "").strip() if len(row) > 2 else ""
181
+ self.bna_translations[field_key][en.lower()] = {
182
+ "es": es or en, "pt": pt or en,
183
+ }
184
+
185
+ def _load_capacity_unit_translations(self):
186
+ """Load 'Capacity Unit Translations' (English | Spanish | Portuguese)."""
187
+ if "Capacity Unit Translations" not in self.wb.sheetnames: return
188
+ ws = self.wb["Capacity Unit Translations"]
189
+ def _key(s):
190
+ if s is None: return ""
191
+ return re.sub(r"\s+", " ", str(s)).strip().lower()
192
+ for i, row in enumerate(ws.iter_rows(values_only=True)):
193
+ if i == 0: continue
194
+ if not row or not row[0]: continue
195
+ en = _key(row[0])
196
+ if not en: continue
197
+ es = str(row[1] or "").strip() if len(row) > 1 else ""
198
+ pt = str(row[2] or "").strip() if len(row) > 2 else ""
199
+ self.capacity_unit_translations[en] = {"es": es or row[0], "pt": pt or row[0]}
200
+
201
+ def _load_dates(self):
202
+ if "Dates" not in self.wb.sheetnames: return
203
+ ws = self.wb["Dates"]
204
+ for i, row in enumerate(ws.iter_rows(values_only=True)):
205
+ if i == 0: continue
206
+ if not row or row[0] is None: continue
207
+ self.date_examples.append((str(row[0]), str(row[1] or "")))
208
+
209
+ def lookup_mapping(self, mapping, value):
210
+ if value is None: return None
211
+ return mapping.get(_norm(value))
212
+
213
+ def map_project_position_to_role(self, bna_term):
214
+ """Given a bracket-extracted BNA position (e.g. 'Managers - Project'),
215
+ return the standard role (e.g. 'Project Manager')."""
216
+ if not bna_term: return None
217
+ return self.project_position_mapping.get(_norm(bna_term))
218
+
219
+ def _load_company_chip_mapping(self):
220
+ """Read the 'Company Chip Mapping' sheet:
221
+ Col A: Agentic AI Output Field Name
222
+ Col B: BNA Chip
223
+ Stored as: ai_field_norm -> bna_chip (preserved case)."""
224
+ if "Company Chip Mapping" not in self.wb.sheetnames: return
225
+ ws = self.wb["Company Chip Mapping"]
226
+ for i, row in enumerate(ws.iter_rows(values_only=True)):
227
+ if i == 0: continue
228
+ if not row or len(row) < 2: continue
229
+ ai_field, bna_chip = row[0], row[1]
230
+ if ai_field is None or bna_chip is None: continue
231
+ self.company_chip_mapping[_norm(ai_field)] = str(bna_chip).strip()
232
+
233
+ def map_ai_company_field_to_chip(self, ai_field):
234
+ """AI field name (e.g. 'Owner Company') -> BNA chip label."""
235
+ if not ai_field: return None
236
+ return self.company_chip_mapping.get(_norm(ai_field))
237
+
238
+ def _load_fx_rates(self):
239
+ """'FX Rates' sheet:
240
+ Col A: ISO currency code (e.g. BRL)
241
+ Col B: date the rate is valid for (DD/MM/YYYY or any parsable form)
242
+ Col C: rate (multiplier to USD; e.g. 0.18 for BRL)
243
+ """
244
+ if "FX Rates" not in self.wb.sheetnames: return
245
+ ws = self.wb["FX Rates"]
246
+ for i, row in enumerate(ws.iter_rows(values_only=True)):
247
+ if i == 0: continue
248
+ if not row or not row[0] or not row[1] or row[2] is None: continue
249
+ try:
250
+ code = str(row[0]).strip().upper()
251
+ dt_raw = row[1]
252
+ if isinstance(dt_raw, datetime):
253
+ dt = dt_raw
254
+ else:
255
+ s = str(dt_raw).strip()
256
+ dt = None
257
+ for fmt in ("%Y-%m-%d","%d/%m/%Y","%m/%d/%Y","%d-%m-%Y","%Y/%m/%d"):
258
+ try: dt = datetime.strptime(s, fmt); break
259
+ except ValueError: pass
260
+ if dt is None: continue
261
+ rate = float(row[2])
262
+ self.fx_rates.append((code, dt, rate))
263
+ except Exception:
264
+ continue
engine/transformer.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Transformer: Applies TIE transformation/validation rules to AI values.
3
+ Runs entirely from TIE config; no hardcoded mapping.
4
+ """
5
+ from __future__ import annotations
6
+ import re
7
+ from datetime import datetime
8
+ from typing import Any, Dict, Optional, Tuple
9
+ from tie_loader import TIE, _norm
10
+
11
+
12
+ # ---------- Date transformation ----------
13
+
14
+ MONTHS_EN = [
15
+ "January", "February", "March", "April", "May", "June",
16
+ "July", "August", "September", "October", "November", "December",
17
+ ]
18
+
19
+ SPANISH_MONTHS = {
20
+ "enero": 1, "febrero": 2, "marzo": 3, "abril": 4, "mayo": 5, "junio": 6,
21
+ "julio": 7, "agosto": 8, "septiembre": 9, "setiembre": 9, "octubre": 10,
22
+ "noviembre": 11, "diciembre": 12,
23
+ }
24
+ PORTUGUESE_MONTHS = {
25
+ "janeiro": 1, "fevereiro": 2, "março": 3, "marco": 3, "abril": 4, "maio": 5,
26
+ "junho": 6, "julho": 7, "agosto": 8, "setembro": 9, "outubro": 10,
27
+ "novembro": 11, "dezembro": 12,
28
+ }
29
+ ENGLISH_MONTHS = {m.lower(): i + 1 for i, m in enumerate(MONTHS_EN)}
30
+ ENGLISH_MONTHS_SHORT = {"jan": 1, "feb": 2, "mar": 3, "apr": 4, "may": 5, "jun": 6,
31
+ "jul": 7, "aug": 8, "sep": 9, "sept": 9, "oct": 10,
32
+ "nov": 11, "dec": 12}
33
+ ALL_MONTHS = {**SPANISH_MONTHS, **PORTUGUESE_MONTHS, **ENGLISH_MONTHS, **ENGLISH_MONTHS_SHORT}
34
+
35
+
36
+ def parse_date_flexible(raw) -> Optional[datetime]:
37
+ """Parse many date formats. Returns datetime or None."""
38
+ if raw is None or raw == "":
39
+ return None
40
+ if isinstance(raw, datetime):
41
+ return raw
42
+ s = str(raw).strip()
43
+ if not s:
44
+ return None
45
+ # Strip time if present
46
+ s = re.sub(r"T\d{2}:\d{2}.*$", "", s)
47
+ s = re.sub(r"\s+\d{2}:\d{2}.*$", "", s)
48
+
49
+ # Try ISO formats
50
+ for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%Y.%m.%d", "%Y-%m", "%Y/%m", "%Y.%m"):
51
+ try:
52
+ return datetime.strptime(s, fmt)
53
+ except ValueError:
54
+ pass
55
+
56
+ # dd-mm-yyyy, dd.mm.yyyy, dd/mm/yyyy
57
+ for fmt in ("%d-%m-%Y", "%d.%m.%Y", "%d/%m/%Y", "%d-%m-%y", "%d.%m.%y", "%d/%m/%y",
58
+ "%m-%Y", "%m/%Y", "%m.%Y"):
59
+ try:
60
+ return datetime.strptime(s, fmt)
61
+ except ValueError:
62
+ pass
63
+
64
+ # Month name: "March 2025", "15 September 2026", "September 2026"
65
+ token_pattern = re.compile(r"([A-Za-zÀ-ÿ]+)", re.UNICODE)
66
+ nums = re.findall(r"\d+", s)
67
+ tokens = token_pattern.findall(s)
68
+ month = None
69
+ for t in tokens:
70
+ tl = t.lower()
71
+ if tl in ALL_MONTHS:
72
+ month = ALL_MONTHS[tl]
73
+ break
74
+ year = None
75
+ day = 1
76
+ for n in nums:
77
+ if len(n) == 4:
78
+ year = int(n)
79
+ elif not day or day == 1:
80
+ if 1 <= int(n) <= 31:
81
+ day = int(n)
82
+ if month and year:
83
+ try:
84
+ return datetime(year, month, day)
85
+ except ValueError:
86
+ return datetime(year, month, 1)
87
+
88
+ # "de" Spanish: "14 de marzo de 2024"
89
+ m = re.search(r"(\d{1,2})\s+de\s+([A-Za-zÀ-ÿ]+)\s+de\s+(\d{4})", s, re.IGNORECASE)
90
+ if m:
91
+ mn = ALL_MONTHS.get(m.group(2).lower())
92
+ if mn:
93
+ return datetime(int(m.group(3)), mn, int(m.group(1)))
94
+
95
+ return None
96
+
97
+
98
+ def format_date_month_year(dt: Optional[datetime], lang: str = "en") -> str:
99
+ if not dt:
100
+ return ""
101
+ if lang == "es":
102
+ es = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio",
103
+ "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"]
104
+ return f"{es[dt.month - 1]} {dt.year}"
105
+ if lang == "pt":
106
+ pt = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho",
107
+ "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"]
108
+ return f"{pt[dt.month - 1]} {dt.year}"
109
+ return f"{MONTHS_EN[dt.month - 1]} {dt.year}"
110
+
111
+
112
+ # ---------- Number transformation ----------
113
+
114
+ def parse_number(raw) -> Optional[float]:
115
+ if raw is None or raw == "":
116
+ return None
117
+ if isinstance(raw, (int, float)):
118
+ return float(raw)
119
+ s = str(raw).strip()
120
+ if not s:
121
+ return None
122
+ # remove currency symbols/units
123
+ s_clean = re.sub(r"[^\d,.\-]", "", s)
124
+ if not s_clean:
125
+ return None
126
+ # Decide decimal separator: if both . and , exist, the last one is decimal
127
+ if "," in s_clean and "." in s_clean:
128
+ if s_clean.rfind(",") > s_clean.rfind("."):
129
+ s_clean = s_clean.replace(".", "").replace(",", ".")
130
+ else:
131
+ s_clean = s_clean.replace(",", "")
132
+ elif "," in s_clean:
133
+ # If comma and exactly two digits follow, treat as decimal (ES/PT)
134
+ parts = s_clean.split(",")
135
+ if len(parts) == 2 and len(parts[-1]) <= 2:
136
+ s_clean = s_clean.replace(",", ".")
137
+ else:
138
+ s_clean = s_clean.replace(",", "")
139
+ try:
140
+ return float(s_clean)
141
+ except ValueError:
142
+ return None
143
+
144
+
145
+ def format_number(value: float, lang: str = "en", decimals: int = 2) -> str:
146
+ if value is None:
147
+ return ""
148
+ if decimals == 0:
149
+ s = f"{value:,.0f}"
150
+ else:
151
+ s = f"{value:,.{decimals}f}"
152
+ if lang in ("es", "pt"):
153
+ # swap thousands/decimal
154
+ s = s.replace(",", "§").replace(".", ",").replace("§", ".")
155
+ return s
156
+
157
+
158
+ def format_capex(value: float, lang: str = "en") -> str:
159
+ if value is None:
160
+ return ""
161
+ decimals = 1 if value <= 99 else 0
162
+ return format_number(value, lang, decimals) + " USD"
163
+
164
+
165
+ # ---------- Multi-value + translation helpers ----------
166
+
167
+ def _split_tokens(raw_value: Any) -> list:
168
+ """Split multi-value strings on comma, semicolon or pipe.
169
+ Do NOT split on '/' — canonical names contain it
170
+ (e.g. 'Construction / Development', 'Public (PPP/PFI)').
171
+
172
+ Pipe ('|') is used by the AI agent for hierarchical project type
173
+ listings, e.g. 'Water > System | Wastewater > Plant'. Each segment
174
+ may also contain a 'Sector > Type' prefix — we keep only the part
175
+ after the last '>' so the translation table sees the leaf token."""
176
+ if raw_value is None:
177
+ return []
178
+ s = str(raw_value).strip()
179
+ if not s:
180
+ return []
181
+ parts = re.split(r"\s*[,;|]\s*", s)
182
+ out = []
183
+ for p in parts:
184
+ p = p.strip()
185
+ if not p:
186
+ continue
187
+ # If a token contains '>', keep only the segment after the last '>'.
188
+ if ">" in p:
189
+ p = p.rsplit(">", 1)[-1].strip()
190
+ if p:
191
+ out.append(p)
192
+ return out
193
+
194
+
195
+ def _translate_enum(canonical_en: str, field_key: str, tie: TIE, lang: str) -> str:
196
+ """Translate enum value to target language using tie.bna_translations.
197
+
198
+ Accepts input in EN/ES/PT — performs reverse-lookup if input is not
199
+ already English. This handles cases where the AI scraper returns a
200
+ value in Spanish/Portuguese (e.g. 'Concessões') instead of English."""
201
+ if not canonical_en:
202
+ return canonical_en
203
+ table = getattr(tie, "bna_translations", {}).get(field_key, {})
204
+ if not table:
205
+ return canonical_en
206
+ key = canonical_en.lower()
207
+ entry = table.get(key)
208
+ if not entry:
209
+ # Reverse-lookup: input might already be in ES or PT
210
+ for en_key, langs in table.items():
211
+ if (langs.get("es") or "").lower() == key or (langs.get("pt") or "").lower() == key:
212
+ entry = langs
213
+ canonical_en = en_key # canonical EN form
214
+ break
215
+ if not entry:
216
+ return canonical_en
217
+ if lang == "en":
218
+ # Return canonical EN (Title-cased from the sheet if found)
219
+ for en_key in table:
220
+ if en_key.lower() == canonical_en.lower():
221
+ # Find original sheet casing
222
+ pass
223
+ return canonical_en
224
+ return entry.get(lang) or canonical_en
225
+
226
+
227
+ def _map_and_translate(raw_value: Any, mapping_dict: Dict[str, str],
228
+ translations_key: Optional[str], tie: TIE, lang: str) -> str:
229
+ """Multi-value safe: split → map each token to canonical EN →
230
+ translate each to target lang → rejoin with ', '."""
231
+ tokens = _split_tokens(raw_value)
232
+ if not tokens:
233
+ return ""
234
+ out = []
235
+ for t in tokens:
236
+ mapped = tie.lookup_mapping(mapping_dict, t) if mapping_dict else None
237
+ canonical = mapped or t
238
+ if translations_key:
239
+ canonical = _translate_enum(canonical, translations_key, tie, lang)
240
+ out.append(canonical)
241
+ return ", ".join(out)
242
+
243
+
244
+ # ---------- Transformation dispatcher ----------
245
+
246
+ def transform(field_name: str, raw_value: Any, ai_date: Any, tie: TIE,
247
+ lang: str = "en", project_type_hint: Optional[str] = None) -> str:
248
+ """Apply per-field TIE transformation. Returns a string."""
249
+ if raw_value is None or str(raw_value).strip() == "":
250
+ return ""
251
+ key = _norm(field_name)
252
+
253
+ # Date-like fields
254
+ date_fields = {
255
+ "announcement date", "completion_end of construction date", "construction start date",
256
+ "contractor tendering start date", "detailed engineering start date",
257
+ "end of operation date", "environmental approval date",
258
+ "environmental impact assessment submission_presentation date",
259
+ "feasibility studies start date", "operations start date",
260
+ "pre-feasibility studies start date", "tendering start date",
261
+ }
262
+ if key in date_fields or "date" in key:
263
+ dt = parse_date_flexible(raw_value)
264
+ return format_date_month_year(dt, lang)
265
+
266
+ # Project stage -> Stage Mapping + Project Stage Translations
267
+ if key == "project stage" or key == "current stage":
268
+ return _map_and_translate(raw_value, tie.stage_mapping, "project_stage", tie, lang)
269
+
270
+ # Project type -> Project Type mapping + Project Type Translations
271
+ if key == "project type":
272
+ return _map_and_translate(raw_value, tie.project_type_mapping, "project_type", tie, lang)
273
+
274
+ # Region (no translation sheet; multi-value safe map)
275
+ if key == "region" or key == "state" or key == "province":
276
+ return _map_and_translate(raw_value, tie.region_mapping, None, tie, lang)
277
+
278
+ # Development type -> Development Type mapping + Development Type Translations
279
+ if key == "development type":
280
+ return _map_and_translate(raw_value, tie.development_type_mapping, "development_type", tie, lang)
281
+
282
+ # Ownership type / property type -> Ownership Type mapping + Property Type Translations
283
+ if key in ("ownership type", "property type"):
284
+ return _map_and_translate(raw_value, tie.ownership_type_mapping, "property_type", tie, lang)
285
+
286
+ # Capex -> USD number
287
+ if key == "capex":
288
+ n = parse_number(raw_value)
289
+ return format_capex(n, lang) if n is not None else str(raw_value)
290
+
291
+ # Capacity
292
+ if key == "capacity":
293
+ n = parse_number(raw_value)
294
+ unit = ""
295
+ if project_type_hint:
296
+ units = tie.capacity_by_type.get(_norm(project_type_hint), [])
297
+ unit = units[0] if units else ""
298
+ if n is None:
299
+ return str(raw_value)
300
+ return (format_number(n, lang, 2) + (f" {unit}" if unit else "")).strip()
301
+
302
+ # Company role-based fields
303
+ company_role_fields = {
304
+ "owner company": "PROJECT_OWNER",
305
+ "operator / concessionaire": "PROJECT_CONCESSIONAIR_OPERATOR",
306
+ "contractor company": "PROJECT_MAIN_CONTRACTOR",
307
+ "engineering company": "PROJECT_ENGINEERING",
308
+ "consultancy company": "PROJECT_CONSULTANCY",
309
+ "equipment / technology provider": "PROJECT_TECHNOLOGY_PROVIDER",
310
+ }
311
+ if key in company_role_fields:
312
+ return str(raw_value).strip()
313
+
314
+ # Default: strip
315
+ return str(raw_value).strip()
engine/translator.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Free-text translator for BNA values that BNA itself doesn't translate
3
+ (Description, Milestones, Principal works).
4
+
5
+ Three-tier pipeline (each tier short-circuits if it has an answer):
6
+
7
+ 1. Researcher overrides — the 'Free Text Overrides' sheet in
8
+ TIE_Requirements.xlsx. Lets researchers pin specific translations
9
+ for sentences they need to control. Highest priority.
10
+
11
+ 2. Persistent JSON cache — translation results from prior runs are
12
+ saved to resources/translation_cache.json so the same paragraph
13
+ is never re-translated. Cache key is sha256(text|src|dst).
14
+
15
+ 3. Live free API — MyMemory (api.mymemory.translated.net). No API
16
+ key, no signup, ~10k words/day per IP. We chunk long text at
17
+ sentence boundaries (≤450 chars per request) and rejoin.
18
+
19
+ Design choices:
20
+ - urllib only — no extra pip dependencies, no rebuild needed.
21
+ - Chunked at sentence boundaries — preserves paragraph structure.
22
+ - Graceful fallback — if API fails, return original text. Never crash.
23
+ - Source-language detection trusts the BNA-detected language we already
24
+ have at run time; falls back to 'en' if missing.
25
+ - Cache file lives next to TIE_Requirements.xlsx so it ships with
26
+ resources/ and gets updated in place.
27
+ """
28
+ from __future__ import annotations
29
+ import hashlib
30
+ import json
31
+ import os
32
+ import re
33
+ import threading
34
+ import time
35
+ import urllib.parse
36
+ import urllib.request
37
+ from typing import Dict, Optional
38
+
39
+
40
+ CACHE_FILENAME = "translation_cache.json"
41
+ CHUNK_SOFT_LIMIT = 450 # MyMemory hard cap is 500 — leave headroom
42
+ API_TIMEOUT = 8 # seconds per request
43
+ API_PAUSE = 0.10 # gentle throttle between calls
44
+ PROVIDERS = ("mymemory", "google") # try MyMemory first, fall back to Google
45
+
46
+
47
+ _lock = threading.Lock()
48
+
49
+
50
+ # ----------------------------------------------------------------------
51
+ # Cache (JSON)
52
+ # ----------------------------------------------------------------------
53
+ def _cache_path(tie_path: Optional[str]) -> Optional[str]:
54
+ if not tie_path: return None
55
+ folder = os.path.dirname(tie_path)
56
+ return os.path.join(folder, CACHE_FILENAME) if folder else None
57
+
58
+
59
+ def _load_cache(tie_path: Optional[str]) -> Dict[str, Dict[str, str]]:
60
+ p = _cache_path(tie_path)
61
+ if not p or not os.path.exists(p): return {}
62
+ try:
63
+ with open(p, "r", encoding="utf-8") as f:
64
+ return json.load(f) or {}
65
+ except Exception:
66
+ return {}
67
+
68
+
69
+ def _save_cache(tie_path: Optional[str], cache: Dict) -> None:
70
+ p = _cache_path(tie_path)
71
+ if not p: return
72
+ try:
73
+ os.makedirs(os.path.dirname(p), exist_ok=True)
74
+ tmp = p + ".tmp"
75
+ with open(tmp, "w", encoding="utf-8") as f:
76
+ json.dump(cache, f, ensure_ascii=False, indent=2)
77
+ os.replace(tmp, p)
78
+ except Exception:
79
+ pass
80
+
81
+
82
+ def _cache_key(text: str, src: str, dst: str) -> str:
83
+ h = hashlib.sha256()
84
+ h.update(f"{src}|{dst}|{text}".encode("utf-8"))
85
+ return h.hexdigest()
86
+
87
+
88
+ # ----------------------------------------------------------------------
89
+ # Researcher overrides (TIE sheet)
90
+ # ----------------------------------------------------------------------
91
+ def _override_lookup(tie, text: str, dst_lang: str) -> Optional[str]:
92
+ """Look up text in the 'Free Text Overrides' TIE sheet. Match is
93
+ exact on the trimmed English column. Returns the dst-lang cell
94
+ or None if not present."""
95
+ if tie is None or not text: return None
96
+ try:
97
+ wb = getattr(tie, "wb", None)
98
+ if wb is None or "Free Text Overrides" not in wb.sheetnames:
99
+ return None
100
+ ws = wb["Free Text Overrides"]
101
+ norm = text.strip()
102
+ col_idx = {"es": 2, "pt": 3}.get(dst_lang)
103
+ if not col_idx: return None
104
+ for i, row in enumerate(ws.iter_rows(values_only=True)):
105
+ if i == 0: continue
106
+ if not row or not row[0]: continue
107
+ if str(row[0]).strip() == norm:
108
+ v = row[col_idx - 1] if len(row) >= col_idx else None
109
+ return str(v).strip() if v else None
110
+ except Exception:
111
+ return None
112
+ return None
113
+
114
+
115
+ # ----------------------------------------------------------------------
116
+ # MyMemory free API
117
+ # ----------------------------------------------------------------------
118
+ def _mymemory(text: str, src: str, dst: str) -> Optional[str]:
119
+ """Call MyMemory translation API. Returns translated text or None
120
+ on any failure. Free, no API key, ~10k words/day per IP."""
121
+ if not text.strip(): return text
122
+ try:
123
+ params = {
124
+ "q": text,
125
+ "langpair": f"{src}|{dst}",
126
+ }
127
+ url = "https://api.mymemory.translated.net/get?" + urllib.parse.urlencode(params)
128
+ with urllib.request.urlopen(url, timeout=API_TIMEOUT) as resp:
129
+ data = json.loads(resp.read().decode("utf-8"))
130
+ # Successful response shape: {"responseData": {"translatedText": "..."}, ...}
131
+ out = ((data or {}).get("responseData") or {}).get("translatedText")
132
+ if not out: return None
133
+ # MyMemory sometimes returns the original on quota / unsupported pair.
134
+ if out.strip().lower() == text.strip().lower():
135
+ return None
136
+ return out
137
+ except Exception:
138
+ return None
139
+
140
+
141
+ def _google_translate(text: str, src: str, dst: str) -> Optional[str]:
142
+ """Call Google Translate via the unofficial public 'gtx' endpoint.
143
+ No API key required. Returns translated text or None on failure.
144
+ Used as a fallback when MyMemory is blocked / quota-exceeded."""
145
+ if not text.strip(): return text
146
+ try:
147
+ params = {
148
+ "client": "gtx",
149
+ "sl": src,
150
+ "tl": dst,
151
+ "dt": "t",
152
+ "q": text,
153
+ }
154
+ url = "https://translate.googleapis.com/translate_a/single?" + urllib.parse.urlencode(params)
155
+ req = urllib.request.Request(url, headers={
156
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
157
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
158
+ "Chrome/120.0 Safari/537.36",
159
+ })
160
+ with urllib.request.urlopen(req, timeout=API_TIMEOUT) as resp:
161
+ data = json.loads(resp.read().decode("utf-8"))
162
+ # Response shape: [[[ "translated", "src", null, null, 1 ], ...], ...]
163
+ if not isinstance(data, list) or not data or not data[0]:
164
+ return None
165
+ parts = []
166
+ for seg in data[0]:
167
+ if isinstance(seg, list) and seg and isinstance(seg[0], str):
168
+ parts.append(seg[0])
169
+ out = "".join(parts).strip()
170
+ if not out: return None
171
+ if out.lower() == text.strip().lower():
172
+ return None
173
+ return out
174
+ except Exception:
175
+ return None
176
+
177
+
178
+ # ----------------------------------------------------------------------
179
+ # Chunking
180
+ # ----------------------------------------------------------------------
181
+ def _chunks(text: str, limit: int = CHUNK_SOFT_LIMIT):
182
+ """Split long text into <=limit-char chunks at sentence/newline
183
+ boundaries. Preserves paragraph breaks for graceful rejoin."""
184
+ if not text: return []
185
+ if len(text) <= limit:
186
+ return [text]
187
+ # Split into paragraphs first
188
+ paragraphs = text.split("\n")
189
+ out = []
190
+ for para in paragraphs:
191
+ if len(para) <= limit:
192
+ out.append(para)
193
+ continue
194
+ # Sentence-aware split
195
+ parts = re.split(r"(?<=[\.\!\?])\s+", para)
196
+ buf = ""
197
+ for s in parts:
198
+ if not s: continue
199
+ if len(buf) + len(s) + 1 <= limit:
200
+ buf = (buf + " " + s).strip() if buf else s
201
+ else:
202
+ if buf: out.append(buf)
203
+ if len(s) <= limit:
204
+ buf = s
205
+ else:
206
+ # Last-resort hard split
207
+ for i in range(0, len(s), limit):
208
+ out.append(s[i:i + limit])
209
+ buf = ""
210
+ if buf: out.append(buf)
211
+ return out
212
+
213
+
214
+ def _rejoin(original: str, chunks_in, chunks_out):
215
+ """Rebuild the translated text by replacing each input chunk with
216
+ its output. Preserves the original paragraph structure."""
217
+ if not chunks_in or not chunks_out: return original
218
+ if len(chunks_in) != len(chunks_out): return original
219
+ out = original
220
+ # Replace longest-first so substring overlaps don't break replacement
221
+ pairs = sorted(zip(chunks_in, chunks_out), key=lambda x: -len(x[0]))
222
+ for src, dst in pairs:
223
+ if dst and src in out:
224
+ out = out.replace(src, dst, 1)
225
+ return out
226
+
227
+
228
+ # ----------------------------------------------------------------------
229
+ # Public entry point
230
+ # ----------------------------------------------------------------------
231
+ def translate_free_text(text: str, src_lang: str, dst_lang: str, tie=None) -> str:
232
+ """Translate `text` from src_lang to dst_lang. Returns text unchanged
233
+ on any failure. Uses overrides → cache → live API. Caller doesn't
234
+ need to wrap in try/except — every internal failure is swallowed."""
235
+ if not text or not text.strip(): return text
236
+ if not dst_lang or src_lang == dst_lang: return text
237
+
238
+ # Normalise lang codes
239
+ src = (src_lang or "en").lower()[:2]
240
+ dst = dst_lang.lower()[:2]
241
+
242
+ # 1) Researcher override
243
+ override = _override_lookup(tie, text, dst)
244
+ if override: return override
245
+
246
+ # 2) Persistent JSON cache
247
+ tie_path = getattr(tie, "path", None) if tie else None
248
+ with _lock:
249
+ cache = _load_cache(tie_path)
250
+ key = _cache_key(text, src, dst)
251
+ cached = cache.get(key)
252
+ if cached and isinstance(cached, dict) and cached.get("text"):
253
+ return cached["text"]
254
+
255
+ # 3) Live API — chunk, translate each, rejoin
256
+ chunks = _chunks(text)
257
+ out_chunks = []
258
+ failed = False
259
+ provider_errors = []
260
+ for ch in chunks:
261
+ translated = None
262
+ for prov in PROVIDERS:
263
+ if prov == "mymemory":
264
+ translated = _mymemory(ch, src, dst)
265
+ elif prov == "google":
266
+ translated = _google_translate(ch, src, dst)
267
+ if translated: break
268
+ provider_errors.append(prov)
269
+ time.sleep(API_PAUSE)
270
+ if translated is None:
271
+ failed = True
272
+ out_chunks.append(ch) # keep original chunk
273
+ else:
274
+ out_chunks.append(translated)
275
+ time.sleep(API_PAUSE)
276
+
277
+ if failed and not any(o != c for o, c in zip(out_chunks, chunks)):
278
+ # Nothing actually translated — log so the user sees that the
279
+ # free-text was passed through untranslated. Write to a sidecar
280
+ # log file next to translation_cache.json for visibility.
281
+ try:
282
+ if tie_path:
283
+ logp = os.path.join(os.path.dirname(tie_path),
284
+ "translation_failures.log")
285
+ with open(logp, "a", encoding="utf-8") as fh:
286
+ fh.write(
287
+ f"[{int(time.time())}] {src}->{dst} "
288
+ f"providers_tried={','.join(set(provider_errors))} "
289
+ f"text={text[:120]!r}\n")
290
+ except Exception:
291
+ pass
292
+ return text
293
+
294
+ rebuilt = _rejoin(text, chunks, out_chunks)
295
+ # Cache the result keyed by the FULL text (not per-chunk)
296
+ with _lock:
297
+ cache = _load_cache(tie_path)
298
+ cache[key] = {"src": src, "dst": dst, "text": rebuilt,
299
+ "ts": int(time.time())}
300
+ _save_cache(tie_path, cache)
301
+ return rebuilt