Spaces:
Sleeping
Sleeping
File size: 4,603 Bytes
3013601 212fd6e 3013601 aeda638 3013601 aeda638 3013601 aeda638 3013601 aeda638 3013601 aeda638 3013601 aeda638 3013601 78989d7 aeda638 78989d7 212fd6e 3013601 aeda638 3013601 aeda638 3013601 aeda638 212fd6e aeda638 3013601 aeda638 3013601 aeda638 3013601 aeda638 3013601 aeda638 3013601 212fd6e 3013601 aeda638 3013601 aeda638 3013601 aeda638 3013601 124c9e2 3013601 124c9e2 3013601 aeda638 3013601 aeda638 212fd6e 3013601 | 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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
import gradio as gr
import torch
import spaces
from transformers import (
AutoModelForSequenceClassification,
AutoTokenizer
)
# Hugging Face model repository
MODEL_ID = "Pavan97/pavan_EA_us_latest"
# Optimized validation threshold for V1
THRESHOLD = 0.25
# Emotion label mapping
id2label = {
0: "admiration",
1: "amusement",
2: "anger",
3: "annoyance",
4: "approval",
5: "caring",
6: "confusion",
7: "curiosity",
8: "desire",
9: "disappointment",
10: "disapproval",
11: "disgust",
12: "embarrassment",
13: "excitement",
14: "fear",
15: "gratitude",
16: "grief",
17: "joy",
18: "love",
19: "nervousness",
20: "optimism",
21: "pride",
22: "realization",
23: "relief",
24: "remorse",
25: "sadness",
26: "surprise",
27: "neutral"
}
label2id = {v: k for k, v in id2label.items()}
# Load model once at startup
print("Loading emotion analysis model...")
tokenizer = AutoTokenizer.from_pretrained(
MODEL_ID
)
model = AutoModelForSequenceClassification.from_pretrained(
MODEL_ID
)
if model.config.num_labels != 28:
raise ValueError(
f"Expected 28 emotion labels, "
f"but model has {model.config.num_labels}."
)
# Keep model on CPU between ZeroGPU requests
model.to("cpu")
model.eval()
print("Model loaded successfully!")
# ZeroGPU prediction function
@spaces.GPU(duration=60)
def predict(text):
if not text or not text.strip():
return {}, "Please enter some text."
device = torch.device(
"cuda" if torch.cuda.is_available() else "cpu"
)
try:
model.to(device)
# Tokenize input text
tokenized_text = tokenizer(
text,
return_tensors="pt",
truncation=True,
max_length=256
)
tokenized_text = {
key: value.to(device)
for key, value in tokenized_text.items()
}
# Perform multi-label inference
with torch.inference_mode():
outputs = model(**tokenized_text)
probabilities = torch.sigmoid(
outputs.logits[0]
).cpu().tolist()
# Convert predictions to dictionary
predicted_labels = {
id2label[idx]: float(score)
for idx, score in enumerate(probabilities)
}
# Sort by highest probability
predicted_labels = dict(
sorted(
predicted_labels.items(),
key=lambda x: x[1],
reverse=True
)
)
# Select emotions above threshold
detected_emotions = [
emotion
for emotion, score in predicted_labels.items()
if score >= THRESHOLD
]
if detected_emotions:
summary = "Detected emotions: " + ", ".join(
detected_emotions
)
else:
summary = (
"No emotions exceeded the "
f"{THRESHOLD} threshold."
)
return predicted_labels, summary
except Exception as e:
print("Prediction error:", str(e))
raise gr.Error(
"Prediction failed. Check the Space logs."
)
finally:
# Release GPU memory after each request
model.to("cpu")
if device.type == "cuda":
torch.cuda.empty_cache()
# Gradio Interface
iface = gr.Interface(
fn=predict,
inputs=gr.Textbox(
lines=3,
placeholder="Enter text to analyze emotions...",
label="Input Text"
),
outputs=[
gr.Label(
num_top_classes=5,
label="Predicted Emotions"
),
gr.Textbox(
label="Detected Emotions"
)
],
title="Emotion Analysis 2026",
description=(
"Analyze text using a fine-tuned RoBERTa model "
"trained to recognize 28 different emotions. "
"Uses multi-label classification with an "
"optimized prediction threshold of 0.25."
),
examples=[
["Thanks a lot for watching the video. I really appreciate it."],
["I am so angry that they delayed the flight again!"],
["Wow, that is absolutely fascinating! Tell me more."],
["I feel nervous about my interview tomorrow."],
["I am really happy with my achievements!"],
["I am excited about my new job but also nervous."]
],
flagging_mode="never",
cache_examples=False
)
# Launch application
if __name__ == "__main__":
iface.launch()
|