Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import gradio as gr
|
3 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
4 |
+
|
5 |
+
# Load model and tokenizer from Hugging Face Hub
|
6 |
+
model_name = "shukdevdatta123/twitter-distilbert-base-uncased-sentiment-analysis-lora-text-classification"
|
7 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
8 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
9 |
+
|
10 |
+
# Define the label mapping (binary sentiment: 0 = Negative, 1 = Positive)
|
11 |
+
id2label = {
|
12 |
+
0: "Negative",
|
13 |
+
1: "Positive"
|
14 |
+
}
|
15 |
+
|
16 |
+
# Set device
|
17 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
18 |
+
model.to(device)
|
19 |
+
|
20 |
+
# Define the prediction function
|
21 |
+
def predict_sentiment(text):
|
22 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True).to(device)
|
23 |
+
|
24 |
+
with torch.no_grad():
|
25 |
+
logits = model(**inputs).logits
|
26 |
+
|
27 |
+
predicted_class = torch.argmax(logits, dim=1).item()
|
28 |
+
label = id2label[predicted_class]
|
29 |
+
|
30 |
+
# Optional: add confidence score
|
31 |
+
probs = torch.nn.functional.softmax(logits, dim=1)
|
32 |
+
confidence = probs[0][predicted_class].item()
|
33 |
+
|
34 |
+
return f"{label} (Confidence: {confidence:.2f})"
|
35 |
+
|
36 |
+
# Create Gradio Interface
|
37 |
+
interface = gr.Interface(
|
38 |
+
fn=predict_sentiment,
|
39 |
+
inputs=gr.Textbox(lines=2, placeholder="Enter a sentence to analyze sentiment..."),
|
40 |
+
outputs="text",
|
41 |
+
title="Twitter Sentiment Classifier",
|
42 |
+
description="This app uses a fine-tuned DistilBERT model with LoRA adapters to predict whether a tweet or sentence is Positive or Negative."
|
43 |
+
)
|
44 |
+
|
45 |
+
# Launch the app
|
46 |
+
interface.launch()
|