Spaces:
Sleeping
Sleeping
File size: 2,667 Bytes
f71f36c cc3ee34 0c9138a cc3ee34 23f8dc2 cc3ee34 dc1163c 95022a0 dc1163c 95022a0 dc1163c 95022a0 cc3ee34 9fbe637 dc1163c 9fbe637 cc3ee34 dc1163c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | import streamlit as st
import pickle
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing.sequence import pad_sequences
# 1. SETUP VARIABLES
max_length = 50
# 2. LOAD ASSETS (Cached so it only loads once)
@st.cache_resource
def load_model_and_tokenizer():
model = load_model('src/best_lstm_model.keras')
with open("src/spam_tokenizer.pickle", "rb") as handle:
tokenizer = pickle.load(handle)
return model, tokenizer
try:
model, tokenizer = load_model_and_tokenizer()
except Exception as e:
st.error(f"Error loading model assets: {e}")
# 3. STREAMLIT INTERFACE LAYOUT
st.title("🚫 LSTM Spam Email Detector")
st.write("Please type or paste an email below to check if it's Spam or Ham.")
# Text Box for User Input
user_message = st.text_area("Email Message", height=150, placeholder="Enter your text here...")
# Analyze Button
if st.button("Predict"):
if user_message.strip() == "":
st.warning("Please enter a message to analyze.")
else:
# Preprocess text input
cleaned_message = str(user_message).lower()
data_sequences = tokenizer.texts_to_sequences([cleaned_message])
data_padded = pad_sequences(data_sequences, maxlen=max_length, padding='post', truncating='post')
processed_text = np.array([data_padded[0]])
# Run inference
prediction = model.predict(processed_text)
# Extract the exact single number from the array layer
prediction_score = float(prediction[0][0])
# Extra validation for short texts: look for high-risk text indicators
spam_keywords = ["won", "winner", "prize", "gift card", "claim", "usd", "cash", "urgent"]
has_trigger_words = any(word in user_message.lower() for word in spam_keywords)
# Decision Logic (Combines your 0.80 metric with trigger keyword validation)
if prediction_score >= 0.80 or (prediction_score > 0.10 and has_trigger_words): # SPAM EMAIL FOLLOW THIS CONDITION
st.error(f"🚨 **SPAM** (Confidence score: {prediction_score:.2%})")
else:
st.success(f"✅ **HAM / LEGITIMATE** (Confidence score: {prediction_score:.2%})")
# Extract the exact decimal scalar score
# prediction_score = float(prediction[0][0])
# Display output based on your 0.6 precision threshold
# if prediction_score > 0.80:
# st.error(f"🚨 **SPAM** (Confidence score: {prediction_score:.2f})")
#else:
# st.success(f"✅ **HAM / LEGITIMATE** (Confidence score: {prediction_score:.2f})")
|