yoyplay's picture
Upload app.py with huggingface_hub
099ca1f verified
Raw History Blame Contribute Delete
1.26 kB
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from transformers import pipeline
import time
import torch
# Estructuras de Pydantic
class EntradaTexto(BaseModel):
texto: str
class Prediccion(BaseModel):
sentimiento: str
confianza: str
tiempo_ms: float
texto: str
app = FastAPI(title="MercaLatam Sentiment Analysis", version="2.0.0")
# Carga de tu modelo local
classifier = pipeline("sentiment-analysis", model="./saved_model", tokenizer="./saved_model")
@app.get("/health")
def health():
return {"status": "ok", "proyecto": "MercaLatam"}
@app.post("/predict", response_model=Prediccion)
def predecir(entrada: EntradaTexto):
if not entrada.texto.strip():
raise HTTPException(status_code=400, detail="Texto vacío")
inicio = time.time()
res = classifier(entrada.texto)[0]
tiempo_ms = round((time.time() - inicio) * 1000, 2)
# Mapeo según tu Sesión 10
label_map = {"LABEL_0": "NEGATIVO 🚩", "LABEL_1": "POSITIVO ✅"}
sentimiento = label_map.get(res['label'], res['label'])
return Prediccion(
sentimiento=sentimiento,
confianza=f"{round(res['score'] * 100, 2)}%",
tiempo_ms=tiempo_ms,
texto=entrada.texto
)