TajWaliKhan commited on
Commit
d75ea57
·
verified ·
1 Parent(s): ede1a92

Upload 3 files

Browse files
AI_Smart_Email_Security_System.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
email_spam_calsifier.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Email_spam_calsifier
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1obsGCm8CluG_jKB59HlJAlyO5movzKD_
8
+
9
+ # IMPORT LIBRARIES
10
+ """
11
+
12
+ import numpy as np
13
+ import pandas as pd
14
+ import matplotlib.pyplot as plt
15
+ import pickle
16
+
17
+ from sklearn.model_selection import train_test_split
18
+ from sklearn.feature_extraction.text import TfidfVectorizer
19
+ from sklearn.svm import SVC
20
+ from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
21
+ from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
22
+
23
+ """#**LOAD DATA**"""
24
+
25
+ df = pd.read_csv('/content/mail_data.csv')
26
+
27
+ # Replace null values
28
+ data = df.where((pd.notnull(df)), '')
29
+
30
+ # Convert labels
31
+ data.loc[data['Category'] == 'spam', 'Category'] = 0
32
+ data.loc[data['Category'] == 'ham', 'Category'] = 1
33
+
34
+ # Separate features and labels
35
+ x = data['Message']
36
+ y = data['Category'].astype('int')
37
+
38
+ """#**TRAIN TEST SPLIT**
39
+
40
+ """
41
+
42
+ x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=3)
43
+
44
+ """#**TF-IDF**"""
45
+
46
+ tfidf = TfidfVectorizer(min_df=1, stop_words='english', lowercase=True)
47
+
48
+ x_train_features = tfidf.fit_transform(x_train)
49
+ x_test_features = tfidf.transform(x_test)
50
+
51
+ """#**SVM MODEL**"""
52
+
53
+ model = SVC()
54
+
55
+ model.fit(x_train_features, y_train)
56
+
57
+ """#**PREDICTIONS**"""
58
+
59
+ train_pred = model.predict(x_train_features)
60
+ test_pred = model.predict(x_test_features)
61
+
62
+ """#**EVALUATION**"""
63
+
64
+ train_acc = accuracy_score(y_train, train_pred)
65
+ test_acc = accuracy_score(y_test, test_pred)
66
+
67
+ precision = precision_score(y_test, test_pred)
68
+ recall = recall_score(y_test, test_pred)
69
+ f1 = f1_score(y_test, test_pred)
70
+
71
+ print("Training Accuracy:", train_acc)
72
+ print("Testing Accuracy:", test_acc)
73
+ print("Precision:", precision)
74
+ print("Recall:", recall)
75
+ print("F1 Score:", f1)
76
+
77
+ """#**SAMPLE TEST**"""
78
+
79
+ sample = ["claim your free gift card today"]
80
+
81
+ sample_vec = tfidf.transform(sample)
82
+ result = model.predict(sample_vec)
83
+
84
+ print("\nPrediction:", "Ham" if result[0] == 1 else "Spam")
85
+
86
+ """#**SAVE MODEL**"""
87
+
88
+ pickle.dump(model, open("email_model.pkl", "wb"))
89
+ pickle.dump(tfidf, open("email_vectorizer.pkl", "wb"))
90
+
91
+ from google.colab import files
92
+ files.download("email_model.pkl")
93
+ files.download("email_vectorizer.pkl")
94
+
95
+ """#**BAR CHART**"""
96
+
97
+ plt.figure()
98
+ data['Category'].value_counts().plot(kind='bar')
99
+ plt.title("Spam vs Ham Emails")
100
+ plt.xlabel("Category (0=Spam, 1=Ham)")
101
+ plt.ylabel("Count")
102
+ plt.savefig("bar_chart.png")
103
+ plt.show()
104
+
105
+ """#**CONFUSION MATRIX**"""
106
+
107
+ cm = confusion_matrix(y_test, test_pred)
108
+ disp = ConfusionMatrixDisplay(confusion_matrix=cm)
109
+ disp.plot()
110
+ plt.savefig("confusion_matrix.png")
111
+ plt.show()
112
+
113
+ """#**ACCURACY COMPARISON**"""
114
+
115
+ plt.figure()
116
+ plt.bar(['Train Accuracy', 'Test Accuracy'], [train_acc, test_acc])
117
+ plt.title("Train vs Test Accuracy")
118
+ plt.savefig("accuracy_graph.png")
119
+ plt.show()
120
+
121
+ """#**DOWNLOAD GRAPHS**"""
122
+
123
+ files.download("bar_chart.png")
124
+ files.download("confusion_matrix.png")
125
+ files.download("accuracy_graph.png")
126
+
127
+ !pip install streamlit pyngrok
128
+
129
+ # Commented out IPython magic to ensure Python compatibility.
130
+ # %%writefile app.py
131
+ # import streamlit as st
132
+ # import pickle
133
+ #
134
+ # model = pickle.load(open("email_model.pkl", "rb"))
135
+ # tfidf = pickle.load(open("email_vectorizer.pkl", "rb"))
136
+ #
137
+ # st.title("Email Spam Detection App")
138
+ #
139
+ # user_input = st.text_area("Type your email here:")
140
+ #
141
+ # if st.button("Predict"):
142
+ # if user_input.strip() == "":
143
+ # st.warning("Please enter some text!")
144
+ # else:
145
+ # input_features = tfidf.transform([user_input])
146
+ # prediction = model.predict(input_features)
147
+ # st.success("Ham Email " if prediction[0]==1 else "Spam Email ")
148
+
149
+ !npm install -g localtunnel
150
+
151
+ !streamlit run app.py & npx localtunnel --port 8501
spam.csv ADDED
The diff for this file is too large to render. See raw diff