Update app.py
Browse files
app.py
CHANGED
|
@@ -1,44 +1,42 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 3 |
import gradio as gr
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
# Load
|
| 6 |
-
|
| 7 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
| 8 |
-
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
| 9 |
|
| 10 |
-
#
|
| 11 |
def classify(text):
|
| 12 |
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
#
|
| 24 |
-
|
| 25 |
-
if
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
iface.launch(share=True)
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 3 |
+
import torch
|
| 4 |
|
| 5 |
+
# Load the tokenizer and model from local path (or HF if internet is available)
|
| 6 |
+
model = AutoModelForSequenceClassification.from_pretrained("ogflash/yelp_review_classifier")
|
| 7 |
+
tokenizer = AutoTokenizer.from_pretrained("ogflash/yelp_review_classifier")
|
|
|
|
| 8 |
|
| 9 |
+
# Prediction function
|
| 10 |
def classify(text):
|
| 11 |
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
| 12 |
+
|
| 13 |
+
# Remove token_type_ids if using DistilBERT
|
| 14 |
+
if "token_type_ids" in inputs:
|
| 15 |
+
inputs.pop("token_type_ids")
|
| 16 |
+
|
| 17 |
+
outputs = model(**inputs)
|
| 18 |
+
logits = outputs.logits
|
| 19 |
+
predicted_class_id = torch.argmax(logits, dim=1).item()
|
| 20 |
+
score = torch.softmax(logits, dim=1)[0][predicted_class_id].item()
|
| 21 |
+
|
| 22 |
+
# Map labels using if-elif-else
|
| 23 |
+
label = f"LABEL_{predicted_class_id}"
|
| 24 |
+
if label == "LABEL_0":
|
| 25 |
+
label_name = "Negative"
|
| 26 |
+
elif label == "LABEL_1":
|
| 27 |
+
label_name = "Neutral"
|
| 28 |
+
elif label == "LABEL_2":
|
| 29 |
+
label_name = "Positive"
|
| 30 |
+
else:
|
| 31 |
+
label_name = label # fallback
|
| 32 |
+
|
| 33 |
+
return f"{label_name} ({score * 100:.2f}%)"
|
| 34 |
+
|
| 35 |
+
# Gradio UI
|
| 36 |
+
iface = gr.Interface(fn=classify,
|
| 37 |
+
inputs=gr.Textbox(lines=2, placeholder="Enter your review here..."),
|
| 38 |
+
outputs="text",
|
| 39 |
+
title="Sentiment Classifier",
|
| 40 |
+
description="Classifies text into Positive, Neutral, or Negative.")
|
| 41 |
+
|
| 42 |
+
iface.launch()
|
|
|