from fastapi import FastAPI, HTTPException from pydantic import BaseModel from transformers import pipeline import numpy as np from typing import List, Optional import uvicorn app = FastAPI() # Cargar modelo de sentimiento multilingüe (funciona en español) sentiment_pipeline = pipeline("sentiment-analysis", model="nlptown/bert-base-multilingual-uncased-sentiment") class SentimentRequest(BaseModel): texts: List[str] candidates: Optional[List[str]] = ["A", "B"] @app.get("/health") def health(): return {"status": "ok"} @app.post("/") async def analyze_sentiment(req: SentimentRequest): if not req.texts: raise HTTPException(status_code=400, detail="No texts provided") scores = [] for text in req.texts: try: # Truncar a 512 caracteres para no exceder límite del modelo result = sentiment_pipeline(text[:512])[0] # El label es algo como "1 star" ... "5 stars" label = result['label'].split()[0] score = (int(label) - 3) / 2 # Convierte 1→ -1, 3→0, 5→1 scores.append(score) except: scores.append(0.0) avg_score = np.mean(scores) if scores else 0.0 pos = sum(1 for s in scores if s > 0.2) / len(scores) if scores else 0 neg = sum(1 for s in scores if s < -0.2) / len(scores) if scores else 0 neu = 1 - pos - neg sentiments = [] for cand in req.candidates: sentiments.append({ "candidate": cand, "average_score": round(avg_score, 3), "positive_percent": round(pos, 3), "negative_percent": round(neg, 3), "neutral_percent": round(neu, 3) }) overall_trend = "positive_to_B" if avg_score > 0.2 else "negative_to_A" if avg_score < -0.2 else "neutral" return { "status": "ok", "sentiments": sentiments, "overall_trend": overall_trend } if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=7860)