Spaces:
Runtime error
Runtime error
File size: 12,102 Bytes
27c9320 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | """
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
|