File size: 1,935 Bytes
78899c6
 
 
 
 
638154a
 
78899c6
 
 
 
 
 
 
 
638154a
78899c6
 
 
 
 
 
 
 
638154a
 
 
 
 
78899c6
638154a
 
 
 
 
 
 
78899c6
638154a
 
78899c6
638154a
78899c6
638154a
78899c6
 
 
638154a
78899c6
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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]

@app.get("/")
def home():
    return {"message": "7-Emotion Analysis API is running"}

@app.post("/analyze")
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)