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"] @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: 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)