Pavan97's picture
Update app.py
aeda638 verified
Raw History Blame Contribute Delete
4.6 kB
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()