Spaces:
Sleeping
Sleeping
import gradio as gr | |
from datasets import load_dataset | |
from sklearn.feature_extraction.text import TfidfVectorizer | |
from sklearn.naive_bayes import MultinomialNB | |
from sklearn.pipeline import make_pipeline | |
from sklearn.model_selection import train_test_split | |
from sklearn.metrics import accuracy_score | |
# 1. Load dataset | |
dataset = load_dataset("ucirvine/sms_spam", split="train") | |
texts = dataset["sms"] | |
labels = [1 if label == "spam" else 0 for label in dataset["label"]] # spam=1, ham=0 | |
# 2. Train/test split | |
X_train, X_test, y_train, y_test = train_test_split(texts, labels, test_size=0.2, random_state=42) | |
# 3. Create model pipeline (TF-IDF + Naive Bayes) | |
model = make_pipeline(TfidfVectorizer(), MultinomialNB()) | |
model.fit(X_train, y_train) | |
# 4. Accuracy for reference | |
y_pred = model.predict(X_test) | |
print("Validation Accuracy:", accuracy_score(y_test, y_pred)) | |
# 5. Gradio interface | |
def predict_spam(message): | |
pred = model.predict([message])[0] | |
return "π© Not Spam (Ham)" if pred == 0 else "π« Spam" | |
iface = gr.Interface( | |
fn=predict_spam, | |
inputs=gr.Textbox(lines=4, label="Enter your SMS message"), | |
outputs=gr.Text(label="Prediction"), | |
title="π¬ SMS Spam Detector", | |
description="Classifies whether an SMS message is spam or not using a Naive Bayes model." | |
) | |
if __name__ == "__main__": | |
iface.launch(share=False) | |