GopiBNA commited on
Commit
0ffaa98
·
verified ·
1 Parent(s): 1bcc8ba

Upload 11 files

Browse files
Files changed (3) hide show
  1. engine/batch_runner.py +55 -0
  2. engine/comparator.py +12 -8
  3. engine/scraper.py +70 -20
engine/batch_runner.py CHANGED
@@ -301,6 +301,46 @@ def run_batch(
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):
@@ -390,6 +430,21 @@ def run_batch(
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 = {
 
301
  raise RuntimeError(f"Could not extract AI ZIP: {e}")
302
  scan_dir = temp_dir
303
 
304
+ # 1b) Reorganise output_folder into two sibling sub-folders:
305
+ # <output_folder>/AI Output folder/ (verbatim copy of the AI source)
306
+ # <output_folder>/Comparer Tool Output folder/ (every artefact the engine writes)
307
+ # All downstream writes (per-project ZIPs, batch_summary.xlsx, etc.)
308
+ # go into the Comparer Tool Output folder. Web app callers re-zip the
309
+ # whole parent so the researcher's download archive has the
310
+ # two-folder layout out of the box; the desktop GUI writes to the
311
+ # same layout under whichever folder the researcher picked.
312
+ ai_copy_dir = os.path.join(output_folder, "AI Output folder")
313
+ comparer_out_dir = os.path.join(output_folder, "Comparer Tool Output folder")
314
+ try:
315
+ os.makedirs(_lp(ai_copy_dir), exist_ok=True)
316
+ os.makedirs(_lp(comparer_out_dir), exist_ok=True)
317
+ except Exception as e:
318
+ raise RuntimeError(
319
+ f"Could not create output sub-folders inside "
320
+ f"'{output_folder}': {e}")
321
+ # Copy the AI source into 'AI Output folder' so the researcher's
322
+ # download archive includes their original files alongside the
323
+ # Comparator's output.
324
+ try:
325
+ if not os.listdir(_lp(ai_copy_dir)): # only fill it the first time
326
+ for entry in os.listdir(_lp(scan_dir)):
327
+ src = os.path.join(scan_dir, entry)
328
+ dst = os.path.join(ai_copy_dir, entry)
329
+ if os.path.isdir(src):
330
+ shutil.copytree(_lp(src), _lp(dst))
331
+ else:
332
+ shutil.copy2(_lp(src), _lp(dst))
333
+ log("INFO", f"AI source copied into '{ai_copy_dir}'")
334
+ except Exception as e:
335
+ # Non-fatal: continue even if the copy step fails so the
336
+ # comparison itself isn't blocked by an OS quirk.
337
+ log("WARNING",
338
+ f"Could not copy AI source into 'AI Output folder': {e}. "
339
+ f"Comparator output will still be written.")
340
+
341
+ # Redirect all subsequent writes to the Comparer Tool Output folder
342
+ output_folder = comparer_out_dir
343
+
344
  # 2) Collect every AI Excel under scan_dir
345
  ai_files: List[str] = []
346
  for root, _, files in os.walk(scan_dir):
 
430
  if not login_ok:
431
  raise RuntimeError("BNA login failed.")
432
 
433
+ # Align BNA's UI language with the researcher's Output Language
434
+ # selection BEFORE any project page is loaded. This makes BNA
435
+ # render fields directly in the target language (es / pt), so
436
+ # extracted values like project name, descriptions, current
437
+ # stage etc. come out in the right language instead of whatever
438
+ # the account's last-used language happened to be.
439
+ if lang in ("en", "es", "pt"):
440
+ try:
441
+ log("INFO", f"Aligning BNA UI language to '{lang}'...")
442
+ sc.set_bna_language(lang)
443
+ except Exception as e:
444
+ log("WARNING",
445
+ f"Could not switch BNA UI language to '{lang}': {e}. "
446
+ f"Falling back to extract-then-translate via TIE tables.")
447
+
448
  for i, ai_path in enumerate(ai_files, 1):
449
  ai_basename = os.path.basename(ai_path)
450
  row_summary = {
engine/comparator.py CHANGED
@@ -408,8 +408,12 @@ def write_comparison_sheet(ws, rows, lang, tie, reco_only=False, project_url=Non
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 = {
@@ -423,15 +427,15 @@ def write_comparison_sheet(ws, rows, lang, tie, reco_only=False, project_url=Non
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.
 
408
  transformed_disp, lang, tie)
409
  except Exception:
410
  pass
411
+ # Free-text fields (Description / Milestones / Principal Works /
412
+ # Main Works) — machine-translate the TRANSFORMED VALUE column
413
+ # only. The AI's output is always in English, so the Transformed
414
+ # Value needs to be rendered in the researcher's selected
415
+ # Output Language. The BNA Value column is left as-extracted so
416
+ # it mirrors exactly what BNA Platform shows.
417
  try:
418
  ai_field_norm = _norm(row.get("ai_field"))
419
  FREE_TEXT_FIELDS = {
 
427
  "principal works", "obras principales", "obras principais",
428
  }
429
  if lang != "en" and ai_field_norm in FREE_TEXT_FIELDS:
430
+ # Translate the Transformed Value (AI's English → target lang)
 
 
 
 
 
431
  if transformed_disp and len(str(transformed_disp).strip()) > 20:
432
  transformed_disp = _translator.translate_free_text(
433
  str(transformed_disp), src_lang="en", dst_lang=lang, tie=tie)
434
+ # AI Value and BNA Value are intentionally NOT translated:
435
+ # - AI Value: stays as the AI Excel wrote it (English)
436
+ # - BNA Value: stays as extracted from BNA Platform
437
+ # (whatever language BNA stored — usually English,
438
+ # sometimes editor-translated)
439
  except Exception:
440
  pass
441
  # "Recommendation" column now carries the Match/Differ verdict directly.
engine/scraper.py CHANGED
@@ -89,10 +89,23 @@ class BNAScraper:
89
  "--disable-dev-shm-usage",
90
  ],
91
  )
 
 
 
 
 
 
 
 
 
 
 
92
  self._context = self._browser.new_context(
93
  ignore_https_errors=False, java_script_enabled=True,
94
  user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
95
- viewport={"width": 1440, "height": 900}, locale="en-US")
 
 
96
  # Hide the navigator.webdriver flag before any page script reads it.
97
  try:
98
  self._context.add_init_script(
@@ -416,10 +429,35 @@ class BNAScraper:
416
  try: self._page.wait_for_load_state("networkidle", timeout=30000)
417
  except Exception: pass
418
  self._page.wait_for_timeout(1500)
419
- # NOTE: BNA UI language alignment is now driven by gui.py — it
420
- # detects the mismatch BEFORE extraction and either prompts the
421
- # researcher to fix it manually (preferred) or calls
422
- # set_bna_language() as a fallback. We don't auto-switch here.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
423
  self._scroll(steps=5, pause=400)
424
  self._project_url = project_url
425
  return True
@@ -605,22 +643,34 @@ class BNAScraper:
605
  whether a date appears inline."""
606
  out = []
607
 
608
- # Strategy 1: DOM walk — accept English / Spanish / Portuguese headers
 
 
 
 
 
 
609
  try:
610
- anchor = None
611
- anchor_words = ("Milestones", "Hitos", "Marcos")
612
- sel_list = []
613
- for w in anchor_words:
614
- for tag in ("h1", "h2", "h3", "h4"):
615
- sel_list.append(f"{tag}:has-text('{w}')")
616
- sel_list += ["[class*='milestone' i] h2", "[class*='milestone' i] h3"]
617
- for sel in sel_list:
618
- loc = self._page.locator(sel).first
619
- if loc.count() > 0:
620
- anchor = loc; break
621
- if anchor is not None:
622
- for sel in ("article", "[class*='milestone' i]", "[class*='timeline' i]",
623
- "li", "p"):
 
 
 
 
 
 
624
  try: items = self._page.locator(sel).all()
625
  except Exception: items = []
626
  for it in items[:120]:
 
89
  "--disable-dev-shm-usage",
90
  ],
91
  )
92
+ # Map the user's Output Language selection to a browser locale so
93
+ # BNA's Accept-Language-based content negotiation serves the
94
+ # right variant. en-US for English, es-ES for Spanish, pt-BR for
95
+ # Portuguese (most BNA Portuguese content is Brazilian-targeted).
96
+ _locale_map = {"en": "en-US", "es": "es-ES", "pt": "pt-BR"}
97
+ _ctx_locale = _locale_map.get(self.bna_lang, "en-US")
98
+ _accept_lang = {
99
+ "en-US": "en-US,en;q=0.9",
100
+ "es-ES": "es-ES,es;q=0.9,en;q=0.5",
101
+ "pt-BR": "pt-BR,pt;q=0.9,en;q=0.5",
102
+ }[_ctx_locale]
103
  self._context = self._browser.new_context(
104
  ignore_https_errors=False, java_script_enabled=True,
105
  user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
106
+ viewport={"width": 1440, "height": 900},
107
+ locale=_ctx_locale,
108
+ extra_http_headers={"Accept-Language": _accept_lang})
109
  # Hide the navigator.webdriver flag before any page script reads it.
110
  try:
111
  self._context.add_init_script(
 
429
  try: self._page.wait_for_load_state("networkidle", timeout=30000)
430
  except Exception: pass
431
  self._page.wait_for_timeout(1500)
432
+ # Per-page language alignment safety net. BNA's language
433
+ # preference doesn't always carry over to subsequent project
434
+ # page loads, so we re-check after each navigation and re-trigger
435
+ # the dropdown click if the page rendered in the wrong language.
436
+ if self.bna_lang in ("en", "es", "pt"):
437
+ current = self.detect_bna_language()
438
+ if current and current != self.bna_lang:
439
+ self.log(
440
+ f"Project page rendered in {current.upper()} but "
441
+ f"output language is {self.bna_lang.upper()}; "
442
+ f"re-aligning before extraction."
443
+ )
444
+ try:
445
+ if self.set_bna_language(self.bna_lang):
446
+ # After the switch BNA usually reloads in-place;
447
+ # wait for that and re-navigate just to be safe
448
+ # so anchor / fragment hash state is clean.
449
+ self._page.wait_for_timeout(1500)
450
+ try:
451
+ self._page.goto(project_url,
452
+ wait_until="domcontentloaded",
453
+ timeout=30000)
454
+ self._page.wait_for_load_state(
455
+ "networkidle", timeout=20000)
456
+ except Exception:
457
+ pass
458
+ self._page.wait_for_timeout(1000)
459
+ except Exception as e:
460
+ self.log(f"Per-page lang re-align failed: {e}")
461
  self._scroll(steps=5, pause=400)
462
  self._project_url = project_url
463
  return True
 
643
  whether a date appears inline."""
644
  out = []
645
 
646
+ # Strategy 1: DOM walk SCOPED TO MILESTONE/TIMELINE CONTAINERS.
647
+ # Without scoping, the first descriptive paragraph on the page
648
+ # (usually the project Description) gets falsely identified as
649
+ # a milestone because it passes _looks_like_milestone(). Limit
650
+ # the search to elements that live inside a container whose
651
+ # class contains 'milestone' or 'timeline' — that's BNA's own
652
+ # marker for the milestones panel.
653
  try:
654
+ # If neither container exists on the page we skip Strategy 1
655
+ # entirely and let Strategy 2 (body-text anchor) handle it.
656
+ has_container = False
657
+ try:
658
+ for c_sel in ("[class*='milestone' i]", "[class*='timeline' i]"):
659
+ if self._page.locator(c_sel).first.count() > 0:
660
+ has_container = True
661
+ break
662
+ except Exception:
663
+ has_container = False
664
+
665
+ if has_container:
666
+ for sel in (
667
+ "[class*='milestone' i] article",
668
+ "[class*='milestone' i] li",
669
+ "[class*='milestone' i] p",
670
+ "[class*='timeline' i] article",
671
+ "[class*='timeline' i] li",
672
+ "[class*='timeline' i] p",
673
+ ):
674
  try: items = self._page.locator(sel).all()
675
  except Exception: items = []
676
  for it in items[:120]: