Spaces:
Paused
Paused
| import time | |
| import json | |
| from pathlib import Path | |
| from typing import Literal, Optional | |
| # Rutas | |
| LOG_FILE = Path("logs/registro_uso.json") | |
| USER_STATS_FILE = Path("logs/usuarios.json") | |
| # Crear carpeta si no existe | |
| LOG_FILE.parent.mkdir(parents=True, exist_ok=True) | |
| # Tipo de entrada admitida | |
| TipoEntrada = Literal["Texto", "Imagen", "PDF", "DOCX", "TXT", "Otro"] | |
| def registrar_uso( | |
| user_id: int, | |
| username: Optional[str], | |
| tipo_entrada: TipoEntrada, | |
| duracion_segundos: float, | |
| exito: bool, | |
| fuente: Optional[str] = "telegram_bot", | |
| ) -> None: | |
| """ | |
| Registra un evento de uso y actualiza el historial acumulado por usuario. | |
| """ | |
| timestamp = time.strftime("%Y-%m-%d %H:%M:%S") | |
| log_entry = { | |
| "timestamp": timestamp, | |
| "user_id": user_id, | |
| "username": username or "N/A", | |
| "tipo_entrada": tipo_entrada, | |
| "duracion_segundos": round(duracion_segundos, 2), | |
| "exito": exito, | |
| "fuente": fuente, | |
| } | |
| # Guardar log individual | |
| try: | |
| registros = [] | |
| if LOG_FILE.exists(): | |
| with open(LOG_FILE, "r", encoding="utf-8") as f: | |
| registros = json.load(f) | |
| registros.append(log_entry) | |
| with open(LOG_FILE, "w", encoding="utf-8") as f: | |
| json.dump(registros, f, indent=2, ensure_ascii=False) | |
| except Exception as e: | |
| print(f"[ERROR] No se pudo guardar el registro individual: {e}") | |
| # Actualizar conteo acumulado | |
| try: | |
| resumen = {} | |
| if USER_STATS_FILE.exists(): | |
| with open(USER_STATS_FILE, "r", encoding="utf-8") as f: | |
| resumen = json.load(f) | |
| uid = str(user_id) | |
| if uid not in resumen: | |
| resumen[uid] = { | |
| "username": username or "N/A", | |
| "total_usos": 0, | |
| "exitosos": 0, | |
| "fallidos": 0, | |
| "ultima_vez": timestamp | |
| } | |
| resumen[uid]["username"] = username or "N/A" | |
| resumen[uid]["total_usos"] += 1 | |
| resumen[uid]["ultima_vez"] = timestamp | |
| if exito: | |
| resumen[uid]["exitosos"] += 1 | |
| else: | |
| resumen[uid]["fallidos"] += 1 | |
| with open(USER_STATS_FILE, "w", encoding="utf-8") as f: | |
| json.dump(resumen, f, indent=2, ensure_ascii=False) | |
| except Exception as e: | |
| print(f"[ERROR] No se pudo actualizar el resumen de usuarios: {e}") | |