Spaces:
Sleeping
Sleeping
| 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="<OOV>") | |
| 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""" | |
| <div style="color:{color}; font-size: 22px; font-weight: bold;">{label}</div> | |
| <div style="font-size: 16px; margin-top: 5px;">Confidence: {pred*100:.2f}%</div> | |
| <div style="margin-top: 10px;">{advice}</div> | |
| """ | |
| # 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() | |