import gradio as gr import numpy as np import pandas as pd import tensorflow as tf from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.models import load_model # Step 1: Load and recreate tokenizer df = pd.read_csv("dataset.csv", encoding='latin-1')[['text_type', 'text']] df.columns = ['label', 'message'] tokenizer = Tokenizer(num_words=5000, oov_token="") tokenizer.fit_on_texts(df['message']) # Step 2: Load trained model model = load_model("spam_detection_model.h5") max_length = 100 # Step 3: Prediction function with confidence, color, and audio trigger history_list = [] audio_path = "audio.mpeg" def predict_message(msg): seq = tokenizer.texts_to_sequences([msg]) padded = pad_sequences(seq, maxlen=max_length, padding='post') pred = model.predict(padded)[0][0] label = "๐Ÿšซ SPAM" if pred > 0.5 else "โœ… HAM" color = "red" if pred > 0.5 else "green" advice = "โš ๏ธ Don't click unknown links!" if pred > 0.5 else "๐Ÿ“จ Safe to read." history_list.append((msg, f"{label} ({pred*100:.2f}%)")) html_output = f"""
{label}
Confidence: {pred*100:.2f}%
{advice}
""" # Return audio only if SPAM return html_output, history_list[-5:], audio_path if pred > 0.5 else None # Step 4: Gradio UI with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown(""" # ๐Ÿ“ฉ SMS Spam Classifier _Check if your message is spam or not using a powerful LSTM neural network._ - ๐Ÿ’ก Type your message below - ๐Ÿง  Trained on real-world SMS dataset - ๐Ÿšจ Hear a warning if it's spam! """) msg_input = gr.Textbox(label="Enter SMS Text", placeholder="E.g. You've won โ‚น10,000 cash prize!", lines=2) submit_btn = gr.Button("๐Ÿ” Analyze") clear_btn = gr.Button("๐Ÿงน Clear History") result = gr.HTML() history = gr.Dataframe(headers=["Message", "Prediction"], label="๐Ÿ“‹ Prediction History", interactive=False) audio_out = gr.Audio(label="๐Ÿ”Š Spam Alert", interactive=False, autoplay=True) def clear_history(): history_list.clear() return None, [], None submit_btn.click(predict_message, inputs=msg_input, outputs=[result, history, audio_out]) clear_btn.click(clear_history, inputs=[], outputs=[result, history, audio_out]) demo.launch()