-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
82 lines (58 loc) · 1.77 KB
/
app.py
File metadata and controls
82 lines (58 loc) · 1.77 KB
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
import streamlit as st
import string
import nltk
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
import os
import pickle
nltk_data_path = os.path.join(os.path.expanduser("~"), "nltk_data")
if not os.path.exists(nltk_data_path):
os.makedirs(nltk_data_path)
nltk.download('punkt', download_dir=nltk_data_path)
nltk.download('stopwords', download_dir=nltk_data_path)
nltk.download("punkt_tab", download_dir=nltk_data_path)
nltk.data.path.append(nltk_data_path)
# Initialize stemmer
ps = PorterStemmer()
# Preprocess function
def transform_text(text):
text = text.lower()
text = nltk.word_tokenize(text)
y = []
for i in text:
if i.isalnum():
y.append(i)
text = y[:]
y.clear()
for i in text:
if i not in stopwords.words('english') and i not in string.punctuation:
y.append(i)
text = y[:]
y.clear()
for i in text:
y.append(ps.stem(i))
return " ".join(y)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# Load the vectorizer
vectorizer_path = os.path.join(BASE_DIR, "vectorizer.pkl")
with open(vectorizer_path, "rb") as f:
tfidf = pickle.load(f)
# Load the trained model
model_path = os.path.join(BASE_DIR, "model.pkl")
with open(model_path, "rb") as f:
model = pickle.load(f)
# Streamlit UI
st.title("📩 SMS Spam Detection")
input_sms = st.text_area("Enter your message")
if st.button("Predict"): # only run when button clicked
# 1. Preprocess
transformed_sms = transform_text(input_sms)
# 2. Vectorize
vectorInput = tfidf.transform([transformed_sms])
# 3. Predict
result = model.predict(vectorInput)[0]
# 4. Display
if result == 0:
st.header("✅ Ham (Not Spam!)")
else:
st.header("🚨 Spam")