from fastapi import FastAPI, HTTPException from pydantic import BaseModel from transformers import pipeline import time import logging # 1. LOGGING (Observabilidad en tiempo real) logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s") logger = logging.getLogger(__name__) # 2. MÉTRICAS ACUMULADAS (Observabilidad: Métricas de Clase) METRICAS = { "total": 0, "exitosas": 0, "errores": 0, "tiempos": [], "confianzas": [], "distribucion": {"POSITIVO ✅": 0, "NEGATIVO 🚩": 0} } # Estructuras de Pydantic class EntradaTexto(BaseModel): texto: str class Prediccion(BaseModel): sentimiento: str confianza: str tiempo_ms: float texto: str # <--- Campo recuperado contador: int app = FastAPI(title="MercaLatam Sentiment Analysis - Observable", version="3.0.0") # Carga del modelo logger.info("Cargando modelo...") classifier = pipeline("sentiment-analysis", model="./saved_model", tokenizer="./saved_model") @app.get("/health") def health(): """Muestra todas las métricas operativas y del modelo (Sesión 16)""" tasa_error = (METRICAS["errores"] / METRICAS["total"] * 100) if METRICAS["total"] > 0 else 0 tiempo_medio = (sum(METRICAS["tiempos"]) / len(METRICAS["tiempos"])) if METRICAS["tiempos"] else 0 confianza_media = (sum(METRICAS["confianzas"]) / len(METRICAS["confianzas"])) if METRICAS["confianzas"] else 0 return { "📊 Métricas Operativas": { "Total peticiones": METRICAS["total"], "Peticiones exitosas": METRICAS["exitosas"], "Peticiones con error": METRICAS["errores"], "Tasa de error": f"{round(tasa_error, 2)}%", "Tiempo medio": f"{round(tiempo_medio, 2)}ms" }, "🧠 Métricas del Modelo": { "Confianza media": f"{round(confianza_media * 100, 2)}%", "Distribución": METRICAS["distribucion"] }, "status": "ok", "proyecto": "MercaLatam" } @app.post("/predict", response_model=Prediccion) def predecir(entrada: EntradaTexto): METRICAS["total"] += 1 inicio = time.time() if not entrada.texto.strip(): METRICAS["errores"] += 1 logger.warning("Intento de predicción con texto vacío.") raise HTTPException(status_code=400, detail="Texto vacío") try: # Inferencia res = classifier(entrada.texto)[0] tiempo_ms = round((time.time() - inicio) * 1000, 2) # Mapeo label_map = {"LABEL_0": "NEGATIVO 🚩", "LABEL_1": "POSITIVO ✅"} sentimiento = label_map.get(res['label'], res['label']) # Actualización de Métricas METRICAS["exitosas"] += 1 METRICAS["tiempos"].append(tiempo_ms) METRICAS["confianzas"].append(res['score']) METRICAS["distribucion"][sentimiento] += 1 logger.info(f"Predicción #{METRICAS['total']} procesada.") return Prediccion( sentimiento=sentimiento, confianza=f"{round(res['score'] * 100, 2)}%", tiempo_ms=tiempo_ms, texto=entrada.texto, # <--- Se devuelve el texto original contador=METRICAS["total"] ) except Exception as e: METRICAS["errores"] += 1 logger.error(f"Error en predicción: {e}") raise HTTPException(status_code=500, detail="Error interno")