""" Insights: computes summary metrics from comparison rows. Feeds the Tkinter dashboard and also writes an Insights sheet to outputs. """ from __future__ import annotations from collections import Counter from datetime import datetime from typing import Any, Dict, List def compute(rows: List[Dict[str, Any]]) -> Dict[str, Any]: def _verdict(r): m = r.get("match") if m is True: return "match" if m is False: return "differ" if isinstance(m, str): return m.lower() return "" # Exclude metadata rows (Project Permalink, etc.) where verdict is # left blank — they should not inflate the total or appear in any # KPI tile. rows = [r for r in rows if _verdict(r)] total = len(rows) matches = sum(1 for r in rows if _verdict(r) == "match") differs = sum(1 for r in rows if _verdict(r) == "differ") pending = sum(1 for r in rows if _verdict(r) == "missing on both") already = sum(1 for r in rows if _verdict(r) == "missing on ai") stale = sum(1 for r in rows if _verdict(r) == "stale ai") unknown = total - matches - differs - pending - already - stale conf = Counter() for r in rows: c = (r.get("ai_confidence") or "").strip().lower() if c: conf[c.capitalize()] += 1 sources = Counter(((r.get("ai_source") or "").strip() or "Unknown") for r in rows) with_ai_date = sum(1 for r in rows if r.get("ai_date_parsed")) with_bna_review = sum(1 for r in rows if r.get("bna_review_parsed")) avg_freshness_days = None freshness_vals = [] now = datetime.utcnow() for r in rows: d = r.get("ai_date_parsed") if d: freshness_vals.append((now - d).days) if freshness_vals: avg_freshness_days = round(sum(freshness_vals) / len(freshness_vals), 1) return { "total_fields": total, "matches": matches, "differs": differs, "pending_disclosure": pending, "missing_on_ai": already, "stale_ai": stale, "unknown": unknown, "match_rate": round((matches / total) * 100, 1) if total else 0, "confidence_breakdown": dict(conf), # Recommendations sheet includes Differ + Stale AI rows. "replace_stale": differs, "replace_no_source_high_conf": 0, "keep": matches, "recommendation_total": differs + stale, "top_sources": dict(sources.most_common(5)), "fields_with_ai_date": with_ai_date, "fields_with_bna_review": with_bna_review, "avg_ai_source_age_days": avg_freshness_days, } LABELS = { "en": { "total": "Total Fields", "matches": "Matches", "differs": "Differs", "pending": "Missing on Both", "already": "Missing on AI", "stale": "Stale AI", "unknown": "Missing BNA value", "rate": "Match Rate (%)", "rep_stale": "Replace-stale BNA", "rep_nosrc": "Replace-no AI date", "rep_total": "Total Replace Recs", "keep": "Keep BNA", "ai_dated": "Fields w AI Date", "bna_reviewed": "Fields w BNA Review", "avg_age": "Avg AI Age (d)", "conf": "Confidence", "src": "Source", }, "es": { "total": "Total campos", "matches": "Coincidencias", "differs": "Diferencias", "pending": "Falta en Ambos", "already": "Falta en IA", "stale": "IA Antigua", "unknown": "Sin valor BNA", "rate": "Tasa coincidencia (%)", "rep_stale": "Reemplazar-BNA viejo", "rep_nosrc": "Reemplazar-sin fecha", "rep_total": "Total recomendaciones", "keep": "Conservar BNA", "ai_dated": "Campos c/fecha IA", "bna_reviewed": "Campos c/revision", "avg_age": "Antiguedad IA (d)", "conf": "Confianza", "src": "Fuente", }, "pt": { "total": "Total campos", "matches": "Coincidencias", "differs": "Diferencas", "pending": "Falta em Ambos", "already": "Falta em IA", "stale": "IA Antiga", "unknown": "Sem valor BNA", "rate": "Taxa coincidencia (%)", "rep_stale": "Substituir-BNA velho", "rep_nosrc": "Substituir-sem data", "rep_total": "Total recomendacoes", "keep": "Manter BNA", "ai_dated": "Campos c/data IA", "bna_reviewed": "Campos c/revisao", "avg_age": "Idade IA (d)", "conf": "Confianca", "src": "Fonte", }, } def to_table(metrics, lang="es"): L = LABELS.get(lang, LABELS["es"]) rows = [ (L["total"], metrics["total_fields"]), (L["matches"], metrics["matches"]), (L["differs"], metrics["differs"]), (L["pending"], metrics.get("pending_disclosure", 0)), (L["already"], metrics.get("missing_on_ai", 0)), (L["stale"], metrics.get("stale_ai", 0)), (L["rate"], metrics["match_rate"]), (L["rep_total"], metrics["recommendation_total"]), (L["ai_dated"], metrics["fields_with_ai_date"]), (L["avg_age"], metrics["avg_ai_source_age_days"] or "N/A"), ] for k, v in metrics["confidence_breakdown"].items(): rows.append((f"{L['conf']}: {k}", v)) for k, v in metrics["top_sources"].items(): rows.append((f"{L['src']}: {k}", v)) return rows