""" Transformer: Applies TIE transformation/validation rules to AI values. Runs entirely from TIE config; no hardcoded mapping. """ from __future__ import annotations import re from datetime import datetime from typing import Any, Dict, Optional, Tuple from tie_loader import TIE, _norm # ---------- Date transformation ---------- MONTHS_EN = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ] SPANISH_MONTHS = { "enero": 1, "febrero": 2, "marzo": 3, "abril": 4, "mayo": 5, "junio": 6, "julio": 7, "agosto": 8, "septiembre": 9, "setiembre": 9, "octubre": 10, "noviembre": 11, "diciembre": 12, } PORTUGUESE_MONTHS = { "janeiro": 1, "fevereiro": 2, "março": 3, "marco": 3, "abril": 4, "maio": 5, "junho": 6, "julho": 7, "agosto": 8, "setembro": 9, "outubro": 10, "novembro": 11, "dezembro": 12, } ENGLISH_MONTHS = {m.lower(): i + 1 for i, m in enumerate(MONTHS_EN)} ENGLISH_MONTHS_SHORT = {"jan": 1, "feb": 2, "mar": 3, "apr": 4, "may": 5, "jun": 6, "jul": 7, "aug": 8, "sep": 9, "sept": 9, "oct": 10, "nov": 11, "dec": 12} ALL_MONTHS = {**SPANISH_MONTHS, **PORTUGUESE_MONTHS, **ENGLISH_MONTHS, **ENGLISH_MONTHS_SHORT} def parse_date_flexible(raw) -> Optional[datetime]: """Parse many date formats. Returns datetime or None.""" if raw is None or raw == "": return None if isinstance(raw, datetime): return raw s = str(raw).strip() if not s: return None # Strip time if present s = re.sub(r"T\d{2}:\d{2}.*$", "", s) s = re.sub(r"\s+\d{2}:\d{2}.*$", "", s) # Try ISO formats for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%Y.%m.%d", "%Y-%m", "%Y/%m", "%Y.%m"): try: return datetime.strptime(s, fmt) except ValueError: pass # dd-mm-yyyy, dd.mm.yyyy, dd/mm/yyyy for fmt in ("%d-%m-%Y", "%d.%m.%Y", "%d/%m/%Y", "%d-%m-%y", "%d.%m.%y", "%d/%m/%y", "%m-%Y", "%m/%Y", "%m.%Y"): try: return datetime.strptime(s, fmt) except ValueError: pass # Month name: "March 2025", "15 September 2026", "September 2026" token_pattern = re.compile(r"([A-Za-zÀ-ÿ]+)", re.UNICODE) nums = re.findall(r"\d+", s) tokens = token_pattern.findall(s) month = None for t in tokens: tl = t.lower() if tl in ALL_MONTHS: month = ALL_MONTHS[tl] break year = None day = 1 for n in nums: if len(n) == 4: year = int(n) elif not day or day == 1: if 1 <= int(n) <= 31: day = int(n) if month and year: try: return datetime(year, month, day) except ValueError: return datetime(year, month, 1) # "de" Spanish: "14 de marzo de 2024" m = re.search(r"(\d{1,2})\s+de\s+([A-Za-zÀ-ÿ]+)\s+de\s+(\d{4})", s, re.IGNORECASE) if m: mn = ALL_MONTHS.get(m.group(2).lower()) if mn: return datetime(int(m.group(3)), mn, int(m.group(1))) return None def format_date_month_year(dt: Optional[datetime], lang: str = "en") -> str: if not dt: return "" if lang == "es": es = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"] return f"{es[dt.month - 1]} {dt.year}" if lang == "pt": pt = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"] return f"{pt[dt.month - 1]} {dt.year}" return f"{MONTHS_EN[dt.month - 1]} {dt.year}" # ---------- Number transformation ---------- def parse_number(raw) -> Optional[float]: if raw is None or raw == "": return None if isinstance(raw, (int, float)): return float(raw) s = str(raw).strip() if not s: return None # remove currency symbols/units s_clean = re.sub(r"[^\d,.\-]", "", s) if not s_clean: return None # Decide decimal separator: if both . and , exist, the last one is decimal if "," in s_clean and "." in s_clean: if s_clean.rfind(",") > s_clean.rfind("."): s_clean = s_clean.replace(".", "").replace(",", ".") else: s_clean = s_clean.replace(",", "") elif "," in s_clean: # If comma and exactly two digits follow, treat as decimal (ES/PT) parts = s_clean.split(",") if len(parts) == 2 and len(parts[-1]) <= 2: s_clean = s_clean.replace(",", ".") else: s_clean = s_clean.replace(",", "") try: return float(s_clean) except ValueError: return None def format_number(value: float, lang: str = "en", decimals: int = 2) -> str: if value is None: return "" if decimals == 0: s = f"{value:,.0f}" else: s = f"{value:,.{decimals}f}" if lang in ("es", "pt"): # swap thousands/decimal s = s.replace(",", "§").replace(".", ",").replace("§", ".") return s def format_capex(value: float, lang: str = "en") -> str: if value is None: return "" decimals = 1 if value <= 99 else 0 return format_number(value, lang, decimals) + " USD" # ---------- Multi-value + translation helpers ---------- def _split_tokens(raw_value: Any) -> list: """Split multi-value strings on comma, semicolon or pipe. Do NOT split on '/' — canonical names contain it (e.g. 'Construction / Development', 'Public (PPP/PFI)'). Pipe ('|') is used by the AI agent for hierarchical project type listings, e.g. 'Water > System | Wastewater > Plant'. Each segment may also contain a 'Sector > Type' prefix — we keep only the part after the last '>' so the translation table sees the leaf token.""" if raw_value is None: return [] s = str(raw_value).strip() if not s: return [] parts = re.split(r"\s*[,;|]\s*", s) out = [] for p in parts: p = p.strip() if not p: continue # If a token contains '>', keep only the segment after the last '>'. if ">" in p: p = p.rsplit(">", 1)[-1].strip() if p: out.append(p) return out def _translate_enum(canonical_en: str, field_key: str, tie: TIE, lang: str) -> str: """Translate enum value to target language using tie.bna_translations. Accepts input in EN/ES/PT — performs reverse-lookup if input is not already English. This handles cases where the AI scraper returns a value in Spanish/Portuguese (e.g. 'Concessões') instead of English.""" if not canonical_en: return canonical_en table = getattr(tie, "bna_translations", {}).get(field_key, {}) if not table: return canonical_en key = canonical_en.lower() entry = table.get(key) if not entry: # Reverse-lookup: input might already be in ES or PT for en_key, langs in table.items(): if (langs.get("es") or "").lower() == key or (langs.get("pt") or "").lower() == key: entry = langs canonical_en = en_key # canonical EN form break if not entry: return canonical_en if lang == "en": # Return canonical EN (Title-cased from the sheet if found) for en_key in table: if en_key.lower() == canonical_en.lower(): # Find original sheet casing pass return canonical_en return entry.get(lang) or canonical_en def _map_and_translate(raw_value: Any, mapping_dict: Dict[str, str], translations_key: Optional[str], tie: TIE, lang: str) -> str: """Multi-value safe: split → map each token to canonical EN → translate each to target lang → rejoin with ', '.""" tokens = _split_tokens(raw_value) if not tokens: return "" out = [] for t in tokens: mapped = tie.lookup_mapping(mapping_dict, t) if mapping_dict else None canonical = mapped or t if translations_key: canonical = _translate_enum(canonical, translations_key, tie, lang) out.append(canonical) return ", ".join(out) # ---------- Transformation dispatcher ---------- def transform(field_name: str, raw_value: Any, ai_date: Any, tie: TIE, lang: str = "en", project_type_hint: Optional[str] = None) -> str: """Apply per-field TIE transformation. Returns a string.""" if raw_value is None or str(raw_value).strip() == "": return "" key = _norm(field_name) # Date-like fields date_fields = { "announcement date", "completion_end of construction date", "construction start date", "contractor tendering start date", "detailed engineering start date", "end of operation date", "environmental approval date", "environmental impact assessment submission_presentation date", "feasibility studies start date", "operations start date", "pre-feasibility studies start date", "tendering start date", } if key in date_fields or "date" in key: dt = parse_date_flexible(raw_value) return format_date_month_year(dt, lang) # Project stage -> Stage Mapping + Project Stage Translations if key == "project stage" or key == "current stage": return _map_and_translate(raw_value, tie.stage_mapping, "project_stage", tie, lang) # Project type -> Project Type mapping + Project Type Translations if key == "project type": return _map_and_translate(raw_value, tie.project_type_mapping, "project_type", tie, lang) # Region (no translation sheet; multi-value safe map) if key == "region" or key == "state" or key == "province": return _map_and_translate(raw_value, tie.region_mapping, None, tie, lang) # Development type -> Development Type mapping + Development Type Translations if key == "development type": return _map_and_translate(raw_value, tie.development_type_mapping, "development_type", tie, lang) # Ownership type / property type -> Ownership Type mapping + Property Type Translations if key in ("ownership type", "property type"): return _map_and_translate(raw_value, tie.ownership_type_mapping, "property_type", tie, lang) # Capex -> USD number if key == "capex": n = parse_number(raw_value) return format_capex(n, lang) if n is not None else str(raw_value) # Capacity if key == "capacity": n = parse_number(raw_value) unit = "" if project_type_hint: units = tie.capacity_by_type.get(_norm(project_type_hint), []) unit = units[0] if units else "" if n is None: return str(raw_value) return (format_number(n, lang, 2) + (f" {unit}" if unit else "")).strip() # Company role-based fields company_role_fields = { "owner company": "PROJECT_OWNER", "operator / concessionaire": "PROJECT_CONCESSIONAIR_OPERATOR", "contractor company": "PROJECT_MAIN_CONTRACTOR", "engineering company": "PROJECT_ENGINEERING", "consultancy company": "PROJECT_CONSULTANCY", "equipment / technology provider": "PROJECT_TECHNOLOGY_PROVIDER", } if key in company_role_fields: return str(raw_value).strip() # Default: strip return str(raw_value).strip()