diff --git "a/engine/scraper.py" "b/engine/scraper.py" new file mode 100644--- /dev/null +++ "b/engine/scraper.py" @@ -0,0 +1,2256 @@ +"""BNA Scraper (Playwright) — robust login + tab-by-tab structured extraction.""" +from __future__ import annotations +import html as _stdhtml +import os +import re +import shutil +import tempfile +import time +import unicodedata as _ud +from typing import Callable, Dict, List, Optional, Any + + +def _strip_accents_local(s): + """Drop diacritics for case + accent insensitive company dedupe.""" + if not s: return "" + nfkd = _ud.normalize("NFKD", str(s)) + return "".join(ch for ch in nfkd if not _ud.combining(ch)) +try: + from playwright.sync_api import sync_playwright, TimeoutError as PWTimeout +except Exception: + sync_playwright = None + PWTimeout = Exception + + +EMAIL_SELECTORS = ["input[type='email']", "input[name='email']", "input[name='username']", + "input[id*='email' i]", "input[id*='user' i]", + "input[placeholder*='email' i]", "input[placeholder*='correo' i]"] +PASSWORD_SELECTORS = ["input[type='password']", "input[name='password']", + "input[id*='password' i]", "input[placeholder*='password' i]", + "input[placeholder*='contraseña' i]"] +SUBMIT_SELECTORS = ["button[type='submit']", "input[type='submit']", + "button:has-text('Log in')", "button:has-text('Login')", + "button:has-text('Sign in')", "button:has-text('Iniciar')", + "button:has-text('Ingresar')", "button:has-text('Entrar')"] +LOGGED_IN_MARKERS = ["a:has-text('Log out')", "a:has-text('Logout')", + "a:has-text('Cerrar sesión')", "[class*='user-menu']"] +ENTRY_URLS = ["https://app.bnamericas.com/", "https://app.bnamericas.com/home"] + + +def _ensure_tab(url, tab): + if "?" in url: + base = re.sub(r"([&?])tab=[^&]*", "", url).rstrip("?&") + sep = "&" if "?" in base else "?" + return f"{base}{sep}tab={tab}" + return f"{url}?tab={tab}" + + +class BNAScraper: + def __init__(self, log=print, headless=True, manual_login=False, + manual_wait_secs=180, debug_dir=None, company_chips=None, + bna_lang="en"): + self.log = log + self.headless = headless + self.manual_login = manual_login + self.manual_wait_secs = manual_wait_secs + self.debug_dir = debug_dir + # Target BNA UI language (matches user-selected output language). + # Aligned in load_project() right after the project page renders. + self.bna_lang = (bna_lang or "en").lower() + # Company chip labels to harvest under the Companies radio. List of + # exact chip labels as they appear on BNA's Companies & Contacts tab. + # Driven by the TIE 'Company Chip Mapping' sheet — gui.py builds this + # list from there. Falls back to the default 6 if not supplied. + self.company_chips = list(company_chips) if company_chips else [ + "Owner", "Concessionaire/operator", "Construction and Management", + "Engineering", "Provider", "Consultancy", + ] + self._pw = None + self._browser = None + self._context = None + self._page = None + self._temp_dir = None + self._project_url = "" + + def __enter__(self): + if sync_playwright is None: + raise RuntimeError("Playwright not installed.") + self._pw = sync_playwright().start() + self._temp_dir = tempfile.mkdtemp(prefix="bna_sess_") + # Stealth launch flags — BNamericas' Cloudflare layer silently + # rejects browsers that look automated (the navigator.webdriver + # flag is the giveaway). These flags + the init script below mask + # the most common tells without affecting normal behaviour. + self._browser = self._pw.chromium.launch( + headless=self.headless, + args=[ + "--disable-blink-features=AutomationControlled", + "--no-sandbox", + "--disable-dev-shm-usage", + ], + ) + self._context = self._browser.new_context( + ignore_https_errors=False, java_script_enabled=True, + 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", + viewport={"width": 1440, "height": 900}, locale="en-US") + # Hide the navigator.webdriver flag before any page script reads it. + try: + self._context.add_init_script( + "Object.defineProperty(navigator, 'webdriver', {get: () => undefined});" + "window.chrome = window.chrome || {runtime: {}};" + ) + except Exception: + pass + self._page = self._context.new_page() + self._page.set_default_timeout(30000) + # Network listener: stash every JSON response — BNA's frontend fetches + # project data (incl. lat/lon) via XHR. We mine those payloads later. + self._json_blobs = [] + def _on_response(resp): + try: + ct = (resp.headers or {}).get("content-type", "") + if "json" not in ct.lower(): return + u = resp.url or "" + # Skip noisy assets + if any(s in u for s in ("google", "analytics", "tracking", "sentry")): return + body = resp.text() + if body and len(body) < 2_000_000: + self._json_blobs.append((u, body)) + except Exception: + pass + try: + self._context.on("response", _on_response) + except Exception: + pass + return self + + def __exit__(self, exc_type, exc, tb): + try: + if self._context: + try: self._context.clear_cookies() + except Exception: pass + self._context.close() + if self._browser: self._browser.close() + if self._pw: self._pw.stop() + finally: + if self._temp_dir and os.path.isdir(self._temp_dir): + shutil.rmtree(self._temp_dir, ignore_errors=True) + + def _try_fill(self, selectors, value): + for sel in selectors: + try: + el = self._page.locator(sel).first + if el.count() > 0 and el.is_visible(timeout=2000): + el.fill(value, timeout=4000); return sel + except Exception: continue + return None + + def _try_click(self, selectors): + for sel in selectors: + try: + el = self._page.locator(sel).first + if el.count() > 0 and el.is_visible(timeout=2000): + el.click(timeout=4000); return sel + except Exception: continue + return None + + def _is_logged_in(self): + url = (self._page.url or "").lower() + if "login=true" in url or "/home" in url or "/project/" in url: return True + if "/login" in url or "signin" in url: return False + for sel in LOGGED_IN_MARKERS: + try: + if self._page.locator(sel).first.count() > 0: return True + except Exception: continue + return False + + def _scroll(self, steps=8, pause=400): + for _ in range(steps): + try: self._page.evaluate("window.scrollBy(0, window.innerHeight);") + except Exception: pass + self._page.wait_for_timeout(pause) + try: self._page.evaluate("window.scrollTo(0, 0);") + except Exception: pass + + def inject_cookies(self, raw: str) -> bool: + """Accept a BNAmericas session as a raw cookie string (the same + format you'd copy from DevTools → Application → Cookies). Splits + on `; ` into name=value pairs, scopes them to .bnamericas.com, + loads the home page, and confirms we're logged in. + + Returns True when the injected session is valid (the home page + renders as a signed-in user). Returns False when the cookies + don't yield a logged-in session — the caller should then fall + back to credential login. + """ + if not raw or not raw.strip(): + return False + pairs = [] + for chunk in raw.replace("\n", ";").split(";"): + chunk = chunk.strip() + if not chunk or "=" not in chunk: + continue + name, _, value = chunk.partition("=") + name = name.strip() + value = value.strip() + if not name: + continue + pairs.append({ + "name": name, "value": value, + "domain": ".bnamericas.com", "path": "/", + "secure": True, "httpOnly": False, "sameSite": "Lax", + }) + if not pairs: + self.log("No usable cookies parsed from session string.") + return False + try: + self._context.add_cookies(pairs) + except Exception as e: + self.log(f"Could not apply cookies: {e}") + return False + try: + self._page.goto(ENTRY_URLS[0], + wait_until="domcontentloaded", timeout=25000) + self._page.wait_for_timeout(1500) + except Exception as e: + self.log(f"Home-page load after cookie inject failed: {e}") + return False + for _ in range(6): + if self._is_logged_in(): + self.log("Cookie session accepted.") + return True + self._page.wait_for_timeout(1000) + self.log("Cookie session not recognised — looks expired.") + return False + + def login(self, email, password): + if self.manual_login: + return self._manual_login() + for url in ENTRY_URLS: + try: + self.log(f"Navigating to {url}") + self._page.goto(url, wait_until="domcontentloaded", timeout=25000) + self._page.wait_for_timeout(1200) + if self._page.locator(PASSWORD_SELECTORS[0]).first.count() > 0: break + except Exception as e: + self.log(f"goto {url} failed: {e}") + if self._try_fill(EMAIL_SELECTORS, email) is None: + self.log("Email field not found. Switching to manual login.") + return self._manual_login() + if self._try_fill(PASSWORD_SELECTORS, password) is None: + self.log("Password field not found.") + return False + if self._try_click(SUBMIT_SELECTORS) is None: + try: self._page.keyboard.press("Enter") + except Exception: pass + try: self._page.wait_for_load_state("networkidle", timeout=30000) + except Exception: pass + self._page.wait_for_timeout(1500) + for _ in range(8): + if self._is_logged_in(): + self.log(f"Login success. URL: {self._page.url}") + return True + self._page.wait_for_timeout(1000) + self.log(f"Login not confirmed. Final URL: {self._page.url}") + return False + + def _manual_login(self): + if self.headless: + self.log("Manual login requires visible browser.") + return False + try: self._page.goto(ENTRY_URLS[0], wait_until="domcontentloaded", timeout=20000) + except Exception: pass + self.log(f"MANUAL LOGIN: please sign in. Waiting up to {self.manual_wait_secs}s") + deadline = time.time() + self.manual_wait_secs + while time.time() < deadline: + self._page.wait_for_timeout(1500) + if self._is_logged_in(): + self.log(f"Manual login detected. URL: {self._page.url}") + return True + self.log("Manual login timed out.") + return False + + def detect_bna_language(self): + """Detect BNA UI language. Returns 'en' / 'es' / 'pt' or None. + + Tries two approaches in order: + 1. The globe-icon dropdown button (most reliable when present). + The button's text content is the 2-letter code (en/es/pt). + 2. Content fingerprinting — look for unmistakable Spanish or + Portuguese keywords in the page body. This catches cases where + the dropdown widget isn't on the page yet. + Logs every step for diagnostics. + """ + self.log("Detecting BNA UI language...") + # ---- Try 1: globe-icon dropdown button ---- + # Globe-bearing selectors come FIRST. The generic + # 'button#dropdown-basic' often matches a non-language dropdown + # (e.g. a sort/filter widget) on the page, so we only fall back + # to it as a last resort and STRICTLY validate the text. + # We also iterate ALL matches per selector (not just .first) and + # pick the one whose visible text is exactly a 2-letter code. + candidates = ( + "button.dropdown-toggle:has(.fa-globe)", + "button:has(.fa-globe)", + "button:has(svg[data-icon='globe'])", + "button:has(i.fa-globe)", + "[data-testid='dropdown-basic']:has(.fa-globe)", + "[data-testid='dropdown-basic']", + "button#dropdown-basic", + ) + for sel in candidates: + try: + loc = self._page.locator(sel) + n = loc.count() + if n == 0: + continue + for i in range(min(n, 10)): + try: + btn = loc.nth(i) + txt = (btn.inner_text(timeout=2500) or "").strip().lower() + self.log(f"BNA language widget '{sel}'[{i}] inner_text={txt!r}") + cleaned = re.sub(r"[^a-z]", "", txt) + if cleaned in ("en", "es", "pt"): + self.log(f"BNA UI language detected via widget: {cleaned.upper()}") + return cleaned + except Exception: + continue + except Exception as e: + self.log(f"BNA language widget {sel} probe error: {e}") + continue + + # ---- Try 2: content fingerprint ---- + try: + txt = (self._page.inner_text("body") or "").lower() + except Exception: + txt = "" + # Portuguese-only markers (NOT Spanish) + pt_markers = ("antiga", "compañia"[:4] + "ia", "empresas e contatos", + "última revisão", "etapa atual", "tipo de propriedade", + "tipo de desenvolvimento", "obras principais", + "vida útil", "olá") + # Spanish-only markers (NOT Portuguese) + es_markers = ("etapa actual", "tipo de propiedad", "tipo de desarrollo", + "obras principales", "última revisión", + "compañías y contactos", "compañía", "hola", + "última revisión experta") + # English markers + en_markers = ("milestones, news", "current stage", "property type", + "development type", "principal works", "lifespan") + pt_hits = sum(1 for m in pt_markers if m in txt) + es_hits = sum(1 for m in es_markers if m in txt) + en_hits = sum(1 for m in en_markers if m in txt) + self.log(f"BNA content fingerprint hits — en={en_hits}, es={es_hits}, pt={pt_hits}") + if pt_hits > es_hits and pt_hits > en_hits and pt_hits >= 1: + self.log("BNA UI language detected via content fingerprint: PT") + return "pt" + if es_hits > pt_hits and es_hits > en_hits and es_hits >= 1: + self.log("BNA UI language detected via content fingerprint: ES") + return "es" + if en_hits >= 1 and en_hits >= es_hits and en_hits >= pt_hits: + self.log("BNA UI language detected via content fingerprint: EN") + return "en" + self.log("BNA language could not be detected.") + return None + + def set_bna_language(self, target_lang): + """Switch BNA UI language to the user-selected target ('en'/'es'/'pt'). + Detects BNA's current language first; if it already matches, returns + True with no action. Otherwise opens the globe dropdown and picks the + target. Returns True on success. + + The dropdown options use a stable parenthesized code at the end of + each label: 'English (En)' / 'Inglés (En)' / 'Inglês (En)' all share + '(En)'. We match on that suffix so the click works regardless of + which language the dropdown is currently rendering its labels in. + """ + target = (target_lang or "en").lower() + if target not in ("en", "es", "pt"): target = "en" + target_code = {"en": "(En)", "es": "(Es)", "pt": "(Pt)"}[target] + current = self.detect_bna_language() + if current == target: + self.log(f"BNA UI already in {target.upper()}.") + return True + if current: + self.log(f"BNA UI is in {current.upper()}; switching to {target.upper()} to match your selection.") + else: + self.log(f"BNA language widget not found; trying to switch to {target.upper()} blindly.") + try: + for sel in ( + "[data-testid='dropdown-basic']", + "button.dropdown-toggle:has(.fa-globe)", + "button:has(.fa-globe)", + ): + try: + btn = self._page.locator(sel).first + if btn.count() == 0: continue + if not btn.is_visible(timeout=1500): continue + btn.click(timeout=3000) + self._page.wait_for_timeout(500) + for opt_sel in ( + f"text={target_code}", + f"a:has-text('{target_code}')", + f"li:has-text('{target_code}')", + f"[role='menuitem']:has-text('{target_code}')", + f"button:has-text('{target_code}')", + ): + try: + o = self._page.locator(opt_sel).first + if o.count() > 0 and o.is_visible(timeout=1500): + o.click(timeout=3000) + self._page.wait_for_timeout(2500) + self.log(f"Switched BNA UI to {target.upper()}.") + return True + except Exception: continue + break + except Exception: continue + except Exception as e: + self.log(f"set_bna_language: {e}") + self.log(f"Could not switch BNA UI; will rely on multilingual regex.") + return False + + def load_project(self, project_url): + self.log("Loading project page...") + try: self._page.goto(project_url, wait_until="domcontentloaded", timeout=45000) + except Exception as e: self.log(f"goto warning: {e}") + try: self._page.wait_for_load_state("networkidle", timeout=30000) + except Exception: pass + self._page.wait_for_timeout(1500) + # NOTE: BNA UI language alignment is now driven by gui.py — it + # detects the mismatch BEFORE extraction and either prompts the + # researcher to fix it manually (preferred) or calls + # set_bna_language() as a fallback. We don't auto-switch here. + self._scroll(steps=5, pause=400) + self._project_url = project_url + return True + + def _click_radio(self, label): + for sel in (f"label:has-text('{label}')", f"text='{label}'", + f"input[type='radio'][value*='{label.lower()}']"): + try: + el = self._page.locator(sel).first + if el.count() > 0 and el.is_visible(timeout=1500): + el.click(timeout=3000) + self._page.wait_for_timeout(800) + return True + except Exception: continue + return False + + def _extract_companies_and_contacts(self): + """Walk the unified BNA table. + Layout: + Headers: Company | Role | Website | Contact | Project position | Phone | Email + Company rows: cells[0] = name, cells[1] = "Owner Participation: 100%" + Contact rows: cells[0] = empty, cells[1] = name, cells[2] = "Pos (Mapped)" + Returns (companies_list, contacts_list). + """ + comps, contacts = [], [] + try: tables = self._page.locator("table").all() + except Exception: tables = [] + target = None + for tb in tables: + try: head = (tb.locator("thead").inner_text(timeout=1500) or "").lower() + except Exception: head = "" + if "company" in head and "role" in head and ("contact" in head or "project position" in head): + target = tb; break + if target is None: + return comps, contacts + try: rows = target.locator("tbody tr").all() + except Exception: rows = [] + for tr in rows: + try: + cells = tr.locator("td").all() + except Exception: continue + if not cells: continue + def _txt(c): + try: return (c.inner_text(timeout=1000) or "").strip() + except Exception: return "" + c0 = _txt(cells[0]) if len(cells) > 0 else "" + c1 = _txt(cells[1]) if len(cells) > 1 else "" + c2 = _txt(cells[2]) if len(cells) > 2 else "" + # Strip URLs and "Show contacts" footer + def _clean(s): + import re as _re + s = _re.split(r"(?i)\bShow\s+contacts\b", s, maxsplit=1)[0] + s = _re.sub(r"https?://\S+", " ", s) + s = _re.sub(r"\s*\(\d+\)\s*", " ", s) + lines = [l.strip() for l in s.splitlines() if l.strip()] + return lines[0].strip() if lines else "" + c0c = _clean(c0); c1c = _clean(c1); c2c = _clean(c2) + # Company row: cells[0] non-empty AND row has a company link + link_text = "" + try: + lk = cells[0].locator("a").first + if lk.count() > 0: + link_text = (lk.inner_text(timeout=900) or "").strip() + except Exception: pass + company_name = link_text or c0c + if company_name and company_name.lower() not in ("company", "role"): + # Role is in cell[1] — strip "Participation: NN%" tail + role_raw = c1c + role_clean = re.sub(r"\bParticipation:\s*\d+%?", "", role_raw, flags=re.IGNORECASE).strip() + role_clean = role_clean.split("\n")[0].strip() + if role_clean.lower() not in ("role", ""): + comps.append({"company": company_name, "role": role_clean}) + elif (not c0c) and c1c and c2c: + # Contact row: cells[1]=Name, cells[2]=Position with "(bracket)" mapped role + if c1c.lower() in ("contact", "name"): continue + contacts.append({"name": c1c, "position": c2c}) + return comps, contacts + + def _extract_role_table(self): + out = [] + URL_RE = re.compile(r"https?://\S+", re.IGNORECASE) + EMAIL_RE = re.compile(r"[\w\.-]+@[\w\.-]+") + def _clean(s): + # Truncate everything from 'Show contacts' onward (footer link) + s = re.split(r"(?i)\bShow\s+contacts\b", s, maxsplit=1)[0] + # Drop URLs / emails + s = URL_RE.sub(" ", s) + s = EMAIL_RE.sub(" ", s) + # Drop trailing counts like ' (2)' + s = re.sub(r"\s*\(\d+\)\s*", " ", s) + lines = [l.strip(" ,") for l in s.splitlines() if l.strip()] + cleaned = [l for l in lines if l.lower() not in ("company", "role", "company (2)")] + return cleaned[0].strip() if cleaned else "" + try: tables = self._page.locator("table").all() + except Exception: tables = [] + for tb in tables: + try: head_text = (tb.locator("thead").inner_text(timeout=1500) or "").lower() + except Exception: head_text = "" + if "company" not in head_text or "role" not in head_text: continue + try: rows = tb.locator("tbody tr").all() + except Exception: rows = [] + for tr in rows: + try: + cells = tr.locator("td").all() + if len(cells) < 2: continue + # Prefer the first hyperlink text inside the company cell + company = "" + try: + link = cells[0].locator("a").first + if link.count() > 0: + ltext = (link.inner_text(timeout=1200) or "").strip() + if ltext and not ltext.lower().startswith("http"): + company = ltext + except Exception: pass + if not company: + company = _clean((cells[0].inner_text(timeout=1500) or "").strip()) + role = _clean((cells[-1].inner_text(timeout=1500) or "").strip()) + if company and company.lower() not in ("company", "company (2)", "role"): + out.append({"company": company, "role": role}) + except Exception: continue + if not out: + try: txt = self._page.inner_text("body") + except Exception: txt = "" + for m in re.finditer( + r"\b(Owner|Former owner|Concessionaire/operator|Concessionaire|Operator|Main contractor|EPC|EPCM|Engineering|Consultancy|Technology provider|Equipment)\b[^\n]*\n([^\n]+)", + txt): + role = m.group(1).strip() + company = _clean(m.group(2).strip()) + if not (2 < len(company) < 200): continue + low = company.lower() + if low.startswith(("participation", "general management")): continue + if re.match(r"^(?:january|february|march|april|may|june|july|august|september|october|november|december|jan|feb|mar|apr|jun|jul|aug|sep|sept|oct|nov|dec|enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)\s+\d{4}\b", low): continue + if re.match(r"^\d{4}[-/]\d{1,2}", company): continue + if re.match(r"^(?:not yet disclosed|not disclosed|tbd|n/a)", low): continue + out.append({"company": company, "role": role}) + return out + + def _extract_contact_table(self): + out = [] + try: tables = self._page.locator("table").all() + except Exception: tables = [] + for tb in tables: + try: head_text = (tb.locator("thead").inner_text(timeout=1500) or "").lower() + except Exception: head_text = "" + if "name" not in head_text or "position" not in head_text: continue + try: rows = tb.locator("tbody tr").all() + except Exception: rows = [] + for tr in rows: + try: + cells = tr.locator("td").all() + if len(cells) < 2: continue + name = (cells[0].inner_text(timeout=1500) or "").strip() + position = (cells[-1].inner_text(timeout=1500) or "").strip() + if name: + out.append({"name": name.split("\n")[0].strip(), + "position": position.split("\n")[0].strip()}) + except Exception: continue + return out + + # ---------- Milestones ---------- + def _looks_like_milestone(self, t): + if not t: return False + if len(t) < 50 or len(t) > 4000: return False + if not re.search(r"[a-z]{3,}", t): return False + if not re.search(r"[.!?]", t): return False + # Skip nav-style or single-word labels + if re.fullmatch(r"[A-Z][A-Z\s,&]+", t.split("\n")[0]): return False + # Must contain whitespace (real sentence) + if t.count(" ") < 6: return False + return True + + def _clean_milestone(self, t): + # Strip leading date prefix if present + t = re.sub( + r"^\s*([A-Za-zÀ-ÿ]{3,9}\s+\d{1,2},?\s*\d{4}|\d{1,2}[/\.\-]\d{1,2}[/\.\-]\d{2,4}|\d{4}-\d{2}-\d{2})\s*[:\-]?\s*", + "", t) + t = re.sub(r"\s+", " ", t).strip() + return t + + def _extract_milestones(self): + """Locate Milestones section, return first substantive paragraph(s). + BNA usually shows newest first; we grab that paragraph regardless of + whether a date appears inline.""" + out = [] + + # Strategy 1: DOM walk — accept English / Spanish / Portuguese headers + try: + anchor = None + anchor_words = ("Milestones", "Hitos", "Marcos") + sel_list = [] + for w in anchor_words: + for tag in ("h1", "h2", "h3", "h4"): + sel_list.append(f"{tag}:has-text('{w}')") + sel_list += ["[class*='milestone' i] h2", "[class*='milestone' i] h3"] + for sel in sel_list: + loc = self._page.locator(sel).first + if loc.count() > 0: + anchor = loc; break + if anchor is not None: + for sel in ("article", "[class*='milestone' i]", "[class*='timeline' i]", + "li", "p"): + try: items = self._page.locator(sel).all() + except Exception: items = [] + for it in items[:120]: + try: t = (it.inner_text(timeout=900) or "").strip() + except Exception: continue + if self._looks_like_milestone(t): + cleaned = self._clean_milestone(t) + if cleaned and not any(o["text"] == cleaned for o in out): + out.append({"date": "", "text": cleaned}) + if out: break + except Exception as e: + self.log(f"DOM milestones error: {e}") + + # Strategy 2: body-text paragraph scan after 'Milestones' (en/es/pt) + def _find_anchor(txt): + for word in ("Milestones", "Hitos", "Marcos"): + idx = txt.find(word) + if idx >= 0: + return idx + len(word) + return -1 + if not out: + try: txt = self._page.inner_text("body") + except Exception: txt = "" + i = _find_anchor(txt) + if i >= 0: + tail = txt[i:] + paras = [p.strip() for p in re.split(r"\n\s*\n+", tail) if p.strip()] + for p in paras: + if self._looks_like_milestone(p): + out.append({"date": "", "text": self._clean_milestone(p)}) + break + + # Strategy 3: collapse line-by-line — the paragraph may be on adjacent + # non-blank lines that pip into one paragraph in the page's flow. + if not out: + try: txt = self._page.inner_text("body") + except Exception: txt = "" + i = _find_anchor(txt) + if i >= 0: + tail = txt[i:] + lines = [l.strip() for l in tail.splitlines()] + # Greedy: collect consecutive non-empty lines, test the joined block + buf = [] + for line in lines: + if not line: + if buf: + block = " ".join(buf) + if self._looks_like_milestone(block): + out.append({"date": "", "text": self._clean_milestone(block)}) + break + buf = [] + else: + buf.append(line) + if not out and buf: + block = " ".join(buf) + if self._looks_like_milestone(block): + out.append({"date": "", "text": self._clean_milestone(block)}) + + self.log(f"Milestones parsed: {len(out)}") + return out + + def _pick_latest_milestone(self, milestones): + if not milestones: return "" + # Page lists newest first; just take the first hit text + return (milestones[0].get("text", "") or "").strip() + + def _harvest_visible_contact_names(self): + """Return contact names whose row is currently *visible* on the page. + Strategy: find every contact-row anchor () that is + actually rendered (not display:none / hidden / aria-hidden).""" + names = [] + try: + anchors = self._page.locator("a[href*='/person/']").all() + except Exception: + anchors = [] + for a in anchors: + try: + if not a.is_visible(timeout=600): + continue + t = (a.inner_text(timeout=800) or "").strip() + if not t: continue + if t.lower() in ("name", "contact", "people"): continue + if not (2 < len(t) < 120): continue + # Skip tab/breadcrumb links by checking parent is a row/cell + if t not in names: + names.append(t) + except Exception: + continue + return names + + # Chip-name aliases — when BNA UI is in Spanish/Portuguese and the + # configured chip is English, click whichever variant the page renders. + _CHIP_ALIASES = { + "Owner": ["Owner", "Dueño", "Proprietário"], + "Concessionaire/operator": ["Concessionaire/operator", + "Concesionaria/operador", + "Concesionaria/operadora", + "Concessionária/operadora", + "Concessionária / operadora"], + "Construction and Management": ["Construction and Management", + "Construcción y gestión", + "Construção e Gestão"], + "Engineering": ["Engineering", "Ingeniería", "Ingenieria", "Engenharia"], + "Provider": ["Provider", "Proveedor", "Provedor", "Fornecedor"], + "Consultancy": ["Consultancy", "Asesoría", "Asesoria", "Consultoria"], + "All": ["All", "Todos", "Todas"], + "Engineering area": ["Engineering", "Ingeniería", "Ingenieria", "Engenharia"], + "Procurement / Purchasing": ["Procurement / Purchasing", + "Adquisiciones / Compras", + "Compras / Adquisiciones", + "Aquisições / Compras"], + "Project": ["Project", "Proyecto", "Projeto"], + } + + def _click_chip(self, label): + """Click an area chip. Tries the requested label first, then any + Spanish/Portuguese alias. Returns True on success.""" + candidates = [label] + [a for a in self._CHIP_ALIASES.get(label, []) if a != label] + for variant in candidates: + for sel in ( + f"button:has-text('{variant}')", + f"label:has-text('{variant}')", + f"a:has-text('{variant}')", + f"[role='tab']:has-text('{variant}')", + f"[role='button']:has-text('{variant}')", + f"[class*='chip' i]:has-text('{variant}')", + f"[class*='filter' i]:has-text('{variant}')", + f"[class*='tag' i]:has-text('{variant}')", + f"span:has-text('{variant}')", + ): + try: + el = self._page.locator(sel).first + if el.count() == 0: continue + if not el.is_visible(timeout=1200): continue + el.click(timeout=3000, force=True) + return True + except Exception: + continue + return False + + def _extract_managers_by_chip(self, fields): + """Bracket-parse is the PRIMARY path. The Contacts table shows the + position string ending in '(Level - Area)' for every contact (e.g. + '(Chief Executives - Engineering)', '(Managers - Project)', + '(Technicians and Professionals - Procurement / Purchasing)'). + We map Area → role: + Engineering → Engineering Manager + Project → Project Manager + Procurement / Purchasing → Purchasing Manager + + Chip filter is unreliable (BNA's printable DOM never hides rows), so + this purely-textual approach is the ground truth. Debug HTML dumps + are still saved per chip state for traceability. + """ + # Save debug dumps (best-effort, won't block primary logic) + if self.debug_dir: + try: + os.makedirs(self.debug_dir, exist_ok=True) + with open(os.path.join(self.debug_dir, "contacts_baseline.html"), + "w", encoding="utf-8") as f: + f.write(self._page.content() or "") + except Exception: pass + + # Click each chip just to capture state-changed dumps for forensics + for chip_label in ("Engineering", "Procurement / Purchasing", "Project"): + try: + if self._click_chip(chip_label): + self._page.wait_for_timeout(900) + if self.debug_dir: + fname = f"contacts_chip_{chip_label.replace(' / ', '_').replace(' ', '_')}.html" + with open(os.path.join(self.debug_dir, fname), + "w", encoding="utf-8") as f: + f.write(self._page.content() or "") + except Exception: pass + + # ---- TIER 0: highlight-company card (Owner + Project Manager) ---- + # BNA renders the OWNER company card with a curated Project chip + # showing exactly which contact is the project manager. The set + # of names is used as a FILTER on the bracket-parse output — + # never as a direct add — because the owner-card view may also + # list contacts who appear under a different chip (General + # management etc.) and would be wrong for Project Manager. + owner_pms = self._extract_owner_project_managers() + owner_pm_norm = set() + if owner_pms: + self.log(f"Owner-card Project Managers (filter set): {owner_pms}") + for n in owner_pms: + owner_pm_norm.add(re.sub(r"\s+", " ", n.strip().lower())) + + # ---- PRIMARY: bracket-parse every contact row ---- + try: + contacts = self._extract_contact_table_with_position() + except Exception as e: + self.log(f"Bracket-parse error: {e}") + contacts = [] + self.log(f"Bracket-parse contacts: {len(contacts)} rows") + + # Map managers by AREA only (level is ignored). The bracket on each + # contact's Project Position is "(Level - Area)". The Area portion + # determines the management role: + # Engineering -> Engineering Manager + # Procurement / Purchasing -> Purchasing Manager + # Project -> Project Manager + # Any level (Chief Executives, Heads, Managers, Technicians, etc.) + # qualifies as long as the area matches. This is the canonical rule + # applied across every project the application processes. + AREA_TO_ROLE = { + "engineering": "Engineering Manager", + "ingeniería": "Engineering Manager", + "ingenieria": "Engineering Manager", + "engenharia": "Engineering Manager", + "procurement / purchasing": "Purchasing Manager", + "adquisiciones / compras": "Purchasing Manager", + "compras / adquisiciones": "Purchasing Manager", + "aquisições / compras": "Purchasing Manager", + "compras / aquisições": "Purchasing Manager", + "purchasing": "Purchasing Manager", + "compras": "Purchasing Manager", + "procurement": "Purchasing Manager", + "adquisiciones": "Purchasing Manager", + "aquisições": "Purchasing Manager", + "project": "Project Manager", + "proyecto": "Project Manager", + "projeto": "Project Manager", + } + + # Each contact may appear in multiple rows on BNA's live Contacts + # view (one row per role assignment). To keep the output clean, every + # NAME is mapped to at most ONE manager role — its FIRST recognised + # role wins. This stops a person whose primary role is Engineering + # from leaking into Purchasing or Project just because they have a + # secondary assignment there. + already_assigned = {} # name_lower -> role + decisions = [] + def _norm_name_local(s): + return re.sub(r"\s+", " ", str(s or "").strip().lower()) + + for c in contacts: + pos = (c.get("position") or "").strip() + name = (c.get("name") or "").strip() + if not name or name.lower() in ("name", "contact", "people"): continue + brackets = re.findall(r"\(([^()]+)\)", pos) + if not brackets: + decisions.append((name, pos, "skip: no bracket")) + continue + # Use the FIRST bracket — represents the contact's primary role. + bracket = re.sub(r"\s+", " ", brackets[0].strip()) + if " - " in bracket: + area = bracket.split(" - ", 1)[1].strip() + else: + area = bracket.strip() + role = AREA_TO_ROLE.get(area.lower()) + if not role: + decisions.append((name, pos, f"skip: area '{area}' not a target")) + continue + nk = _norm_name_local(name) + if nk in already_assigned: + # Name already mapped to a (possibly different) role — keep + # the first assignment, drop this duplicate row. + prev = already_assigned[nk] + decisions.append((name, pos, f"skip: already '{prev}', this row says '{role}'")) + continue + # When the owner-card filter set is non-empty, only allow + # Project Manager assignments for names that ALSO appear in + # that curated set. This combines bracket-area="Project" + # AND BNA's own curation, avoiding both over-inclusion + # (Choquequirao case) and under-inclusion (Hombre Muerto). + if role == "Project Manager" and owner_pm_norm: + if nk not in owner_pm_norm: + decisions.append((name, pos, "skip: bracket says Project Manager but not in owner-card")) + continue + already_assigned[nk] = role + fields.setdefault(f"manager::{role}", []).append(name) + decisions.append((name, pos, f"assigned: {role}")) + + # Log + persist decisions for traceability across all future projects + for role in ("Project Manager", "Purchasing Manager", "Engineering Manager"): + v = fields.get(f"manager::{role}", []) + self.log(f"{role}: {', '.join(v) if v else '(none)'}") + if self.debug_dir: + try: + with open(os.path.join(self.debug_dir, "manager_decisions.txt"), + "w", encoding="utf-8") as f: + for n, p, d in decisions: + f.write(f"NAME={n} | POS={p} | DECISION={d}\n") + except Exception: pass + + def _extract_all_companies_with_roles(self): + """Return [{'company', 'role'}] for every company on the Companies + & Contacts tab. BNA renders this section in THREE layouts: + + (A0) Highlighted Owner card — `
` + with role in and company in `a.fw-bold`. Used by the + Spanish/Portuguese live UI for the primary owner. + (A) Live UI list — `
` blocks. + (B) Printable / table — header may be 'Company/Role' (en), + 'Compañía/Rol' (es) or 'Empresa/Função' (pt). + """ + out = [] + # ---------- (A0) highlight-company cards ---------- + try: + cards = self._page.locator(".highlight-company").all() + except Exception: + cards = [] + for card in cards: + try: + role = "" + bs = card.locator("b").all() + for b in bs: + t = (b.inner_text(timeout=800) or "").strip() + if t and t.lower() not in ("show contacts", "mostrar contactos"): + role = t; break + company = "" + links = card.locator("a.fw-bold[href*='/company/']").all() + if not links: + links = card.locator("a[href*='/company/']").all() + for lk in links: + t = (lk.inner_text(timeout=800) or "").strip() + if t and not t.lower().startswith("http"): + company = re.sub(r"\s+", " ", t).strip(); break + if company: + out.append({"company": company, "role": role}) + except Exception: + continue + + # ---------- (A) list-collapsed__item layout ---------- + # Note: tiers A and B both run and append to `out`. Dedup at the + # end. Earlier code returned after A which made tier B unreachable + # whenever ANY list-collapsed__item existed; we now always run + # both so the printable table fallback can rescue companies the + # live UI hides behind chip filters. + try: + items = self._page.locator("[class*='list-collapsed__item']").all() + except Exception: + items = [] + if items: + for item in items: + # Company name: first /company/ link inside this item + company = "" + try: + link = item.locator("a[href*='/company/']").first + if link.count() > 0: + t = (link.inner_text(timeout=800) or "").strip() + if t and not t.lower().startswith("http"): + company = re.sub(r"\s+", " ", t).strip() + except Exception: pass + if not company: + continue + + # Role: the px-2 (or 30% width) sub-div has the role text. + # Try multiple selectors for resilience. + role = "" + for sel in ( + "div.px-2", + "div[class*='px-2']", + "div[style*='width: 30%']", + "div[style*='width:30%']", + ): + try: + loc = item.locator(sel).first + if loc.count() > 0: + t = (loc.inner_text(timeout=800) or "").strip() + if t: + # Strip "Participation: 100%" trailer + t = re.split(r"(?i)\bParticipa(?:tion|ción|cion|ção|cao):", t)[0].strip() + role = t.split("\n")[0].strip() + break + except Exception: continue + + # Last-resort: scan the item's full text and pick the first + # non-URL, non-link line that isn't "Show contacts" or the + # company name itself. + if not role: + try: full = item.inner_text(timeout=800) or "" + except Exception: full = "" + lines = [l.strip() for l in full.splitlines() if l.strip()] + for l in lines: + if l == company: continue + if re.match(r"(?i)^\s*show\s+contacts\b", l): continue + if l.lower().startswith("http"): continue + if l.lower() in ("follow", "participation"): continue + role = re.split(r"(?i)\bParticipa(?:tion|ción|cion|ção|cao):", l)[0].strip() + break + + out.append({"company": company, "role": role}) + # NOTE: don't return here — tier B (the PDF / printable + # table) often holds extra companies the live UI hides + # behind chip filters. Keep going. + + # ---------- (B) table fallback ---------- + try: tables = self._page.locator("table").all() + except Exception: tables = [] + target = None + for tb in tables: + try: head = (tb.locator("thead").inner_text(timeout=1500) or "").lower() + except Exception: head = "" + company_token = any(k in head for k in ("company", "compañía", "compania", "compañia", "empresa", "empresas")) + role_token = any(k in head for k in ("role", "rol", "função", "funcao")) + if company_token and role_token: + target = tb; break + # Walk EVERY descendant tr — including those inside nested tables. + # If Tier B couldn't lock on a labelled table, skip this walk + # entirely. Tier C (static-HTML orphan-tbody rescue) below works + # off the raw page HTML and will catch the rows on its own. + rows = [] + if target is not None: + try: rows = target.locator("tr").all() + except Exception: rows = [] + for tr in rows: + try: + # Skip rows that wrap a nested table (the inner rows are + # already captured separately). + if tr.locator("table").count() > 0: + continue + except Exception: pass + try: cells = tr.locator("td").all() + except Exception: continue + if len(cells) < 2: continue + company = "" + try: + lk = cells[0].locator("a[href*='/company/']").first + if lk.count() > 0: + t = (lk.inner_text(timeout=900) or "").strip() + if t and not t.lower().startswith("http"): + company = t.split("\n")[0].strip() + except Exception: pass + if not company: + try: raw = (cells[0].inner_text(timeout=900) or "").strip() + except Exception: raw = "" + raw = re.split(r"(?i)\b(?:Show\s+contacts|Mostrar\s+contactos|Mostrar\s+contatos)\b", raw, maxsplit=1)[0] + raw = re.sub(r"https?://\S+", " ", raw) + raw = re.sub(r"\s*\(\d+\)\s*", " ", raw) + lines = [l.strip() for l in raw.splitlines() if l.strip()] + lines = [l for l in lines if l.lower() not in ("company", "role", "contact")] + if lines: company = lines[0] + if not company: continue + if re.match(r"(?i)^\s*show\s+contacts\b", company): continue + role = "" + for c in cells[1:]: + try: t = (c.inner_text(timeout=900) or "").strip() + except Exception: t = "" + if not t: continue + if t.lower().startswith("http"): continue + if re.match(r"(?i)^\s*show\s+contacts\b", t): continue + t = re.split(r"(?i)\bParticipa(?:tion|ción|cion|ção|cao):", t)[0].strip() + role = t.split("\n")[0].strip() + break + out.append({"company": company, "role": role}) + + # ---------- (C) orphan-tbody rescue ---------- + # BNA's PT/ES print HTML sometimes closes the companies table after + # the FIRST data row and emits each subsequent company as a sibling + # after . Browsers don't always reparent these so + # target.locator("tr") misses them. + # + # NOTE: Walking every on the page via Playwright is slow + # (each handle call is a round-trip). On pages with many tables + # this could take long enough to break downstream tabs. So we do + # the orphan-tbody rescue via the static HTML pulled in one shot + # — no per-element Playwright calls. + try: + page_html = self._page.content() or "" + except Exception: + page_html = "" + if page_html: + try: + # Pull every tr that has at least 2 cells and a /company/ + # link in cell 0. Cap iterations as a safety net. + tr_pat = re.compile(r"]*>([\s\S]*?)", re.IGNORECASE) + td_pat = re.compile(r"]*>([\s\S]*?)", re.IGNORECASE) + link_pat = re.compile( + r']+href=["\'][^"\']*?/company/[^"\']*?["\'][^>]*?>([\s\S]*?)', + re.IGNORECASE) + tag_strip = re.compile(r"<[^>]+>") + import html as _html + seen_orphan = set() + count = 0 + for tr_m in tr_pat.finditer(page_html): + count += 1 + if count > 500: # safety cap + break + inner = tr_m.group(1) + if " &, " -> ", ' -> ') + # BEFORE strip + collapse so 'Neoingeniería P&T' + # collapses to 'Neoingeniería P&T' and dedupes against + # the live-DOM-captured 'Neoingeniería P&T' copy. + company = _html.unescape(lk.group(1)) + company = re.sub(r"\s+", " ", tag_strip.sub(" ", company)).strip() + if not company: + continue + if re.match(r"(?i)^\s*show\s+contacts\b", company): + continue + # Role from cell 1 + role_html = _html.unescape(tds[1]) + role = re.sub(r"\s+", " ", tag_strip.sub(" ", role_html)).strip() + role = re.split(r"(?i)\bParticipa(?:tion|ción|cion|ção|cao):", role)[0].strip() + role = role.split("\n")[0].strip() + key = (company.lower(), role.lower()) + if key in seen_orphan: + continue + seen_orphan.add(key) + out.append({"company": company, "role": role}) + except Exception as e: + self.log(f"Orphan-tbody rescue error: {e}") + + # De-dupe by (company, role) — multiple tiers may emit the same row + seen = set(); deduped = [] + for r in out: + key = (re.sub(r"\s+", " ", str(r.get("company", "")).strip().lower()), + re.sub(r"\s+", " ", str(r.get("role", "")).strip().lower())) + if key in seen: continue + seen.add(key); deduped.append(r) + return deduped + + @staticmethod + def _chip_for_role(role_text): + """Map a BNA role string to the chip bucket it belongs to. + Accepts English / Spanish / Portuguese role text. Returns None if no + recognized term is found. + + BNA usually formats role cells as ' - '. + Classification MUST run on the role label only — running it on + the full text causes false positives (e.g. 'Feasibility study - + Cooperation agreement for engineering and construction of a + pilot plant' would wrongly match Engineering on the word + 'engineering' inside the description). Trim on first ' - '. + """ + if not role_text: return None + r_full = re.sub(r"\s+", " ", str(role_text).lower()).strip() + if not r_full: return None + # Use only the head (before ' - ' / ' — '). Em-dash and en-dash also. + r = re.split(r"\s+[-–—]\s+", r_full, maxsplit=1)[0].strip() + if not r: r = r_full + # Owner / Dueño / Proprietário + if (r == "owner" or r.startswith("owner ") or r.startswith("owners") + or r == "dueño" or r == "dueno" or r.startswith("dueño ") + or r.startswith("propietario") or r.startswith("proprietário") + or r.startswith("proprietario")): + return "Owner" + # Concessionaire / Operator (en/es/pt) + if any(k in r for k in ("concessionaire", "operator", + "concesionari", "concesionario", "operador", + "concessionári", "concessionario", "operador")): + return "Concessionaire/operator" + # Construction and management — en/es/pt + sub-roles + if any(k in r for k in ( + "construction and management", + "construcción y gestión", "construccion y gestion", + "construção e gestão", "construcao e gestao", + "main contractor", + "contratista principal", "contratante principal", + "epc", + "main works constructor", "constructora obras principales", + "construtor das obras principais", + "complementary works", "obras complementarias", "obras complementares", + "construction management", + "gestión de la construcción", "gestao da construcao", + "gestão de construção", + )): + return "Construction and Management" + # Engineering / Ingeniería / Engenharia + if ("engineering" in r or "ingeniería" in r or "ingenieria" in r + or "engenharia" in r + or r == "feed" or r.startswith("feed ")): + return "Engineering" + # Provider / Proveedor / Provedor / Fornecedor / Supplier + if any(k in r for k in ( + "provider", "supplier", + "proveedor", "provedor", "fornecedor", + )): + return "Provider" + # Consultancy / Asesoría / Consultoria + technical advisory & studies. + # NOTE: Financial Advisor and Legal Advisor are intentionally NOT + # mapped here — BNA exposes them as their own chips and including + # them under Consultancy pollutes the consultancy list with + # banks / law firms that the AI side never lists as consultants. + if any(k in r for k in ( + "consultancy", "consultant", + "asesoría técnica", "asesoria tecnica", "consultoría", "consultoria", + "feasibility study", "estudio de factibilidad", "estudo de viabilidade", + "prefeasibility study", "estudio de prefactibilidad", "estudo de pré-viabilidade", + "preliminary economic assessment", "pea", + "evaluación económica preliminar", "avaliação econômica preliminar", + "environmental study", "estudio ambiental", "estudo ambiental", + "prospecting services", "servicios de prospección", "serviços de prospecção", + "resources/reserves estimation", + "estimación de recursos", "estimativa de recursos", + )): + return "Consultancy" + return None + + def _extract_latlon_from_page(self, fields): + """Extract project Latitude/Longitude from the current page. + Strategy (try in order, take FIRST plausible match): + 1. Google Static Maps img: 'staticmap?...center=LAT,LON' + 2. Generic '?center=LAT,LON' in any URL on the page + 3. 'q=LAT,LON' or '@LAT,LON' (Google Maps share-style) + 4. data-lat / data-lng attributes + 5. JSON 'lat':X,'lng':Y in any embedded script + + On success writes Latitude, Longitude, Coordinates AND the AI + field key 'Latitude and Longitude' for direct lookup. + Logs every attempt, persists a latlon_debug.txt for traceability. + """ + attempts = [] + try: page_html = self._page.content() or "" + except Exception: page_html = "" + try: page_text = self._page.inner_text("body") or "" + except Exception: page_text = "" + + sources = [("page.content()", page_html), + ("page.inner_text('body')", page_text)] + # Also include captured XHR JSON blobs + try: + for u, body in (self._json_blobs or [])[-30:]: + sources.append((f"xhr:{u[-50:]}", body)) + except Exception: pass + + patterns = [ + ("staticmap center", r"staticmap\?[^\"']*?center=(-?\d{1,3}\.\d+),(-?\d{1,3}\.\d+)"), + ("?center=", r"[?&]center=(-?\d{1,3}\.\d+),(-?\d{1,3}\.\d+)"), + ("?ll=", r"[?&]ll=(-?\d{1,3}\.\d+),(-?\d{1,3}\.\d+)"), + ("?q=", r"[?&]q=(-?\d{1,3}\.\d+),(-?\d{1,3}\.\d+)"), + ("@lat,lon", r"@(-?\d{1,3}\.\d+),(-?\d{1,3}\.\d+)"), + ("markers", r"markers=color:[^&]+%7C(-?\d{1,3}\.\d+),(-?\d{1,3}\.\d+)"), + ("data-lat/lng", r"data-lat[\"']?=[\"']?(-?\d{1,3}\.\d+).*?data-l(?:ng|on|ongitude)[\"']?=[\"']?(-?\d{1,3}\.\d+)"), + ('"lat":n,"lng":n', r"[\"']lat(?:itude)?[\"']\s*:\s*(-?\d{1,3}\.\d+)[^\d-]+[\"']l(?:o?n|ong|ongitude)[\"']\s*:\s*(-?\d{1,3}\.\d+)"), + ] + + found = None + for name, src in sources: + for label, pat in patterns: + try: + m = re.search(pat, src, re.IGNORECASE | re.DOTALL) + except Exception: + continue + if not m: continue + lat_s, lon_s = m.group(1), m.group(2) + try: + la = float(lat_s); lo = float(lon_s) + except ValueError: + continue + if not (-90 <= la <= 90 and -180 <= lo <= 180): + attempts.append((name, label, f"out-of-range {la},{lo}")) + continue + attempts.append((name, label, f"FOUND {lat_s},{lon_s}")) + found = (lat_s, lon_s) + break + if found: break + + if found: + lat, lon = found + fields["Latitude"] = lat + fields["Longitude"] = lon + fields["Coordinates"] = f"{lat}, {lon}" + # Also store with the canonical AI field name for direct lookup + fields["Latitude and Longitude"] = f"{lat}, {lon}" + self.log(f"Coordinates: {lat}, {lon}") + else: + self.log("Lat/Lon not found in page content.") + + # Persist debug log + if self.debug_dir: + try: + os.makedirs(self.debug_dir, exist_ok=True) + with open(os.path.join(self.debug_dir, "latlon_debug.txt"), + "w", encoding="utf-8") as f: + f.write(f"Found: {found}\n\n") + for n, label, dec in attempts: + f.write(f" source={n} | pattern={label} | {dec}\n") + if not attempts: + f.write("(no attempts logged - all patterns missed)\n") + # Also dump first 500 chars of the page HTML containing 'center=' + try: + i = page_html.lower().find("center=") + if i >= 0: + ctx = page_html[max(0, i - 200):i + 300] + with open(os.path.join(self.debug_dir, "latlon_context.html"), + "w", encoding="utf-8") as f: + f.write(ctx) + except Exception: pass + except Exception: pass + + def _extract_companies_under_chip(self): + """After a chip is clicked, find the visible Company-column values. + Strategy: + - Locate the table whose header includes 'Company' and 'Role'. + - Walk visible rows; pull the Company cell text (or its link). + - Stop appending the moment a row's text starts with 'Show contacts' + (case-insensitive); do NOT include that row. + Returns a list of unique company names (preserve order). + """ + names = [] + try: tables = self._page.locator("table").all() + except Exception: tables = [] + target = None + for tb in tables: + try: head = (tb.locator("thead").inner_text(timeout=1500) or "").lower() + except Exception: head = "" + company_token = any(k in head for k in ("company", "compañía", "compania", "compañia", "empresa", "empresas")) + role_token = any(k in head for k in ("role", "rol", "função", "funcao")) + if company_token and role_token: + target = tb; break + if target is None: + return names + try: rows = target.locator("tbody tr").all() + except Exception: rows = [] + for tr in rows: + try: + row_text = (tr.inner_text(timeout=1000) or "").strip() + except Exception: + row_text = "" + # Stop sentinel: rows that begin with "Show contacts" + if re.match(r"(?i)^\s*(?:show\s+contacts|mostrar\s+contactos|mostrar\s+contatos)\b", row_text): + break + try: + cells = tr.locator("td").all() + except Exception: + continue + if not cells: + continue + # Company name lives in the first cell. Prefer the link text. + company = "" + try: + lk = cells[0].locator("a").first + if lk.count() > 0: + t = (lk.inner_text(timeout=900) or "").strip() + if t and not t.lower().startswith("http"): + company = t.split("\n")[0].strip() + except Exception: pass + if not company: + try: + raw = (cells[0].inner_text(timeout=900) or "").strip() + except Exception: + raw = "" + # Strip URLs and "Show contacts" footer + raw = re.split(r"(?i)\b(?:Show\s+contacts|Mostrar\s+contactos|Mostrar\s+contatos)\b", raw, maxsplit=1)[0] + raw = re.sub(r"https?://\S+", " ", raw) + # Drop trailing counts like " (2)" + raw = re.sub(r"\s*\(\d+\)\s*", " ", raw) + lines = [l.strip() for l in raw.splitlines() if l.strip()] + # Reject header rows + lines = [l for l in lines if l.lower() not in ("company", "role")] + if lines: + company = lines[0] + if not company: + continue + if re.match(r"(?i)^\s*show\s+contacts\b", company): + break + if company not in names: + names.append(company) + return names + + def _extract_companies_by_chip(self, fields): + """Populate fields['company::'] for every chip in self.company_chips. + + Strategy: + PRIMARY - read every row in the unfiltered All-table; classify each + company by its Role text (no chip click required). This + is the ground-truth path because BNA's role text is + always shown. + SECONDARY- if the All parse returns nothing, fall back to per-chip + click + parse. This rescues edge cases where the All + table isn't rendered as expected. + + Decisions are persisted to company_decisions.txt for traceability. + """ + if self.debug_dir: + try: + os.makedirs(self.debug_dir, exist_ok=True) + with open(os.path.join(self.debug_dir, "companies_baseline.html"), + "w", encoding="utf-8") as f: + f.write(self._page.content() or "") + except Exception: pass + + decisions = [] + + # Make sure 'All' chip is selected so every row is visible. + try: + self._click_chip("All") + self._page.wait_for_timeout(800) + except Exception: pass + try: self._scroll(steps=3, pause=300) + except Exception: pass + + # Pre-seed every configured chip with an empty list so the comparator + # always finds the key (avoids "Not Available" when chip simply has + # no companies on this project). + for chip_label in self.company_chips: + fields.setdefault(f"company::{chip_label}", []) + + # ---- PRIMARY: All-table parse + role-based grouping ---- + rows = self._extract_all_companies_with_roles() + self.log(f"All-table: {len(rows)} company rows.") + if rows: + for row in rows: + chip = self._chip_for_role(row.get("role", "")) + if not chip: + decisions.append(("(unmapped)", row.get("company", ""), + row.get("role", ""), "no chip mapping")) + continue + bucket_key = f"company::{chip}" + # Try to match chip to one of the configured chip names — + # case-insensitive. If not found, still create the bucket. + target_chip = chip + for cfg in self.company_chips: + if cfg.lower() == chip.lower(): + target_chip = cfg; break + bucket_key = f"company::{target_chip}" + fields.setdefault(bucket_key, []) + # Case + accent + entity insensitive dedupe so the same + # company captured by multiple tiers (live DOM + static + # HTML rescue, with or without & entities) only + # appears once in the final list. + cname = row["company"] + cnorm = re.sub(r"\s+", " ", + _strip_accents_local(cname).lower() + ).strip() + existing_norms = { + re.sub(r"\s+", " ", + _strip_accents_local(x).lower()).strip() + for x in fields[bucket_key] + } + if cnorm and cnorm not in existing_norms: + fields[bucket_key].append(cname) + decisions.append((target_chip, row["company"], row.get("role", ""), + "assigned via All-table")) + else: + # ---- SECONDARY: per-chip click + parse ---- + self.log("All-table empty; falling back to per-chip click harvest.") + for chip_label in self.company_chips: + ok = self._click_chip(chip_label) + if not ok: + decisions.append((chip_label, "(none)", "(none)", "chip not clickable")) + continue + self._page.wait_for_timeout(1200) + try: self._scroll(steps=2, pause=300) + except Exception: pass + names = self._extract_companies_under_chip() + fields[f"company::{chip_label}"] = names + for n in names: + decisions.append((chip_label, n, "(per-chip)", "harvested")) + if self.debug_dir: + try: + fname = "companies_chip_" + re.sub(r"[^A-Za-z0-9]+", "_", + chip_label).strip("_") + ".html" + with open(os.path.join(self.debug_dir, fname), + "w", encoding="utf-8") as f: + f.write(self._page.content() or "") + except Exception: pass + + # Log final per-chip results + for chip_label in self.company_chips: + v = fields.get(f"company::{chip_label}", []) + self.log(f"Chip '{chip_label}': {len(v)} companies -> {v}") + + if self.debug_dir: + try: + with open(os.path.join(self.debug_dir, "company_decisions.txt"), + "w", encoding="utf-8") as f: + for chip, comp, role, decision in decisions: + f.write(f"CHIP={chip} | COMPANY={comp} | ROLE={role} | DECISION={decision}\n") + except Exception: pass + + def _extract_owner_project_managers(self): + """Extract Project Manager(s) shown in BNA's curated owner card + (`
`). The card contains: + - Proprietário|Owner|Propietario (role tag) + - Owner company name + - (filter chip) + - Person name (the project manager) + + Returns list of person names extracted, [] if none. + Static-HTML regex pass to keep it fast and not block on Playwright.""" + names = [] + try: + html = self._page.content() or "" + except Exception: + return names + if not html or "highlight-company" not in html: + return names + try: + # Capture each highlight-company block + card_pat = re.compile( + r']*class="[^"]*highlight-company[^"]*"[^>]*>([\s\S]*?)(?=]*class="[^"]*highlight-company|
\s*
\s*]*class="mb-3|$)', + re.IGNORECASE) + person_link_pat = re.compile( + r']+href="[^"]*?/person/[^"]*?"[^>]*>([\s\S]*?)', + re.IGNORECASE) + tag_strip = re.compile(r"<[^>]+>") + for cm in card_pat.finditer(html): + block = cm.group(1) + # Look for the chip label that signals project filter + # (case-insensitive, multilingual). The presence of any one + # of these markers indicates the contacts below are + # project-related. + if not re.search(r"\b(?:Project|Proyecto|Projeto)\s*\(\d+\)", + block, re.IGNORECASE): + continue + import html as _html2 + for pm in person_link_pat.finditer(block): + raw = _html2.unescape(pm.group(1)) + name = re.sub(r"\s+", " ", tag_strip.sub(" ", raw)).strip() + if name and name not in names: + names.append(name) + except Exception as e: + self.log(f"Owner-card PM extraction error: {e}") + return names + + + def _extract_contact_table_with_position(self): + """Walk every on the contacts view; return rows where one cell + carries a person name and another cell carries the position string + ending in '(Level - Area)'. Robust to header drift and multi-line + cells (the bracket may sit on its own line in inner_text).""" + out = [] + try: rows = self._page.locator("tr").all() + except Exception: rows = [] + for tr in rows: + try: + cells = tr.locator("td").all() + except Exception: continue + if len(cells) < 2: continue + texts = [] + for cell in cells: + try: t = (cell.inner_text(timeout=600) or "").strip() + except Exception: t = "" + if t: texts.append(t) + if len(texts) < 2: continue + # Position cell: the FIRST cell containing a "( ... - ... )" bracket + position = "" + position_idx = -1 + for idx, t in enumerate(texts): + # Flatten newlines for bracket detection + flat = re.sub(r"\s+", " ", t) + if re.search(r"\([^()]+ - [^()]+\)", flat): + position = flat + position_idx = idx + break + # Name cell: the cell BEFORE the position cell (typical order: + # Name | Position | Phone | Email) + if position_idx > 0: + name_raw = texts[position_idx - 1] + else: + name_raw = texts[0] + # If first cell has no person, scan forward for one that does + # (skip pure phone / email cells) + for t in texts: + low = t.lower() + if "@" in low or re.fullmatch(r"[\d\-\s\.\(\)\+]+", t.strip()): + continue + name_raw = t; break + name = name_raw.split("\n")[0].strip() + # Reject phone/email-only or junk cells + if not name: continue + if "@" in name: continue + if re.fullmatch(r"[\d\-\s\.\(\)\+]+", name): continue + if name.lower() in ("name", "contact", "company", "role"): continue + # If we still don't have a position, fall back to the cell + # immediately after the name cell + if not position and len(texts) >= 2: + position = re.sub(r"\s+", " ", texts[1]) + out.append({"name": name, "position": position}) + return out + + def extract_fields(self): + fields = {} + url = self._project_url or self._page.url + + # Companies & Contacts + try: + cc_url = _ensure_tab(url, "companies-contacts") + self.log(f"Loading Companies & Contacts: {cc_url}") + self._page.goto(cc_url, wait_until="domcontentloaded", timeout=30000) + try: self._page.wait_for_load_state("networkidle", timeout=20000) + except Exception: pass + self._page.wait_for_timeout(1200) + self._click_radio("Companies") + self._page.wait_for_timeout(800) + self._scroll(steps=4, pause=300) + # NEW canonical path: chip-by-chip harvest into company:: + self._extract_companies_by_chip(fields) + # Lat/Lon — BNA renders a Google Static Maps thumbnail on the + # Companies & Contacts page. The img URL contains + # '?center=LAT,LON'. Pull it from the page content directly. + self._extract_latlon_from_page(fields) + # Legacy: also keep the unified contacts list parsed from the + # Companies-radio table (used downstream by managers if needed). + try: + _, contacts_unified = self._extract_companies_and_contacts() + except Exception: + contacts_unified = [] + self._click_radio("Contacts") + self._page.wait_for_timeout(1200) + self._scroll(steps=4, pause=300) + self._extract_managers_by_chip(fields) + except Exception as e: + self.log(f"Companies & Contacts extraction error: {e}") + + # Milestones + try: + ms = [] + for slug in ("milestones-news-reports", "milestones", "milestones-news", + "hitos-noticias-reportes", "hitos", "marcos-noticias-relatorios", "marcos"): + ms_url = _ensure_tab(url, slug) + self.log(f"Loading Milestones tab: {ms_url}") + self._page.goto(ms_url, wait_until="domcontentloaded", timeout=30000) + try: self._page.wait_for_load_state("networkidle", timeout=20000) + except Exception: pass + self._page.wait_for_timeout(1500) + self._scroll(steps=8, pause=500) + # Always dump for inspection + if self.debug_dir: + try: + os.makedirs(self.debug_dir, exist_ok=True) + with open(os.path.join(self.debug_dir, "milestones_text.txt"), "w", encoding="utf-8") as f: + f.write(self._page.inner_text("body") or "") + with open(os.path.join(self.debug_dir, "milestones_page.html"), "w", encoding="utf-8") as f: + f.write(self._page.content() or "") + self.log(f"Saved milestones debug dump in {self.debug_dir}") + except Exception as de: + self.log(f"Milestones debug save error: {de}") + ms = self._extract_milestones() + if ms: break + if ms: + latest_text = self._pick_latest_milestone(ms) + fields["Milestones"] = latest_text + self.log(f"Latest milestone: {latest_text[:200]}") + else: + self.log("No milestones found.") + except Exception as e: + self.log(f"Milestones extraction error: {e}") + + # Latitude / Longitude — out-of-the-box: scan RAW HTML + iframe srcs + JSON state + try: + lat = lon = None + + def _try(text): + if not text: return None, None + # 1) Standard label-based pair (full precision) + m = re.search( + r"latitud[ey]?\s*[:=]?\s*([+-]?\d+\.\d{2,})[^\d+\-]+longitud[ey]?\s*[:=]?\s*([+-]?\d+\.\d{2,})", + text, re.IGNORECASE) + if m: return m.group(1), m.group(2) + # 2) Reversed order (lng first) + m = re.search( + r"longitud[ey]?\s*[:=]?\s*([+-]?\d+\.\d{2,})[^\d+\-]+latitud[ey]?\s*[:=]?\s*([+-]?\d+\.\d{2,})", + text, re.IGNORECASE) + if m: return m.group(2), m.group(1) + # 3) Single labels split anywhere + la = re.search(r"latitud[ey]?\s*[:=]?\s*([+-]?\d+\.\d{2,})", text, re.IGNORECASE) + lo = re.search(r"longitud[ey]?\s*[:=]?\s*([+-]?\d+\.\d{2,})", text, re.IGNORECASE) + if la and lo: return la.group(1), lo.group(1) + # 4) JSON-style: "lat":-23.44, "lng":-70.08 (or lon, longitude) + m = re.search( + r"[\"']lat(?:itude)?[\"']\s*:\s*([+-]?\d+\.\d{2,})[^\d]+[\"']l(?:o?n|ong|ongitude)[\"']\s*:\s*([+-]?\d+\.\d{2,})", + text) + if m: return m.group(1), m.group(2) + # 5) HTML data-attributes: data-lat="X" data-lng="Y" + la2 = re.search(r"data-l(?:at|atitude)\s*=\s*[\"']([+-]?\d+\.\d{2,})[\"']", text, re.IGNORECASE) + lo2 = re.search(r"data-l(?:ng|on|ongitude)\s*=\s*[\"']([+-]?\d+\.\d{2,})[\"']", text, re.IGNORECASE) + if la2 and lo2: return la2.group(1), lo2.group(1) + # 6) Google Maps URL pattern: q=lat,lng or center=lat,lng or @lat,lng, + m = re.search(r"(?:[?&](?:q|center|ll)=|@)([+-]?\d{1,3}\.\d{2,}),\s*([+-]?\d{1,3}\.\d{2,})", text) + if m: + a, b = float(m.group(1)), float(m.group(2)) + if -90 <= a <= 90 and -180 <= b <= 180: + return m.group(1), m.group(2) + # 7) MapBox marker / pin pattern: pin-s+ff0000(lng,lat) + m = re.search(r"\(([+-]?\d{1,3}\.\d{2,}),([+-]?\d{1,3}\.\d{2,})\)", text) + if m: + # MapBox is lng,lat + a, b = float(m.group(1)), float(m.group(2)) + if -180 <= a <= 180 and -90 <= b <= 90: + return m.group(2), m.group(1) + return None, None + + # Strategy: navigate to Map tab, click 'View Map', then click the star/marker + # for the main project to open a tooltip containing the coordinates. + try: + map_url = _ensure_tab(url, "map") + self._page.goto(map_url, wait_until="domcontentloaded", timeout=30000) + try: self._page.wait_for_load_state("networkidle", timeout=20000) + except Exception: pass + self._page.wait_for_timeout(1500) + # Click 'View Map' / 'Ver mapa' button + for vsel in ("button:has-text('View on map')", "button:has-text('View Map')", + "a:has-text('View on map')", "a:has-text('View Map')", + "button:has-text('Ver mapa')", "a:has-text('Ver mapa')", + "button:has-text('Ver no mapa')"): + try: + v = self._page.locator(vsel).first + if v.count() > 0 and v.is_visible(timeout=1500): + v.click(timeout=3000) + self._page.wait_for_timeout(1500) + self.log(f"Clicked: {vsel}") + break + except Exception: continue + # Wait for map markers to render + self._page.wait_for_timeout(2000) + # Click the main project star/marker. Try several common selectors. + for msel in ("[aria-label*='Main project' i]", "[title*='Main project' i]", + "img[src*='star' i]", "img[alt*='star' i]", + "[class*='main-marker' i]", "[class*='main-project' i]", + "[class*='star' i]", + "svg [class*='star' i]", + "button[aria-label*='star' i]", + ".leaflet-marker-icon", "[role='button'][aria-label*='project' i]"): + try: + marker = self._page.locator(msel).first + if marker.count() > 0: + marker.click(timeout=3000, force=True) + self._page.wait_for_timeout(1500) + self.log(f"Clicked marker: {msel}") + break + except Exception: continue + self._page.wait_for_timeout(800) + except Exception as e: + self.log(f"Map click sequence error: {e}") + + sources = [] + # Source 0: captured JSON blobs from XHR responses (most reliable) + try: + for u, body in (self._json_blobs or []): + sources.append((f"xhr:{u[-60:]}", body)) + except Exception: pass + # Source A: raw HTML of currently-loaded page + try: sources.append(("current_html", self._page.content())) + except Exception: pass + # Source B: inner_text fallback + try: sources.append(("current_text", self._page.inner_text("body"))) + except Exception: pass + # Source C: iframe srcs + try: + ifr = self._page.evaluate("() => Array.from(document.querySelectorAll('iframe')).map(i => i.src).join('|')") + if ifr: sources.append(("iframes", ifr)) + except Exception: pass + # Source D: window JSON state (Vue/React often stash it) + try: + state = self._page.evaluate("() => JSON.stringify(window.__INITIAL_STATE__||window.__NUXT__||window.__APOLLO_STATE__||{})") + if state and len(state) > 5: sources.append(("win_state", state)) + except Exception: pass + + + for name, txt in sources: + lat, lon = _try(txt) + if lat and lon: + self.log(f"Lat/Lon found via {name}: {lat}, {lon}") + break + + if not (lat and lon): + for slug in ("map", "location", "general"): + if lat and lon: break + try: + map_url = _ensure_tab(url, slug) + self.log(f"Loading {slug} for lat/lon: {map_url}") + self._page.goto(map_url, wait_until="domcontentloaded", timeout=30000) + try: self._page.wait_for_load_state("networkidle", timeout=20000) + except Exception: pass + self._page.wait_for_timeout(1500) + self._scroll(steps=4, pause=400) + for source in (self._page.content(), self._page.inner_text("body")): + lat, lon = _try(source) + if lat and lon: + self.log(f"Lat/Lon found on {slug}: {lat}, {lon}") + break + except Exception as e: + self.log(f"Map ({slug}) error: {e}") + + if lat and lon: + fields["Latitude"] = lat + fields["Longitude"] = lon + fields["Coordinates"] = f"{lat}, {lon}" + self.log(f"Coordinates: {fields['Coordinates']}") + else: + self.log("Latitude/Longitude not found anywhere.") + except Exception as e: + self.log(f"Map extraction error: {e}") + + # Schedule tab — date precedes label in the timeline UI + try: + sch_url = _ensure_tab(url, "schedule") + self.log(f"Loading Schedule: {sch_url}") + self._page.goto(sch_url, wait_until="domcontentloaded", timeout=30000) + try: self._page.wait_for_load_state("networkidle", timeout=20000) + except Exception: pass + self._page.wait_for_timeout(1500) + self._scroll(steps=6, pause=400) + sch_text = self._page.inner_text("body") + # Strip badge tokens (ESTIMATED/MAIN/CONFIRMED/...) that BNA + # renders inline as colored chips. They show up two ways: + # 1) Full word glued / on its own line: "AUGUST 2025ESTIMATED" + # 2) Single uppercase initial glued to year: "AUGUST 2025E" + # Both must be removed before the date<->label regex runs. + BADGE_RE = r"(?:ESTIMATED|MAIN|CONFIRMED|UPDATED|PROPOSED|PRELIMINARY|TARGET|PRIMARY|SECONDARY|EXPECTED)\b" + sch_text = re.sub(BADGE_RE, " ", sch_text) + # Strip ANY uppercase-letter run sitting between a 4-digit year + # and end-of-line (catches the single-letter "E" badge). + sch_text = re.sub(r"(\d{4})[A-Z]+(?=\s*$)", r"\1", + sch_text, flags=re.MULTILINE) + sch_text = re.sub(r"[ \t]+", " ", sch_text) + sch_text = re.sub(r" *\n *", "\n", sch_text) + sch_text = re.sub(r"\n{2,}", "\n", sch_text) + # Each schedule field has en/es/pt aliases. We try every alias + # and store under the canonical English key. + # NOTE: PT labels on BNA use "da" (not "de") and use + # "empreiteiro" / "detalhamento" — match what the platform + # actually renders, not what a translator might guess. + schedule_aliases = { + "Project Announced": [ + "Project Announced", "Proyecto Anunciado", + "Projeto Anunciado"], + "Start of Operation": [ + "Start of Operation", + "Inicio de Operación", "Inicio de la Operación", + "Início da Operação", "Início de Operação"], + "End of Operation": [ + "End of Operation", + "Fin de Operación", + "Fim da Operação", "Fim de Operação"], + "Start of Construction": [ + "Start of Construction", + "Inicio de Construcción", "Inicio de la Construcción", + "Início da Construção", "Início de Construção"], + "End of Construction": [ + "End of Construction", + "Fin de Construcción", + "Fim da Construção", "Fim de Construção"], + "Start of Main Contractor Tendering": [ + "Start of Main Contractor Tendering", + "Inicio de Licitación de Contratista Principal", + "Inicio de Licitación del Contratista Principal", + "Início da Licitação do Empreiteiro Principal", + "Início de Licitação do Empreiteiro Principal", + "Início da Licitação do Contratante Principal", + "Início de Licitação do Contratante Principal"], + "Start of Detailed Engineering": [ + "Start of Detailed Engineering", + "Inicio de Ingeniería Detallada", + "Inicio de ingeniería de detalle", + "Inicio de Ingeniería de Detalle", + "Início da Engenharia de Detalhamento", + "Início de Engenharia de Detalhamento", + "Início da Engenharia Detalhada", + "Início de Engenharia Detalhada", + "Início da Engenharia de Detalhe", + "Início de Engenharia de Detalhe"], + "Environmental and Social Approval": [ + "Environmental and Social Approval", + "Aprobación Ambiental y Social", + "Aprovação Ambiental e Social"], + } + # Persist schedule snapshot for diagnostics + if self.debug_dir: + try: + os.makedirs(self.debug_dir, exist_ok=True) + with open(os.path.join(self.debug_dir, "schedule_text.txt"), + "w", encoding="utf-8") as f: + f.write(sch_text or "") + except Exception: pass + # 'Not yet disclosed' equivalents in EN/ES/PT — used to mark a + # schedule date as explicitly unset (not assigned to next row). + unset_token = (r"NOT\s+YET\s+DISCLOSED|NOT\s+DISCLOSED|" + r"A[úu]n\s+no\s+divulgado|A[úu]n\s+no\s+publicado|" + r"No\s+divulgado|No\s+publicado|" + r"Ainda\s+n[ãa]o\s+divulgado|N[ãa]o\s+divulgado|" + r"TBD|N\/A") + date_token = (rf"(?:{unset_token}|" + r"[A-Za-zÀ-ÿ]+\s+\d{4}|" + r"\d{1,2}[/\.\-]\d{1,2}[/\.\-]\d{2,4}|" + r"\d{4}-\d{2}-\d{2})") + unset_re = re.compile(rf"^(?:{unset_token})$", re.IGNORECASE) + for canonical, aliases in schedule_aliases.items(): + found = False + for label in aliases: + # ONLY date-then-label is reliable on BNA's Schedule tab. + # The previous label-then-date fallback was too greedy: + # when a field had 'Aún no divulgado' (no date), it + # picked up the NEXT field's date and mis-assigned it. + pat = rf"(?mi)^\s*({date_token})\s*\n\s*{re.escape(label)}\b" + m = re.search(pat, sch_text) + if not m: continue + val = m.group(1).strip() + if unset_re.fullmatch(val): + # Explicitly marked unset — leave this field blank. + found = True; break + fields[canonical] = val + self.log(f"Schedule {canonical}: {val}") + found = True; break + if found: continue + except Exception as e: + self.log(f"Schedule extraction error: {e}") + + # General tab + try: + gen_url = _ensure_tab(url, "general") + self.log(f"Loading General: {gen_url}") + self._page.goto(gen_url, wait_until="domcontentloaded", timeout=30000) + try: self._page.wait_for_load_state("networkidle", timeout=20000) + except Exception: pass + self._page.wait_for_timeout(1500) + self._scroll(steps=6, pause=400) + # Always save a snapshot of the General tab for diagnostics + if self.debug_dir: + try: + os.makedirs(self.debug_dir, exist_ok=True) + with open(os.path.join(self.debug_dir, "general_page.html"), + "w", encoding="utf-8") as f: + f.write(self._page.content() or "") + with open(os.path.join(self.debug_dir, "general_text.txt"), + "w", encoding="utf-8") as f: + f.write(self._page.inner_text("body") or "") + except Exception: pass + text = self._page.inner_text("body") + # Strip inline badge tokens (ESTIMATED/MAIN/...) so they don't + # corrupt extracted values like Capex "102.4 US$ mnESTIMATED". + # Case-sensitive ALL-CAPS match (see Schedule tab for rationale). + text = re.sub( + r"(?:ESTIMATED|MAIN|CONFIRMED|UPDATED|PROPOSED|PRELIMINARY|TARGET|PRIMARY|SECONDARY|EXPECTED)\b", + " ", text) + # Single-letter badge initial glued to a 4-digit year ('2025E') + text = re.sub(r"(\d{4})[A-Z]+(?=\s*$)", r"\1", + text, flags=re.MULTILINE) + text = re.sub(r"[ \t]+", " ", text) + text = re.sub(r" *\n *", "\n", text) + text = re.sub(r"\n{2,}", "\n", text) + # Multilingual label aliases — each English target field maps to a + # set of equivalent labels (English / Spanish / Portuguese) BNA may + # render. The scraper finds whichever variant the page is using. + label_aliases = { + "Capex": ("Capex", "CAPEX"), + "Lifespan": ("Lifespan", "Vida útil", "Vida util", + "Tempo de vida", "Tempo de Vida"), + "Development type": ("Development type", "Tipo de desarrollo", + "Tipo de desenvolvimento"), + "Property Type": ("Property Type", "Tipo de propiedad", + "Tipo de propriedade"), + "Current stage": ("Current stage", "Etapa actual", "Etapa atual", + "Fase actual", "Fase atual"), + "Last expert review": ("Last expert review", "Última Revisión Experta", + "Última Revisão Especializada", "Última Revisão", + "Última revisão de especialistas"), + "Latitude": ("Latitude", "Latitud"), + "Longitude": ("Longitude", "Longitud"), + } + # BNA renders inline badges (ESTIMATED/ESTIMADO/CONFIRMED/...) + # glued to numeric values, e.g. "215 US$ mnESTIMADO". Strip + # them so downstream comparison sees just the value. + GEN_BADGE_RE = re.compile( + r"\s*(?:ESTIMATED|ESTIMADO|CONFIRMED|CONFIRMADO|UPDATED|ATUALIZADO|" + r"PROPOSED|PROPUESTO|PROPOSTO|PRELIMINARY|PRELIMINAR|TARGET|META|" + r"PRIMARY|SECONDARY|EXPECTED|PRINCIPAL)\b\s*$", + re.IGNORECASE) + for canonical, aliases in label_aliases.items(): + for label in aliases: + m = re.search( + rf"(?mi)^{re.escape(label)}\s*[:\n]\s*([^\n]+(?:\n[^\n]+){{0,2}})", + text) + if m: + val = m.group(1).strip().split("\n\n")[0].strip().split("\n")[0].strip() + # Strip trailing badge token glued to numeric value + val = GEN_BADGE_RE.sub("", val).strip() + fields[canonical] = val + break + mc = re.search( + r"(?ims)\b(?:Project\s+Type\s+and\s+capacity|Tipo\s+y\s+capacidad\s+del\s+proyecto|Tipo\s+de\s+proyecto\s+y\s+capacidad|Tipo\s+e\s+capacidade\s+do\s+projeto|Tipo\s+de\s+projeto\s+e\s+capacidade)\b\s*[:\n]\s*(.+?)(?=\n\s*(?:Topics|Temas|T[óo]picos|Property\s+Type|Tipo\s+de\s+propiedad|Tipo\s+de\s+propriedade|Map|Mapa|Companies|Compañ[ií]as|Empresas|Description|Descripci[óo]n|Descri[çc][ãa]o|Schedule|Cronograma)\b)", + text) + if mc: + fields["Project Type and capacity"] = re.sub(r"\s+", " ", mc.group(1)).strip() + try: + page_html = self._page.content() or "" + section = re.search( + r"(?is)(?:Project\s+Type\s+and\s+capacity|Tipo\s+y\s+capacidad\s+del\s+proyecto|Tipo\s+de\s+proyecto\s+y\s+capacidad|Tipo\s+e\s+capacidade\s+do\s+projeto|Tipo\s+de\s+projeto\s+e\s+capacidade)[\s\S]{0,80}?(]+id=\"map\"|Topics|Temas|T[óo]picos)", + page_html) + if section: + chunk = section.group(1) + raw_items = re.findall( + r"]*class=\"[^\"]*mb-0[^\"]*\"[^>]*>([\s\S]*?)

", + chunk) + items = [] + for raw in raw_items: + # Strip BNA's badge spans. Multiple class signatures + # are used: badge / pill / tag / chip / label + # (generic) AND 'icon-status main-project-type' + # (the 'Principal' marker on the primary project + # type entry). Catch them all. + x = re.sub( + r"]*class=\"[^\"]*(?:badge|pill|tag-pill|chip|label|icon-status|main-project-type)[^\"]*\"[^>]*>[\s\S]*?", + " ", raw, flags=re.IGNORECASE) + x = re.sub(r"<[^>]+>", " ", x) + x = re.sub( + r"\b(?:main|estimated|confirmed|updated|proposed|preliminary|target|primary|secondary|expected)\b", + " ", x, flags=re.IGNORECASE) + # Strip a trailing 'Principal' word that may have + # leaked through inner_text without HTML markup. + x = re.sub(r"\s+Principal\s*$", "", x) + x = re.sub(r"\s+", " ", x).strip() + if x: items.append(x) + project_types = [] + capacities = [] + for it in items: + m = re.search(r"\d", it) + if not m: + project_types.append(it); continue + name_part = it[:m.start()].strip(" ,;:-") + cap_part = it[m.start():].strip() + if name_part: project_types.append(name_part) + if cap_part: capacities.append(cap_part) + def _dedupe(seq): + seen = set(); out = [] + for x in seq: + k = re.sub(r"\s+", " ", x.lower()).strip() + if k and k not in seen: + seen.add(k); out.append(x) + return out + project_types = _dedupe(project_types) + capacities = _dedupe(capacities) + if project_types: + fields["Project Type"] = ", ".join(project_types) + if capacities: + fields["Capacity"] = ", ".join(capacities) + self.log(f"Project Type items: {project_types}") + self.log(f"Capacity items: {capacities}") + except Exception as e: + self.log(f"Project Type/Capacity split error: {e}") + stop_words = ( + "Property Type", "Tipo de propiedad", "Tipo de propriedade", + "Project Type and capacity", "Tipo y capacidad del proyecto", + "Tipo de proyecto y capacidad", "Tipo e capacidade do projeto", + "Tipo de projeto e capacidade", + "Capex", + "Lifespan", "Vida útil", "Tempo de vida", + "Development type", "Tipo de desarrollo", "Tipo de desenvolvimento", + "Current stage", "Etapa actual", "Etapa atual", + "Fase actual", "Fase atual", + "Last expert review", "Última Revisión", "Última Revisão", + "Última revisão de especialistas", + "Topics", "Temas", "Tópicos", + "Principal works", "Obras principales", "Obras principais", + "Trabalhos principais", "Trabalhos Principais", + "Latitude", "Latitud", "Longitude", "Longitud", + "Map", "Mapa", + "Companies", "Compañías", "Compañias", "Empresas", + ) + stop_re = "|".join(re.escape(s) for s in stop_words) + md = re.search( + rf"(?ims)\b(?:Description|Descripción|Descrição)\b\s*[:\n]\s*(.+?)(?:\n\s*(?:{stop_re})\b)", + text) + if md: + desc = re.sub(r"\n{2,}", "\n\n", md.group(1).strip()) + fields["Description"] = desc + except Exception as e: + self.log(f"General extraction error: {e}") + + # Principal works tab + try: + for slug in ("products-services-principal-works", "products-services", "principal-works", + "productos-servicios-obras-principales", "productos-servicios", + "produtos-servicos-obras-principais", + "produtos-servicos-e-obras-principais", + "produtos-e-servicos-obras-principais", + "produtos-servicos", "trabalhos-principais"): + pw_url = _ensure_tab(url, slug) + self.log(f"Loading Principal Works: {pw_url}") + self._page.goto(pw_url, wait_until="domcontentloaded", timeout=30000) + try: self._page.wait_for_load_state("networkidle", timeout=20000) + except Exception: pass + self._page.wait_for_timeout(1500) + self._scroll(steps=8, pause=500) + pw_text = self._page.inner_text("body") + pw_match = ( + "Principal works" in pw_text or "Principal Works" in pw_text + or "Obras principales" in pw_text or "Obras Principales" in pw_text + or "Obras principais" in pw_text or "Obras Principais" in pw_text + or "Trabalhos principais" in pw_text or "Trabalhos Principais" in pw_text + or "Principales Trabajos" in pw_text or "Principales trabajos" in pw_text + or "Trabajos Principales" in pw_text or "Trabajos principales" in pw_text + ) + if pw_match: + stop_words = ("Disclaimer", "Exención de Responsabilidad", "Isenção", + "Products and services", "Products & services", + "Productos y servicios", "Productos, servicios", + "Produtos e serviços", + "Topics", "Temas", "Tópicos", + "Companies", "Compañías", "Compañias", + "Schedule", "Cronograma", + "Map", "Mapa", + "Documents", "Documentos") + stop_re = "|".join(re.escape(s) for s in stop_words) + # Words that look like content but are actually nav / + # tab labels on BNA. If a chunk is mostly these, the + # Principal Works section is effectively empty. + NAV_WORDS = { + "notes", "notas", "general", "general ", + "principal works", "obras principales", "obras principais", + "trabalhos principais", "principales trabajos", + "trabajos principales", + "products and services", "products & services", + "productos y servicios", "productos, servicios", + "productos, servicios y obras principales", + "produtos e serviços", "produtos e servicos", + "products, services & principal works", + "schedule", "cronograma", "map", "mapa", + "companies", "compañías", "compañias", "empresas", + "companies & contacts", "compañías y contactos", + "compañías y contactos", + "empresas e contatos", + "milestones, news & reports", "milestones", + "hitos, noticias y reportes", "hitos", + "marcos, noticias", "marcos, notícias", + "documents", "documentos", + "description", "descripción", "descrição", + } + + def _strip_nav_lines(chunk): + """Remove lines anywhere in the chunk that are + exact matches of nav words, then collapse blank + runs. Keeps real content.""" + out_lines = [] + for ln in chunk.splitlines(): + if ln.strip().lower() in NAV_WORDS: continue + out_lines.append(ln) + cleaned = "\n".join(out_lines) + cleaned = re.sub(r"\n{3,}", "\n\n", cleaned) + return cleaned.strip(" :\n\t") + + def _is_meaningful(chunk): + """Drop chunks that are just nav / tab names or are + too short to plausibly describe principal works.""" + if not chunk or not chunk.strip(): return False + cleaned = _strip_nav_lines(chunk) + if len(cleaned) < 30: return False + words = re.findall(r"[A-Za-zÀ-ÿ]{2,}", cleaned) + return len(words) >= 5 + + candidates = [] + for hm in re.finditer( + r"(?im)\b(?:Principal\s+[Ww]orks|Obras\s+[Pp]rincipales|Obras\s+[Pp]rincipais|Trabalhos\s+[Pp]rincipais|Principales\s+[Tt]rabajos|Trabajos\s+[Pp]rincipales)\b", + pw_text): + start = hm.end() + rest = pw_text[start:] + cut = re.search(rf"(?ims)\n\s*(?:{stop_re})\b", rest) + chunk = rest[:cut.start()] if cut else rest + chunk = chunk.strip(" :\n\t") + if chunk and not re.match(rf"(?i)^(?:{stop_re}|Products\s+and\s+services|Productos\s+y\s+servicios|Produtos\s+e\s+serviços)\b", chunk): + if _is_meaningful(chunk): + candidates.append(chunk) + if candidates: + body = max(candidates, key=len) + # Strip nav prefix lines from the final body too. + body = _strip_nav_lines(body) + if body: + fields["Principal works"] = body + self.log(f"Principal works captured: {len(body)} chars") + break + # ---- HTML
  • ...
bullet fallback ---- + # Some projects render Principal Works as bullet lists + # only — the inner_text path collapses them oddly and + # the regex misses them. Scan the page HTML for any + #
    sitting after a Principal Works heading and + # pull the
  • items. + try: + pw_html = self._page.content() or "" + except Exception: + pw_html = "" + if pw_html: + head_re = (r'(?is)]*>\s*' + r'(?:Principal\s+[Ww]orks|Obras\s+[Pp]rincipales|' + r'Obras\s+[Pp]rincipais|Trabalhos\s+[Pp]rincipais|' + r'Principales\s+[Tt]rabajos|Trabajos\s+[Pp]rincipales)' + r'\s*') + head_m = re.search(head_re, pw_html) + scan_from = head_m.end() if head_m else 0 + chunk = pw_html[scan_from:] + ul_match = re.search(r"(?is)]*>([\s\S]*?)
", chunk) + if ul_match: + ul_html = ul_match.group(1) + items = re.findall(r"(?is)]*>([\s\S]*?)", ul_html) + cleaned_items = [] + for it in items: + text_only = re.sub(r"<[^>]+>", " ", it) + text_only = re.sub(r"\s+", " ", text_only).strip() + if text_only and len(text_only) >= 2: + cleaned_items.append(text_only) + if cleaned_items: + body = "\n".join(cleaned_items) + fields["Principal works"] = body + self.log(f"Principal works (bullet path): {len(cleaned_items)} items") + break + except Exception as e: + self.log(f"Principal works extraction error: {e}") + if not fields: + self.log("No fields extracted. Saving debug dump.") + self._save_debug() + if self.debug_dir: + try: + os.makedirs(self.debug_dir, exist_ok=True) + with open(os.path.join(self.debug_dir, "all_bna_fields.txt"), + "w", encoding="utf-8") as f: + f.write(f"Total fields: {len(fields)}\n\n") + for k in sorted(fields.keys()): + v = fields[k] + if isinstance(v, list): + v_str = "[" + ", ".join(repr(x) for x in v) + "]" + else: + v_str = repr(v) + if len(v_str) > 1000: + v_str = v_str[:1000] + f"... (+{len(v_str)-1000} chars)" + f.write(f"{k}: {v_str}\n") + except Exception as e: + self.log(f"all_bna_fields dump failed: {e}") + self.log(f"Total normalized BNA fields: {len(fields)}") + return fields + + def _save_debug(self): + try: + if not self.debug_dir: + self.debug_dir = os.path.join(os.getcwd(), "debug") + os.makedirs(self.debug_dir, exist_ok=True) + with open(os.path.join(self.debug_dir, "page.html"), "w", encoding="utf-8") as f: + f.write(self._page.content() or "") + with open(os.path.join(self.debug_dir, "page_text.txt"), "w", encoding="utf-8") as f: + f.write(self._page.inner_text("body") or "") + except Exception as e: + self.log(f"debug dump error: {e}")