Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
2 |
+
import torch
|
3 |
+
import gradio as gr
|
4 |
+
|
5 |
+
# Load model and tokenizer
|
6 |
+
model_name = "nateraw/bert-base-uncased-emotion"
|
7 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
8 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
9 |
+
|
10 |
+
# Emotion labels
|
11 |
+
labels = ['sadness', 'joy', 'love', 'anger', 'fear', 'surprise']
|
12 |
+
|
13 |
+
# Prediction function
|
14 |
+
def predict_emotion(text):
|
15 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
16 |
+
with torch.no_grad():
|
17 |
+
outputs = model(**inputs)
|
18 |
+
probs = torch.nn.functional.softmax(outputs.logits, dim=1)
|
19 |
+
pred_class = torch.argmax(probs).item()
|
20 |
+
emotion = labels[pred_class]
|
21 |
+
return f"{emotion} ({probs[0][pred_class].item()*100:.2f}% confidence)"
|
22 |
+
|
23 |
+
# Gradio Interface
|
24 |
+
interface = gr.Interface(
|
25 |
+
fn=predict_emotion,
|
26 |
+
inputs=gr.Textbox(lines=2, placeholder="Type something here..."),
|
27 |
+
outputs="text",
|
28 |
+
title="BERT-based Emotion Detection",
|
29 |
+
description="A web app that uses a fine-tuned BERT model to detect emotions from text."
|
30 |
+
)
|
31 |
+
|
32 |
+
interface.launch()
|