Spaces:
Runtime error
Runtime error
Download engine/i18n.py from BNAmericas/ComparerTool: direct link, hf CLI and curl.
- Browser
- Download file 14.5 kB
-
https://huggingface.co/spaces/BNAmericas/ComparerTool/resolve/main/engine/i18n.py
- Command line
-
hf download hf://spaces/BNAmericas/ComparerTool/engine/i18n.py
-
curl -L -o i18n.py https://huggingface.co/spaces/BNAmericas/ComparerTool/resolve/main/engine/i18n.py
14.5 kB
| """ | |
| i18n: headers, labels and confidence translations for outputs. | |
| Only 6 columns now per TIE Logics spec. | |
| """ | |
| from __future__ import annotations | |
| from tie_loader import TIE, _norm | |
| HEADERS = { | |
| "es": ["Campo IA", "Valor IA", "Valor Transformado", "Valor BNA", "Recomendación", "Fuente IA", "URL Fuente IA", "Fecha de Fuente IA"], | |
| "en": ["AI Field", "AI Value", "Transformed Value", "BNA Value", "Recommendation", "AI Source", "AI Source URL", "AI Source Date"], | |
| "pt": ["Campo IA", "Valor IA", "Valor Transformado", "Valor BNA", "Recomendação", "Fonte IA", "URL Fonte IA", "Data da Fonte IA"], | |
| } | |
| # Extra reviewer columns appended only on the Recommendations sheet | |
| RECO_HEADERS_EXTRA = { | |
| "es": ["Comando Investigador (Válido/Inválido)", "Comentario del Investigador"], | |
| "en": ["Researcher Command (Valid/Invalid)", "Researcher's Remark"], | |
| "pt": ["Comando do Pesquisador (Válido/Inválido)", "Observação do Pesquisador"], | |
| } | |
| VALID_OPTIONS = { | |
| "es": ["Válido", "Inválido"], | |
| "en": ["Valid", "Invalid"], | |
| "pt": ["Válido", "Inválido"], | |
| } | |
| INSIGHTS_HEADERS = { | |
| "es": ["Métrica", "Valor"], | |
| "en": ["Metric", "Value"], | |
| "pt": ["Métrica", "Valor"], | |
| } | |
| LOG_HEADERS = { | |
| "es": ["Marca de tiempo", "Nivel", "Mensaje"], | |
| "en": ["Timestamp", "Level", "Message"], | |
| "pt": ["Data/Hora", "Nível", "Mensagem"], | |
| } | |
| CONFIDENCE = { | |
| "en": {"high": "High", "medium": "Medium", "low": "Low"}, | |
| "es": {"high": "Alta", "medium": "Media", "low": "Baja"}, | |
| "pt": {"high": "Alta", "medium": "Média", "low": "Baixa"}, | |
| } | |
| VERDICT_LEGEND_TITLE = { | |
| "es": "Leyenda de veredictos — qué significa cada indicador", | |
| "en": "Verdict legend — what each indicator means", | |
| "pt": "Legenda de veredictos — o que cada indicador significa", | |
| } | |
| VERDICT_LEGEND_ITEMS = { | |
| "es": [ | |
| "Coincide — el valor de la IA coincide con BNA.", | |
| "Difiere — IA y BNA tienen valores diferentes; se genera una recomendación.", | |
| "Falta en Ambos — ni la IA ni BNA tienen el valor; nada que actualizar.", | |
| "Falta en IA — BNA tiene el valor; la IA no lo extrajo. El equipo de IA puede revisar.", | |
| "IA Antigua — los valores difieren, pero la fecha de la fuente IA es anterior a la última revisión BNA; BNA puede ya tener la información más reciente.", | |
| ], | |
| "en": [ | |
| "Match — AI value agrees with BNA.", | |
| "Differ — AI and BNA both have values but they don't match; a recommendation is generated.", | |
| "Missing on Both — neither AI nor BNA has the value; nothing to act on.", | |
| "Missing on AI — BNA already has the value; AI didn't extract it. The AI team can investigate.", | |
| "Stale AI — values differ but the AI source date is older than BNA's last expert review; BNA likely already has the more current value.", | |
| ], | |
| "pt": [ | |
| "Coincide — o valor da IA coincide com BNA.", | |
| "Difere — IA e BNA têm valores, mas não coincidem; uma recomendação é gerada.", | |
| "Falta em Ambos — nem IA nem BNA têm o valor; nada para atualizar.", | |
| "Falta em IA — BNA tem o valor; a IA não extraiu. A equipe de IA pode revisar.", | |
| "IA Antiga — os valores diferem, mas a data da fonte IA é anterior à última revisão BNA; BNA provavelmente já tem o valor mais recente.", | |
| ], | |
| } | |
| MATCH_LABEL = { | |
| "es": { | |
| "Match": "Coincide", "Differ": "Difiere", | |
| "Missing on Both": "Falta en Ambos", | |
| "Missing on AI": "Falta en IA", | |
| "Stale AI": "IA Antigua", | |
| "": "", | |
| }, | |
| "en": { | |
| "Match": "Match", "Differ": "Differ", | |
| "Missing on Both": "Missing on Both", | |
| "Missing on AI": "Missing on AI", | |
| "Stale AI": "Stale AI", | |
| "": "", | |
| }, | |
| "pt": { | |
| "Match": "Coincide", "Differ": "Difere", | |
| "Missing on Both": "Falta em Ambos", | |
| "Missing on AI": "Falta em IA", | |
| "Stale AI": "IA Antiga", | |
| "": "", | |
| }, | |
| } | |
| def translate_confidence(value, lang): | |
| if value is None: return "" | |
| return CONFIDENCE.get(lang, CONFIDENCE["en"]).get(_norm(value), str(value)) | |
| # Built-in translations for the standard AI Excel field-name vocabulary. | |
| # Keyed by lowercased English form. TIE-sheet lookups (current_stages, | |
| FIELD_NAME_I18N = { | |
| "project name": {"es": "Nombre del Proyecto", "pt": "Nome do Projeto"}, | |
| "owner company": {"es": "Empresa Propietaria", "pt": "Empresa Proprietária"}, | |
| "concessionaire / operator company": {"es": "Concesionario / Operador", "pt": "Concessionário / Operador"}, | |
| "contractor company": {"es": "Empresa Contratista", "pt": "Empresa Contratada"}, | |
| "engineering company": {"es": "Empresa de Ingeniería", "pt": "Empresa de Engenharia"}, | |
| "equipment / technology provider": {"es": "Proveedor de Equipos / Tecnología", "pt": "Fornecedor de Equipamentos / Tecnologia"}, | |
| "consultancy company": {"es": "Consultoría", "pt": "Consultoria"}, | |
| "project stage": {"es": "Etapa del Proyecto", "pt": "Fase do Projeto"}, | |
| "project description": {"es": "Descripción del Proyecto", "pt": "Descrição do Projeto"}, | |
| "property type": {"es": "Tipo de Propiedad", "pt": "Tipo de Propriedade"}, | |
| "development type": {"es": "Tipo de Desarrollo", "pt": "Tipo de Desenvolvimento"}, | |
| "capex": {"es": "Capex", "pt": "Capex"}, | |
| "lifespan": {"es": "Vida Útil", "pt": "Tempo de Vida"}, | |
| "project type": {"es": "Tipo de Proyecto", "pt": "Tipo de Projeto"}, | |
| "milestones": {"es": "Hitos", "pt": "Marcos"}, | |
| "announcement date": {"es": "Fecha de Anuncio", "pt": "Data de Anúncio"}, | |
| "completion_end of construction date": {"es": "Fecha de Finalización de la Construcción", "pt": "Data de Fim da Construção"}, | |
| "construction start date": {"es": "Fecha de Inicio de Construcción", "pt": "Data de Início da Construção"}, | |
| "contractor tendering start date": {"es": "Fecha de Inicio de Licitación de Contratista", "pt": "Data de Início da Licitação do Contratante"}, | |
| "detailed engineering start date": {"es": "Fecha de Inicio de Ingeniería Detallada", "pt": "Data de Início da Engenharia Detalhada"}, | |
| "environmental approval date": {"es": "Fecha de Aprobación Ambiental", "pt": "Data de Aprovação Ambiental"}, | |
| "operations start date": {"es": "Fecha de Inicio de Operación", "pt": "Data de Início de Operação"}, | |
| "tendering start date": {"es": "Fecha de Inicio de Licitación", "pt": "Data de Início da Licitação"}, | |
| "end of operation date": {"es": "Fecha de Fin de Operación", "pt": "Data de Fim de Operação"}, | |
| "environmental impact assessment submission_presentation date": {"es": "Fecha de Presentación del EIA", "pt": "Data de Apresentação do EIA"}, | |
| "feasibility studies start date": {"es": "Fecha de Inicio de Estudios de Factibilidad", "pt": "Data de Início dos Estudos de Viabilidade"}, | |
| "pre-feasibility studies start date": {"es": "Fecha de Inicio de Estudios de Pre-Factibilidad", "pt": "Data de Início dos Estudos de Pré-Viabilidade"}, | |
| "latitude and longitude": {"es": "Latitud y Longitud", "pt": "Latitude e Longitude"}, | |
| "main works description": {"es": "Descripción de Obras Principales", "pt": "Descrição das Obras Principais"}, | |
| "project documentation": {"es": "Documentación del Proyecto", "pt": "Documentação do Projeto"}, | |
| "project manager": {"es": "Gerente de Proyecto", "pt": "Gerente de Projeto"}, | |
| "purchasing manager": {"es": "Gerente de Compras", "pt": "Gerente de Compras"}, | |
| "engineering manager": {"es": "Gerente de Ingeniería", "pt": "Gerente de Engenharia"}, | |
| "capacity": {"es": "Capacidad", "pt": "Capacidade"}, | |
| "products required": {"es": "Productos Requeridos", "pt": "Produtos Necessários"}, | |
| "services required": {"es": "Servicios Requeridos", "pt": "Serviços Necessários"}, | |
| } | |
| def translate_field_name(name, lang, tie: TIE): | |
| if not name: return name | |
| key = _norm(name) | |
| if key in FIELD_NAME_I18N and lang in FIELD_NAME_I18N[key]: | |
| return FIELD_NAME_I18N[key][lang] | |
| for row in tie.current_stages: | |
| if _norm(name) == _norm(row.get("substage")) or _norm(name) == _norm(row.get("en")): | |
| return row.get(lang, name) or name | |
| for enum_key, langs in tie.company_roles.items(): | |
| if _norm(name) == _norm(enum_key) or _norm(name) == _norm(langs.get("en", "")): | |
| return langs.get(lang, name) or name | |
| return name | |
| RECO_TEMPLATE = { | |
| "en": "{label} differs. Agentic AI value: {ai}. BNA Platform value: {bna}.", | |
| "es": "{label} difiere. Valor de la IA Agéntica: {ai}. Valor de la Plataforma BNA: {bna}.", | |
| "pt": "{label} difere. Valor da IA Agêntica: {ai}. Valor da Plataforma BNA: {bna}.", | |
| } | |
| RECO_MISSING_TEMPLATE = { | |
| "en": "Missing information identified from Agentic AI output: {extra}", | |
| "es": "Información faltante identificada en la salida de la IA Agéntica: {extra}", | |
| "pt": "Informação ausente identificada na saída da IA Agêntica: {extra}", | |
| } | |
| NOT_AVAILABLE_LABEL = { | |
| "en": "Not Available", | |
| "es": "No disponible", | |
| "pt": "Não disponível", | |
| } | |
| # Placeholder phrases the AI Excel commonly uses to mean 'no value'. | |
| # When the user picks ES/PT, these are translated for display so the | |
| # whole row reads natively. Lookup is case-insensitive on the trimmed | |
| # value. Only triggers when the value is EXACTLY one of these phrases. | |
| PLACEHOLDER_TRANSLATIONS = { | |
| "not publicly disclosed": {"es": "No divulgado públicamente", "pt": "Não divulgado publicamente"}, | |
| "not yet disclosed": {"es": "Aún no divulgado", "pt": "Ainda não divulgado"}, | |
| "not disclosed": {"es": "No divulgado", "pt": "Não divulgado"}, | |
| "not available": {"es": "No disponible", "pt": "Não disponível"}, | |
| "to be determined": {"es": "Por determinar", "pt": "A ser determinado"}, | |
| "to be disclosed": {"es": "Por divulgar", "pt": "A ser divulgado"}, | |
| "tbd": {"es": "Por determinar", "pt": "A ser determinado"}, | |
| "n/a": {"es": "N/D", "pt": "N/D"}, | |
| "n.a.": {"es": "N/D", "pt": "N/D"}, | |
| "na": {"es": "N/D", "pt": "N/D"}, | |
| "none": {"es": "Ninguno", "pt": "Nenhum"}, | |
| "null": {"es": "Nulo", "pt": "Nulo"}, | |
| "no disponible": {"es": "No disponible", "pt": "Não disponível"}, | |
| "no divulgado": {"es": "No divulgado", "pt": "Não divulgado"}, | |
| } | |
| def translate_placeholder(value, lang): | |
| """If `value` is a known placeholder phrase, return its translation | |
| in the target language. Otherwise return the original value.""" | |
| if not value or lang == "en": return value | |
| key = str(value).strip().lower() | |
| if not key: return value | |
| tr = PLACEHOLDER_TRANSLATIONS.get(key, {}).get(lang) | |
| return tr if tr else value | |
| # Map AI field name -> which translation bucket to use for the BNA value. | |
| # Keys are lowercased AI field names. The bucket name matches the key in | |
| # tie.bna_translations (property_type / development_type / project_type / | |
| # project_stage). Unmapped fields are left untranslated (free text). | |
| _BNA_FIELD_BUCKET = { | |
| "property type": "property_type", | |
| "development type": "development_type", | |
| "project type": "project_type", | |
| "project stage": "project_stage", | |
| "current stage": "project_stage", | |
| } | |
| def translate_capacity_value(text, lang, tie): | |
| """Translate the unit phrases inside a capacity value to ES/PT | |
| while keeping the numbers intact. | |
| '8 Number of stations, 33 kilometers' -> '8 número de estaciones, 33 kilómetros' | |
| Items are split on commas / semicolons; each item is parsed for its | |
| leading number, the remaining unit text is looked up in the editable | |
| 'Capacity Unit Translations' sheet. Falls back to original text if | |
| no translation is found.""" | |
| if not text or lang == "en" or tie is None: return text | |
| table = getattr(tie, "capacity_unit_translations", {}) or {} | |
| if not table: return text | |
| import re as _re | |
| parts = _re.split(r"\s*[,;]\s*", str(text)) | |
| out = [] | |
| any_change = False | |
| for p in parts: | |
| s = p.strip() | |
| if not s: continue | |
| # Match optional number (with thousands sep / decimal) then unit | |
| m = _re.match(r"^([\d.,\s]+)?\s*(.*)$", s, flags=_re.UNICODE) | |
| if not m: | |
| out.append(s); continue | |
| num = (m.group(1) or "").strip() | |
| unit = (m.group(2) or "").strip() | |
| if not unit: | |
| out.append(s); continue | |
| key = _re.sub(r"\s+", " ", unit).strip().lower() | |
| tr = table.get(key, {}).get(lang) | |
| if tr and tr.lower() != unit.lower(): | |
| any_change = True | |
| out.append((num + " " + tr).strip() if num else tr) | |
| else: | |
| out.append(s) | |
| return ", ".join(out) if any_change else text | |
| def translate_bna_value(ai_field, bna_value, lang, tie): | |
| """Translate a BNA-platform value into the selected output language | |
| using the editable translation sheets.""" | |
| if not bna_value or lang == "en" or tie is None: | |
| return bna_value | |
| bucket = _BNA_FIELD_BUCKET.get(_norm(ai_field)) | |
| if not bucket: return bna_value | |
| table = (getattr(tie, "bna_translations", {}) or {}).get(bucket, {}) | |
| if not table: return bna_value | |
| import re as _re | |
| full_key = str(bna_value).strip().lower() | |
| if full_key in table: | |
| t = table[full_key].get(lang) | |
| if t: return t | |
| parts = _re.split(r"\s*,\s*", str(bna_value)) | |
| parts = _re.split(r"\s*,\s*", str(bna_value)) | |
| translated_parts = [] | |
| any_change = False | |
| for p in parts: | |
| key = p.strip().lower() | |
| if key in table: | |
| t = table[key].get(lang) | |
| if t and t != p: | |
| any_change = True | |
| translated_parts.append(t or p) | |
| continue | |
| base = _re.sub(r"\s*\([^)]*\)\s*$", "", key).strip() | |
| if base and base in table: | |
| tail = _re.search(r"\s*\([^)]*\)\s*$", p) | |
| t = table[base].get(lang) or p | |
| if tail: t = (t + " " + tail.group(0).strip()).strip() | |
| if t != p: any_change = True | |
| translated_parts.append(t) | |
| continue | |
| translated_parts.append(p) | |
| return ", ".join(translated_parts) if any_change else bna_value | |