Spaces:
Running
Running
| from fastapi import FastAPI, HTTPException | |
| from pydantic import BaseModel | |
| from transformers import pipeline | |
| from typing import List | |
| # NEW MODEL: Detects 7 Emotions (Joy, Anger, Disgust, Fear, Sadness, Surprise, Neutral) | |
| sentiment_pipeline = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base", top_k=1) | |
| app = FastAPI() | |
| class TextInput(BaseModel): | |
| sentences: List[str] | |
| def home(): | |
| return {"message": "7-Emotion Analysis API is running"} | |
| def analyze(data: TextInput): | |
| try: | |
| # Analyze the list of sentences | |
| results = sentiment_pipeline(data.sentences, truncation=True, max_length=512) | |
| processed_results = [] | |
| for res_list in results: | |
| # The pipeline returns a list of scores, we take the top one | |
| top_result = res_list[0] | |
| label = top_result['label'] # e.g., 'joy', 'anger', 'neutral' | |
| score = top_result['score'] | |
| # --- CALCULATE POLARITY FOR GAUGE --- | |
| # We map the 7 emotions to a -1 to 1 scale so your Gauge still works. | |
| if label == 'joy': | |
| polarity = score # Positive | |
| elif label in ['anger', 'disgust', 'fear', 'sadness']: | |
| polarity = -score # Negative | |
| else: | |
| polarity = 0.0 # Neutral or Surprise (Surprise is usually neutral context) | |
| processed_results.append({ | |
| "label": label, # This will send "anger", "joy", etc. to your Table | |
| "confidence": score, | |
| "polarity": polarity # This drives the Gauge | |
| }) | |
| return {"results": processed_results} | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run(app, host="0.0.0.0", port=7860) |