Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import BertTokenizer, BertForSequenceClassification
|
| 4 |
+
|
| 5 |
+
model_path = "my_model"
|
| 6 |
+
|
| 7 |
+
tokenizer = BertTokenizer.from_pretrained(model_path)
|
| 8 |
+
model = BertForSequenceClassification.from_pretrained(model_path)
|
| 9 |
+
|
| 10 |
+
device = torch.device("cpu")
|
| 11 |
+
model.to(device)
|
| 12 |
+
model.eval()
|
| 13 |
+
|
| 14 |
+
def predict(text):
|
| 15 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
| 16 |
+
|
| 17 |
+
with torch.no_grad():
|
| 18 |
+
outputs = model(**inputs)
|
| 19 |
+
|
| 20 |
+
logits = outputs.logits
|
| 21 |
+
probs = torch.softmax(logits, dim=1)
|
| 22 |
+
|
| 23 |
+
predicted_class = torch.argmax(probs, dim=1).item()
|
| 24 |
+
confidence = probs[0][predicted_class].item()
|
| 25 |
+
|
| 26 |
+
label = "Positive 😊" if predicted_class == 1 else "Negative 😡"
|
| 27 |
+
|
| 28 |
+
return f"{label} (Confidence: {confidence:.2f})"
|
| 29 |
+
|
| 30 |
+
demo = gr.Interface(
|
| 31 |
+
fn=predict,
|
| 32 |
+
inputs=gr.Textbox(lines=3, placeholder="Enter text..."),
|
| 33 |
+
outputs="text",
|
| 34 |
+
title="🎬 Sentiment Analyzer",
|
| 35 |
+
description="BERT-based sentiment classifier"
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
demo.launch()
|