import os
import time
from typing import Dict
import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
# ==============================
# Configurations
# ==============================
MODEL_ID = os.getenv("MODEL_ID", "23f1000805/emotion-bert-t32025") # Change this to your HF model repo
LABELS = ["anger", "fear", "joy", "sadness", "surprise"]
MAX_LEN = 128
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
# ==============================
# Load model and tokenizer
# ==============================
def load_model_and_tokenizer(model_id):
try:
start_time = time.time()
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForSequenceClassification.from_pretrained(
model_id,
problem_type="multi_label_classification",
num_labels=len(LABELS),
).to(DEVICE)
model.eval()
print(f"Model loaded in {time.time() - start_time:.2f} seconds on {DEVICE}")
return tokenizer, model
except Exception as e:
print(f"Error loading model: {e}")
return None, None
tokenizer, model = load_model_and_tokenizer(MODEL_ID)
# ==============================
# Prediction function with error handling
# ==============================
@torch.inference_mode()
def predict_emotions(text: str) -> Dict[str, float]:
if not tokenizer or not model:
return {label: 0.0 for label in LABELS}
text = text.strip()
if not text:
return {label: 0.0 for label in LABELS}
try:
encoded = tokenizer(
text,
truncation=True,
padding="max_length",
max_length=MAX_LEN,
return_tensors="pt",
).to(DEVICE)
logits = model(**encoded).logits
probs = torch.sigmoid(logits)[0].cpu().tolist()
return {label: round(float(p), 4) for label, p in zip(LABELS, probs)}
except Exception as e:
print(f"Inference error: {e}")
return {label: 0.0 for label in LABELS}
# ==============================
# Custom CSS to inject
# ==============================
CUSTOM_CSS = """
.gradio-container {
max-width: 900px !important;
margin: 0 auto !important;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
#title-container h1 {
font-size: 2.4rem;
font-weight: 700;
margin-bottom: 0.3rem;
}
#title-container p {
font-size: 1rem;
color: #555;
}
.app-card {
border-radius: 16px;
border: 1px solid rgba(0, 0, 0, 0.1);
padding: 20px 20px 16px 20px;
background: linear-gradient(135deg, #f0f4f8, #d9e2ec);
box-shadow: 0 8px 12px rgba(0, 0, 0, 0.05);
}
.emotion-label .wrap {
font-size: 1rem !important;
}
.gr-button.primary {
background-color: #4c8cff !important;
border-color: #4c8cff !important;
color: white !important;
font-weight: 600 !important;
}
.gr-button.primary:hover {
background-color: #3463d9 !important;
border-color: #3463d9 !important;
}
.gr-button.secondary {
background-color: transparent !important;
border-color: #ccc !important;
color: #333 !important;
}
.gr-button.secondary:hover {
background-color: #e4e7eb !important;
}
"""
# ==============================
# Build Gradio UI with CSS injection via HTML
# ==============================
with gr.Blocks(analytics_enabled=False, title="Emotion Classifier") as demo:
# Inject CSS as raw HTML (fixes css argument issue in older gradio versions)
gr.HTML(f"")
with gr.Column():
# Title and description
with gr.Row(elem_id="title-container"):
gr.Markdown(
"""
# 🎠Emotion Classifier
Predict probabilities for anger, fear, joy, sadness, and surprise.
"""
)
gr.Markdown(
"""
Enter any English text, and the model will analyze probable emotions.
"""
)
with gr.Row():
with gr.Column(scale=4):
text_input = gr.Textbox(
label="Input Text",
placeholder="Type or paste your text here...",
lines=4,
show_label=True,
)
with gr.Row():
clear_btn = gr.Button("Clear", variant="secondary")
submit_btn = gr.Button("Analyze Emotions", variant="primary")
output_label = gr.Label(
label="Emotion Probabilities",
num_top_classes=len(LABELS),
)
with gr.Column(scale=2):
gr.Markdown("### Example inputs")
examples = [
"I am very happy today!",
"This is so scary and upsetting.",
"I feel sad and lonely.",
"What a surprising outcome!",
"I'm furious about this injustice.",
]
gr.Examples(examples, inputs=text_input, cache_examples=False)
# Footer with model info
gr.Markdown(
f"""
---
Model: `{MODEL_ID}` · Device: `{DEVICE}`
"""
)
submit_btn.click(predict_emotions, inputs=text_input, outputs=output_label, queue=True)
clear_btn.click(lambda: "", inputs=None, outputs=text_input)
if __name__ == "__main__":
demo.launch()