File size: 2,892 Bytes
cdf1735
 
 
 
 
 
 
e9422ac
 
 
 
 
cdf1735
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9422ac
 
cdf1735
 
 
 
 
 
 
 
 
e9422ac
cdf1735
e9422ac
cdf1735
e9422ac
 
 
 
 
 
 
cdf1735
 
 
 
 
 
 
 
 
e9422ac
cdf1735
 
 
 
 
 
 
 
 
e9422ac
cdf1735
e9422ac
 
 
 
 
 
 
 
 
cdf1735
 
e9422ac
cdf1735
 
e9422ac
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# app.py

import re
import joblib
import pandas as pd
import streamlit as st

# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
# 0) Must set page config first
# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
st.set_page_config(page_title="E-mail Spam Detection", layout="centered")

# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
# 1) Text cleaning & feature functions
# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

def clean_text(text: str) -> str:
    text = re.sub(r'[\r\n\t]+', ' ', text)
    text = re.sub(r'https?://\S+', ' URL ', text)
    text = re.sub(r'[^a-z0-9\s]', ' ', text)
    text = re.sub(r'\s{2,}', ' ', text)
    return text.strip()

def featurize(title: str, body: str) -> pd.DataFrame:
    raw = f"{title or ''} {body or ''}"
    txt = clean_text(raw.lower())
    return pd.DataFrame([{
        'content':     txt,
        'msg_len':     len(txt),
        'digit_count': len(re.findall(r'\d', txt)),
        'url_count':   txt.count('URL'),
        'key_flag':    int(
            bool(re.search(r'(opportunity|reward|service)', txt))
            and (bool(re.search(r'\d', txt)) or 'URL' in txt)
        )
    }])

# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
# 2) Load models/artifacts once
# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
@st.cache_resource
def load_models():
    """
    Loads the deploy pipeline (preprocessor + calibrated RF) and threshold.
    This runs only once per session.
    """
    deploy_pipe = joblib.load('spam_deploy_pipeline.pkl')
    threshold   = joblib.load('spam_threshold.pkl')
    return deploy_pipe, threshold

pipe, thresh = load_models()

# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
# 3) Streamlit UI
# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”

st.title("πŸ“§ E-mail Spam Detector")
st.markdown(
    "Enter an e-mail **Subject** and **Body** below, then click **Predict** "
    "to see the spam probability and label."
)

with st.form("input_form"):
    subj = st.text_input("Subject / Title")
    body = st.text_area("Body text", height=200)
    submitted = st.form_submit_button("Predict")

if submitted:
    # 1) featurize
    X = featurize(subj, body)

    # 2) predict
    proba = pipe.predict_proba(X)[0, 1]
    is_spam = (proba >= thresh)

    # 3) display
    st.metric("Spam probability", f"{proba:.1%}")
    if is_spam:
        st.subheader("🚫 SPAM")
        st.warning("This message is classified as spam. Proceed with caution!")
    else:
        st.subheader("βœ… Not Spam")
        st.success("This message looks clean.")

    st.divider()
    st.caption(f"Decision threshold (Fβ‚‚-optimized): {thresh:.2f}")