File size: 1,257 Bytes
099ca1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

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
    )