Spaces:
Build error
Build error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import pickle
|
3 |
+
import nltk
|
4 |
+
import string
|
5 |
+
from nltk.corpus import stopwords
|
6 |
+
from nltk.stem.porter import PorterStemmer
|
7 |
+
|
8 |
+
# Initialize PorterStemmer
|
9 |
+
ps = PorterStemmer()
|
10 |
+
|
11 |
+
# Load the pre-trained model and TF-IDF vectorizer
|
12 |
+
|
13 |
+
with open('model.pkl', 'rb') as fil:
|
14 |
+
model = pickle.load(fil)
|
15 |
+
with open('vectorized.pkl', 'rb') as file:
|
16 |
+
tfidf = pickle.load(file)
|
17 |
+
|
18 |
+
|
19 |
+
# Define the text preprocessing function
|
20 |
+
def update_text(text):
|
21 |
+
text = text.lower()
|
22 |
+
text = nltk.word_tokenize(text)
|
23 |
+
y = []
|
24 |
+
for i in text:
|
25 |
+
if i.isalnum():
|
26 |
+
y.append(i)
|
27 |
+
text = y[:]
|
28 |
+
y.clear()
|
29 |
+
for i in text:
|
30 |
+
if i not in stopwords.words('english') and i not in string.punctuation:
|
31 |
+
y.append(i)
|
32 |
+
text = y[:]
|
33 |
+
y.clear()
|
34 |
+
for i in text:
|
35 |
+
y.append(ps.stem(i))
|
36 |
+
|
37 |
+
return " ".join(y)
|
38 |
+
|
39 |
+
|
40 |
+
# Streamlit application title
|
41 |
+
st.title("Email/SMS Spam Classifier")
|
42 |
+
|
43 |
+
# Collecting the SMS text with a larger text area
|
44 |
+
input_sms = st.text_area("Write the Message", height=150)
|
45 |
+
|
46 |
+
# Add a button to trigger the prediction
|
47 |
+
if st.button("Predict"):
|
48 |
+
# Preprocessing the text
|
49 |
+
transformed_sms = update_text(input_sms)
|
50 |
+
|
51 |
+
# Ensure the transformed SMS is not empty before vectorizing
|
52 |
+
if transformed_sms.strip():
|
53 |
+
# Vectorizing the SMS
|
54 |
+
vectorized_input = tfidf.transform([transformed_sms])
|
55 |
+
|
56 |
+
# Convert the sparse matrix to a dense format
|
57 |
+
vectorized_input_dense = vectorized_input.toarray()
|
58 |
+
|
59 |
+
# Predicting
|
60 |
+
try:
|
61 |
+
result = model.predict(vectorized_input_dense)[0]
|
62 |
+
if result == 1:
|
63 |
+
st.header("Spam")
|
64 |
+
else:
|
65 |
+
st.header("Not Spam")
|
66 |
+
except Exception as e:
|
67 |
+
st.error(f"Error during prediction: {e}")
|
68 |
+
else:
|
69 |
+
st.warning("Please enter a valid message.")
|