Update app.py
Browse files
app.py
CHANGED
|
@@ -1,51 +1,55 @@
|
|
| 1 |
-
import
|
| 2 |
-
from transformers import AutoTokenizer
|
| 3 |
-
import
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
# Get
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 3 |
+
import torch
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
# Load model and tokenizer with authentication
|
| 7 |
+
model_name = "Anurag3703/bert-spam-classifier"
|
| 8 |
+
token = os.environ.get("HF_TOKEN") # Get token from environment
|
| 9 |
+
|
| 10 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, token=token)
|
| 11 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_name, token=token)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def classify_text(text):
|
| 15 |
+
"""Classify text as spam or not spam"""
|
| 16 |
+
# Tokenize input
|
| 17 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
|
| 18 |
+
|
| 19 |
+
# Get predictions
|
| 20 |
+
with torch.no_grad():
|
| 21 |
+
outputs = model(**inputs)
|
| 22 |
+
predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
| 23 |
+
|
| 24 |
+
# Get probabilities
|
| 25 |
+
ham_prob = predictions[0][0].item()
|
| 26 |
+
spam_prob = predictions[0][1].item()
|
| 27 |
+
|
| 28 |
+
return {
|
| 29 |
+
"Not Spam (Ham)": ham_prob,
|
| 30 |
+
"Spam": spam_prob
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# Create Gradio interface
|
| 35 |
+
demo = gr.Interface(
|
| 36 |
+
fn=classify_text,
|
| 37 |
+
inputs=gr.Textbox(
|
| 38 |
+
lines=3,
|
| 39 |
+
placeholder="Enter a message to classify...",
|
| 40 |
+
label="Input Text"
|
| 41 |
+
),
|
| 42 |
+
outputs=gr.Label(num_top_classes=2, label="Classification Results"),
|
| 43 |
+
title="BERT Spam Classifier",
|
| 44 |
+
description="Enter a text message to check if it's spam or not spam.",
|
| 45 |
+
examples=[
|
| 46 |
+
["Win a free iPhone now! Click here!"],
|
| 47 |
+
["Hey, can we meet for coffee tomorrow?"],
|
| 48 |
+
["URGENT: Your account will be closed. Verify now!"],
|
| 49 |
+
["Thanks for the meeting today, let's catch up next week."]
|
| 50 |
+
],
|
| 51 |
+
theme="soft"
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
if __name__ == "__main__":
|
| 55 |
+
demo.launch()
|