LSTM_spam_ham / app.py
Aswin337's picture
Update app.py
1c9f84d verified
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()