import csv import os import shutil from collections import Counter from loguru import logger _MONITOR_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) _server_dir = os.environ.get("MONITOR_SERVER_DIR") _CSV_PATH = os.path.join(_server_dir if _server_dir else _MONITOR_DIR, "NEW_MonitorOsservatorio", "TABELLA DECODIFICA RETI.CSV") _table: list[dict] = [] # [{PAESE, ORIGINALE, DECODIFICATO}] def load(): global _table try: with open(_CSV_PATH, newline='', encoding='latin-1') as f: reader = csv.DictReader(f, delimiter=';') _table = [dict(r) for r in reader] logger.info("Tabella decodifica reti caricata: {} reti", len(_table)) except Exception as e: logger.warning("Impossibile caricare tabella decodifica reti: {}", e) _table = [] def decode_channel(channel: str) -> tuple[str, str]: """Returns (decodificato, paese). Falls back to (channel, '') if not found.""" ch = (channel or "").strip() for row in _table: if row.get('ORIGINALE', '').strip().upper() == ch.upper(): return row.get('DECODIFICATO', ch).strip(), row.get('PAESE', '').strip() return ch, '' def detect_paese(records) -> str: """Detect country by majority vote across all channels in the file.""" paesi = [] for r in records: _, paese = decode_channel(r.channel) if paese: paesi.append(paese) if not paesi: return '' return Counter(paesi).most_common(1)[0][0] def get_table() -> list[dict]: return list(_table) def add_row(paese: str, originale: str, decodificato: str): _table.append({'PAESE': paese, 'ORIGINALE': originale, 'DECODIFICATO': decodificato}) _save() def delete_row(idx: int): if 0 <= idx < len(_table): _table.pop(idx) _save() def save_table(rows: list[dict]): global _table _table = [{'PAESE': r.get('PAESE','').strip(), 'ORIGINALE': r.get('ORIGINALE','').strip(), 'DECODIFICATO': r.get('DECODIFICATO','').strip()} for r in rows if r.get('ORIGINALE','').strip()] _save() def _backup_path(n: int) -> str: base = _CSV_PATH.rsplit('.', 1) return f"{base[0]}_backup_{n}.CSV" def _rotate_backups(): if not os.path.exists(_CSV_PATH): return for i in range(3, 1, -1): src = _backup_path(i - 1) dst = _backup_path(i) if os.path.exists(src): shutil.copy2(src, dst) shutil.copy2(_CSV_PATH, _backup_path(1)) def _save(): _rotate_backups() with open(_CSV_PATH, 'w', newline='', encoding='latin-1') as f: writer = csv.DictWriter(f, fieldnames=['PAESE', 'ORIGINALE', 'DECODIFICATO'], delimiter=';') writer.writeheader() writer.writerows(_table) logger.info("Tabella decodifica reti salvata: {} reti", len(_table))