""" TIE Loader: Reads TIE Requirements.xlsx at runtime. Per TIE Logics.docx: ignore General tab. Load reference tabs only. """ from __future__ import annotations import os import re from datetime import datetime from typing import Dict, List, Optional, Tuple import openpyxl def _norm(s): if s is None: return "" return str(s).strip().lower() class TIE: def __init__(self, path: str): self.path = path self.wb = openpyxl.load_workbook(path, data_only=True) self.stage_mapping: Dict[str, str] = {} self.project_type_mapping: Dict[str, str] = {} self.region_mapping: Dict[str, str] = {} self.ownership_type_mapping: Dict[str, str] = {} self.development_type_mapping: Dict[str, str] = {} self.project_position_mapping: Dict[str, str] = {} self.company_roles: Dict[str, Dict[str, str]] = {} self.current_stages: List[Dict[str, str]] = [] self.capacity_by_type: Dict[str, List[str]] = {} # Capacity Units: phrase → canonical short unit. Built from the # editable 'Capacity Units' sheet (UNIT, NAME UNIT columns) so # researchers can extend mappings without code changes. self.capacity_unit_aliases: Dict[str, str] = {} # BNA enum-value translations: english_lower → {'es': ..., 'pt': ...} # Used to display BNA values in the selected output language even # when BNA stores the underlying enum in English. Editable via the # '*** Translations' sheets in TIE_Requirements.xlsx. self.bna_translations: Dict[str, Dict[str, Dict[str, str]]] = { "property_type": {}, "development_type": {}, "project_type": {}, "project_stage": {}, } # Capacity unit phrase translations: english_lower → {'es','pt'}. # Editable via the 'Capacity Unit Translations' sheet. self.capacity_unit_translations: Dict[str, Dict[str, str]] = {} self.date_examples: List[Tuple[str, str]] = [] # Company Chip Mapping: AI field name -> BNA chip label. # Loaded from the editable 'Company Chip Mapping' sheet so the # researcher can extend mappings without code changes. self.company_chip_mapping: Dict[str, str] = {} # FX Rates: list of (currency, date, rate_to_usd) tuples loaded from # the editable 'FX Rates' sheet. Used by currency.py for Capex conv. self.fx_rates: List = [] self._load_mapping("Stage Mapping", self.stage_mapping) self._load_mapping("Project Type", self.project_type_mapping) self._load_mapping("Region", self.region_mapping) self._load_mapping("Ownership Type", self.ownership_type_mapping) self._load_mapping("Development Type", self.development_type_mapping) self._load_project_position() self._load_company_roles() self._load_company_chip_mapping() self._load_fx_rates() self._load_current_stages() self._load_capacity() self._load_capacity_units() self._load_bna_translations() self._load_capacity_unit_translations() self._load_dates() def _load_mapping(self, sheet, target): if sheet not in self.wb.sheetnames: return ws = self.wb[sheet] for i, row in enumerate(ws.iter_rows(values_only=True)): if i == 0: continue if not row or len(row) < 2: continue ext, bna = row[0], row[1] if ext is None or bna is None: continue target[_norm(ext)] = str(bna).strip() def _load_project_position(self): """Project Position sheet: maps standard role -> BNA position term. We invert it: bracket-extracted BNA term -> standard role.""" if "Project Position" not in self.wb.sheetnames: return ws = self.wb["Project Position"] for i, row in enumerate(ws.iter_rows(values_only=True)): if i == 0: continue if not row or len(row) < 2: continue std_role, bna_term = row[0], row[1] if std_role is None or bna_term is None: continue # invert: bna term -> std role self.project_position_mapping[_norm(bna_term)] = str(std_role).strip() def _load_company_roles(self): if "Company Mapping (Roles)" not in self.wb.sheetnames: return ws = self.wb["Company Mapping (Roles)"] headers = None for i, row in enumerate(ws.iter_rows(values_only=True)): if i == 0: headers = [str(h or "").strip() for h in row]; continue if not row or not row[0]: continue enum_key = str(row[0]).strip() self.company_roles[enum_key] = { "es": str(row[1] or "").strip() if len(row) > 1 else "", "en": str(row[2] or "").strip() if len(row) > 2 else "", "pt": str(row[3] or "").strip() if len(row) > 3 else "", } def _load_current_stages(self): if "Current Stage" not in self.wb.sheetnames: return ws = self.wb["Current Stage"] for i, row in enumerate(ws.iter_rows(values_only=True)): if i == 0: continue if not row or not row[1]: continue self.current_stages.append({ "order": row[0], "substage": str(row[1]).strip(), "es": str(row[2] or "").strip() if len(row) > 2 else "", "en": str(row[3] or "").strip() if len(row) > 3 else "", "pt": str(row[4] or "").strip() if len(row) > 4 else "", }) def _load_capacity(self): if "Capacity" not in self.wb.sheetnames: return ws = self.wb["Capacity"] for i, row in enumerate(ws.iter_rows(values_only=True)): if i == 0: continue if not row or not row[1]: continue project_type = _norm(row[1]) units = [] for idx in (2, 4, 6, 8): if idx < len(row) and row[idx]: units.append(str(row[idx]).strip()) self.capacity_by_type[project_type] = units def _load_capacity_units(self): """Load 'Capacity Units' sheet. Two columns: UNIT, NAME UNIT. Both forms become aliases that map to the canonical (UNIT) value — e.g. 'barrels per day' -> 'b/d', 'b/d' -> 'b/d'. Lookup is case-insensitive and whitespace-insensitive.""" if "Capacity Units" not in self.wb.sheetnames: return ws = self.wb["Capacity Units"] def _key(s): if s is None: return "" return re.sub(r"\s+", " ", str(s)).strip().lower() for i, row in enumerate(ws.iter_rows(values_only=True)): if i == 0: continue if not row or len(row) < 2: continue unit, name_unit = row[0], row[1] if unit is None and name_unit is None: continue canonical = _key(unit) or _key(name_unit) if not canonical: continue if unit: self.capacity_unit_aliases[_key(unit)] = canonical if name_unit: self.capacity_unit_aliases[_key(name_unit)] = canonical def _load_bna_translations(self): """Load the four BNA enum-value translation sheets. Each row is (English, Spanish, Portuguese). Stored keyed by lowercased English for case-insensitive lookup. Researchers can add rows to extend coverage without touching code.""" sheet_to_field = { "Property Type Translations": "property_type", "Development Type Translations": "development_type", "Project Type Translations": "project_type", "Project Stage Translations": "project_stage", } for sheet, field_key in sheet_to_field.items(): if sheet not in self.wb.sheetnames: continue ws = self.wb[sheet] for i, row in enumerate(ws.iter_rows(values_only=True)): if i == 0: continue # header if not row or not row[0]: continue en = str(row[0]).strip() if not en: continue es = str(row[1] or "").strip() if len(row) > 1 else "" pt = str(row[2] or "").strip() if len(row) > 2 else "" self.bna_translations[field_key][en.lower()] = { "es": es or en, "pt": pt or en, } def _load_capacity_unit_translations(self): """Load 'Capacity Unit Translations' (English | Spanish | Portuguese).""" if "Capacity Unit Translations" not in self.wb.sheetnames: return ws = self.wb["Capacity Unit Translations"] def _key(s): if s is None: return "" return re.sub(r"\s+", " ", str(s)).strip().lower() for i, row in enumerate(ws.iter_rows(values_only=True)): if i == 0: continue if not row or not row[0]: continue en = _key(row[0]) if not en: continue es = str(row[1] or "").strip() if len(row) > 1 else "" pt = str(row[2] or "").strip() if len(row) > 2 else "" self.capacity_unit_translations[en] = {"es": es or row[0], "pt": pt or row[0]} def _load_dates(self): if "Dates" not in self.wb.sheetnames: return ws = self.wb["Dates"] for i, row in enumerate(ws.iter_rows(values_only=True)): if i == 0: continue if not row or row[0] is None: continue self.date_examples.append((str(row[0]), str(row[1] or ""))) def lookup_mapping(self, mapping, value): if value is None: return None return mapping.get(_norm(value)) def map_project_position_to_role(self, bna_term): """Given a bracket-extracted BNA position (e.g. 'Managers - Project'), return the standard role (e.g. 'Project Manager').""" if not bna_term: return None return self.project_position_mapping.get(_norm(bna_term)) def _load_company_chip_mapping(self): """Read the 'Company Chip Mapping' sheet: Col A: Agentic AI Output Field Name Col B: BNA Chip Stored as: ai_field_norm -> bna_chip (preserved case).""" if "Company Chip Mapping" not in self.wb.sheetnames: return ws = self.wb["Company Chip Mapping"] for i, row in enumerate(ws.iter_rows(values_only=True)): if i == 0: continue if not row or len(row) < 2: continue ai_field, bna_chip = row[0], row[1] if ai_field is None or bna_chip is None: continue self.company_chip_mapping[_norm(ai_field)] = str(bna_chip).strip() def map_ai_company_field_to_chip(self, ai_field): """AI field name (e.g. 'Owner Company') -> BNA chip label.""" if not ai_field: return None return self.company_chip_mapping.get(_norm(ai_field)) def _load_fx_rates(self): """'FX Rates' sheet: Col A: ISO currency code (e.g. BRL) Col B: date the rate is valid for (DD/MM/YYYY or any parsable form) Col C: rate (multiplier to USD; e.g. 0.18 for BRL) """ if "FX Rates" not in self.wb.sheetnames: return ws = self.wb["FX Rates"] for i, row in enumerate(ws.iter_rows(values_only=True)): if i == 0: continue if not row or not row[0] or not row[1] or row[2] is None: continue try: code = str(row[0]).strip().upper() dt_raw = row[1] if isinstance(dt_raw, datetime): dt = dt_raw else: s = str(dt_raw).strip() dt = None for fmt in ("%Y-%m-%d","%d/%m/%Y","%m/%d/%Y","%d-%m-%Y","%Y/%m/%d"): try: dt = datetime.strptime(s, fmt); break except ValueError: pass if dt is None: continue rate = float(row[2]) self.fx_rates.append((code, dt, rate)) except Exception: continue