Spaces:
Sleeping
Sleeping
Upload app.py with huggingface_hub
Browse files
app.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from fastapi import FastAPI, HTTPException
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
from transformers import pipeline
|
| 5 |
+
import time
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
# Estructuras de Pydantic
|
| 9 |
+
class EntradaTexto(BaseModel):
|
| 10 |
+
texto: str
|
| 11 |
+
|
| 12 |
+
class Prediccion(BaseModel):
|
| 13 |
+
sentimiento: str
|
| 14 |
+
confianza: str
|
| 15 |
+
tiempo_ms: float
|
| 16 |
+
texto: str
|
| 17 |
+
|
| 18 |
+
app = FastAPI(title="MercaLatam Sentiment Analysis", version="2.0.0")
|
| 19 |
+
|
| 20 |
+
# Carga de tu modelo local
|
| 21 |
+
classifier = pipeline("sentiment-analysis", model="./saved_model", tokenizer="./saved_model")
|
| 22 |
+
|
| 23 |
+
@app.get("/health")
|
| 24 |
+
def health():
|
| 25 |
+
return {"status": "ok", "proyecto": "MercaLatam"}
|
| 26 |
+
|
| 27 |
+
@app.post("/predict", response_model=Prediccion)
|
| 28 |
+
def predecir(entrada: EntradaTexto):
|
| 29 |
+
if not entrada.texto.strip():
|
| 30 |
+
raise HTTPException(status_code=400, detail="Texto vacío")
|
| 31 |
+
|
| 32 |
+
inicio = time.time()
|
| 33 |
+
res = classifier(entrada.texto)[0]
|
| 34 |
+
tiempo_ms = round((time.time() - inicio) * 1000, 2)
|
| 35 |
+
|
| 36 |
+
# Mapeo según tu Sesión 10
|
| 37 |
+
label_map = {"LABEL_0": "NEGATIVO 🚩", "LABEL_1": "POSITIVO ✅"}
|
| 38 |
+
sentimiento = label_map.get(res['label'], res['label'])
|
| 39 |
+
|
| 40 |
+
return Prediccion(
|
| 41 |
+
sentimiento=sentimiento,
|
| 42 |
+
confianza=f"{round(res['score'] * 100, 2)}%",
|
| 43 |
+
tiempo_ms=tiempo_ms,
|
| 44 |
+
texto=entrada.texto
|
| 45 |
+
)
|