A7md47 commited on
Commit
d5f1b8e
·
verified ·
1 Parent(s): bc9e7af

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -26
app.py CHANGED
@@ -3,15 +3,11 @@ import json
3
  import os
4
 
5
  import torch
6
- import torch.nn.functional as F
7
  from fastapi import FastAPI, HTTPException, Request
8
  from fastapi.middleware.cors import CORSMiddleware
9
- from transformers import (
10
- AutoTokenizer,
11
- AutoModelForSequenceClassification,
12
- )
13
 
14
- app = FastAPI(title="Text Emotion Recognition")
15
 
16
  app.add_middleware(
17
  CORSMiddleware,
@@ -21,7 +17,48 @@ app.add_middleware(
21
  allow_headers=["*"],
22
  )
23
 
24
- MODEL_LABELS = ["Anger", "Disgust", "Fear", "Happy", "Neutral", "Sad", "Surprise"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
  _model = None
27
  _tokenizer = None
@@ -31,10 +68,9 @@ _device = None
31
  def load_model():
32
  global _model, _tokenizer, _device
33
  _device = "cuda" if torch.cuda.is_available() else "cpu"
34
- model_path = os.path.dirname(os.path.abspath(__file__))
35
- _tokenizer = AutoTokenizer.from_pretrained(model_path)
36
- _model = AutoModelForSequenceClassification.from_pretrained(model_path).to(_device).eval()
37
- print(f"[INFO] Model loaded on {_device}")
38
 
39
 
40
  @app.on_event("startup")
@@ -48,10 +84,47 @@ async def health():
48
  return {
49
  "status": "ok",
50
  "model_loaded": _model is not None,
 
51
  "device": _device,
52
  }
53
 
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  @app.post("/predict_b64")
56
  async def predict_b64(request: Request):
57
  try:
@@ -63,6 +136,7 @@ async def predict_b64(request: Request):
63
  text_b64 = payload.get("text", "")
64
  else:
65
  import urllib.parse
 
66
  parsed = urllib.parse.parse_qs(body.decode())
67
  raw = parsed.get("data", [None])[0]
68
  if raw is None:
@@ -78,21 +152,7 @@ async def predict_b64(request: Request):
78
  except Exception:
79
  text = text_b64
80
 
81
- inputs = _tokenizer(text, return_tensors="pt", truncation=True, max_length=512).to(_device)
82
- with torch.no_grad():
83
- outputs = _model(**inputs)
84
- probs = F.softmax(outputs.logits, dim=-1).squeeze(0)
85
-
86
- probs_np = probs.cpu().numpy()
87
- pred_idx = int(probs_np.argmax())
88
- emotion = MODEL_LABELS[pred_idx]
89
- prob_map = {c: round(float(probs_np[i]), 4) for i, c in enumerate(MODEL_LABELS)}
90
-
91
- return {
92
- "emotion": emotion,
93
- "confidence": round(float(probs_np[pred_idx]), 4),
94
- "probabilities": prob_map,
95
- }
96
  except HTTPException:
97
  raise
98
  except Exception as e:
 
3
  import os
4
 
5
  import torch
 
6
  from fastapi import FastAPI, HTTPException, Request
7
  from fastapi.middleware.cors import CORSMiddleware
8
+ from transformers import AutoModel, AutoTokenizer
 
 
 
9
 
10
+ app = FastAPI(title="Text Emotion Recognition (GoEmotions)")
11
 
12
  app.add_middleware(
13
  CORSMiddleware,
 
17
  allow_headers=["*"],
18
  )
19
 
20
+ MODEL_ID = os.environ.get("MODEL_ID", "Hidden-States/roberta-base-goemotions")
21
+
22
+ GOEMOTIONS_LABELS = [
23
+ "admiration", "amusement", "anger", "annoyance", "approval", "caring",
24
+ "confusion", "curiosity", "desire", "disappointment", "disapproval",
25
+ "disgust", "embarrassment", "excitement", "fear", "gratitude", "grief",
26
+ "joy", "love", "nervousness", "optimism", "pride", "realization",
27
+ "relief", "remorse", "sadness", "surprise", "neutral",
28
+ ]
29
+
30
+ GOEMOTION_TO_APP = {
31
+ "admiration": "Happy",
32
+ "amusement": "Happy",
33
+ "anger": "Anger",
34
+ "annoyance": "Anger",
35
+ "approval": "Happy",
36
+ "caring": "Happy",
37
+ "confusion": "Sad",
38
+ "curiosity": "Neutral",
39
+ "desire": "Happy",
40
+ "disappointment": "Sad",
41
+ "disapproval": "Anger",
42
+ "disgust": "Disgust",
43
+ "embarrassment": "Sad",
44
+ "excitement": "Happy",
45
+ "fear": "Fear",
46
+ "gratitude": "Happy",
47
+ "grief": "Sad",
48
+ "joy": "Happy",
49
+ "love": "Happy",
50
+ "nervousness": "Fear",
51
+ "optimism": "Happy",
52
+ "pride": "Happy",
53
+ "realization": "Surprise",
54
+ "relief": "Happy",
55
+ "remorse": "Sad",
56
+ "sadness": "Sad",
57
+ "surprise": "Surprise",
58
+ "neutral": "Neutral",
59
+ }
60
+
61
+ APP_LABELS = ["Anger", "Disgust", "Fear", "Happy", "Neutral", "Sad", "Surprise"]
62
 
63
  _model = None
64
  _tokenizer = None
 
68
  def load_model():
69
  global _model, _tokenizer, _device
70
  _device = "cuda" if torch.cuda.is_available() else "cpu"
71
+ _tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
72
+ _model = AutoModel.from_pretrained(MODEL_ID, trust_remote_code=True).to(_device).eval()
73
+ print(f"[INFO] Model loaded on {_device} from {MODEL_ID}")
 
74
 
75
 
76
  @app.on_event("startup")
 
84
  return {
85
  "status": "ok",
86
  "model_loaded": _model is not None,
87
+ "model_id": MODEL_ID,
88
  "device": _device,
89
  }
90
 
91
 
92
+ def _predict(text: str) -> dict:
93
+ inputs = _tokenizer(
94
+ text,
95
+ return_tensors="pt",
96
+ truncation=True,
97
+ max_length=512,
98
+ ).to(_device)
99
+
100
+ with torch.inference_mode():
101
+ outputs = _model(**inputs)
102
+
103
+ try:
104
+ logits = outputs[1]
105
+ except (IndexError, KeyError, TypeError):
106
+ logits = outputs.logits
107
+
108
+ probs = torch.sigmoid(logits).squeeze(0).cpu().numpy()
109
+
110
+ idx = int(probs.argmax())
111
+ fine_emotion = GOEMOTIONS_LABELS[idx]
112
+ emotion = GOEMOTION_TO_APP[fine_emotion]
113
+
114
+ app_probs = {label: 0.0 for label in APP_LABELS}
115
+ for label, prob in zip(GOEMOTIONS_LABELS, probs):
116
+ app_label = GOEMOTION_TO_APP[label]
117
+ app_probs[app_label] = max(app_probs[app_label], float(prob))
118
+ total = sum(app_probs.values()) or 1.0
119
+
120
+ return {
121
+ "emotion": emotion,
122
+ "confidence": round(float(probs[idx]), 4),
123
+ "fine_emotion": fine_emotion,
124
+ "probabilities": {k: round(v / total, 4) for k, v in app_probs.items()},
125
+ }
126
+
127
+
128
  @app.post("/predict_b64")
129
  async def predict_b64(request: Request):
130
  try:
 
136
  text_b64 = payload.get("text", "")
137
  else:
138
  import urllib.parse
139
+
140
  parsed = urllib.parse.parse_qs(body.decode())
141
  raw = parsed.get("data", [None])[0]
142
  if raw is None:
 
152
  except Exception:
153
  text = text_b64
154
 
155
+ return _predict(text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  except HTTPException:
157
  raise
158
  except Exception as e: