Spaces:
Build error
Build error
Download app.py from Srey72/agent_sentiment03: direct link, hf CLI and curl.
- Browser
- Download file 1.57 kB
-
https://huggingface.co/spaces/Srey72/agent_sentiment03/resolve/main/app.py
- Command line
-
hf download hf://spaces/Srey72/agent_sentiment03/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Srey72/agent_sentiment03/resolve/main/app.py
1.57 kB
| from fastapi import FastAPI, HTTPException | |
| from pydantic import BaseModel | |
| from textblob import TextBlob | |
| import numpy as np | |
| from typing import List, Optional | |
| import uvicorn | |
| app = FastAPI() | |
| 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: | |
| blob = TextBlob(text) | |
| scores.append(blob.sentiment.polarity) | |
| 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) |