Spaces:
No application file
No application file
Download app.py from Srey72/agent-sentiment: direct link, hf CLI and curl.
- Browser
- Download file 2.05 kB
-
https://huggingface.co/spaces/Srey72/agent-sentiment/resolve/main/app.py
- Command line
-
hf download hf://spaces/Srey72/agent-sentiment/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Srey72/agent-sentiment/resolve/main/app.py
2.05 kB
| 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"] | |
| def health(): | |
| return {"status": "ok"} | |
| 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) |