-
Notifications
You must be signed in to change notification settings - Fork 0
/
hack_o_hire.py
410 lines (319 loc) · 12.8 KB
/
hack_o_hire.py
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# -*- coding: utf-8 -*-
"""Hack-o-hire.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1LuC9E6HuqZxhRa-t0zYUO18n-3H9PdRn
# DATA EXPLORATION
"""
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
train = pd.read_csv('/content/Train - Email Classification.csv')
plt.figure(figsize=(8, 10))
sns.countplot(y='industry', palette='viridis', data=train)
plt.title('Class Distribution', size=15)
plt.show()
"""# NAIVE BASEIAN MODEL
"""
import pandas as pd
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
train=pd.read_csv('/content/Train - Email Classification.csv')
test=pd.read_csv('/content/Test - Email Classification.csv')
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('wordnet')
def preprocess_text(text):
text=text.lower()
tokens=word_tokenize(text)
stop_words=set(stopwords.words('english'))
tokens = [word for word in tokens if word not in stop_words]
lemmatizer = WordNetLemmatizer()
tokens = [lemmatizer.lemmatize(word) for word in tokens]
return ' '.join(tokens)
train['proc_pre_text']=train['pre_text'].apply(preprocess_text)
train['proc_post_text']=train['post_text'].apply(preprocess_text)
train['new_col']=train['proc_pre_text']+train['proc_post_text']
print(train['new_col'].head().loc[0])
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, classification_report,f1_score
from sklearn.model_selection import train_test_split
X=train['new_col']
Y=train['industry']
tfidf_vectorizer = TfidfVectorizer()
X_tfidf = tfidf_vectorizer.fit_transform(X)
test['proc_pre_text']=test['pre_text'].apply(preprocess_text)
test['proc_post_text']=test['post_text'].apply(preprocess_text)
test['new_col']=test['proc_pre_text']+test['proc_post_text']
X_test_tfidf = tfidf_vectorizer.transform(test['new_col'])
X_train,X_test,Y_train,Y_test=train_test_split(X_tfidf,Y,test_size=0.25,random_state=42)
naive_bayes_classifier = MultinomialNB()
model=naive_bayes_classifier.fit(X_train,Y_train)
y_pred = model.predict(X_test)
print(y_pred)
accuracy = accuracy_score(Y_test, y_pred)
print("Accuracy:", accuracy)
f1 = f1_score(Y_test,y_pred,average=None)
print("F1 score:",f1)
y_pred_test = model.predict(X_test_tfidf)
print(y_pred_test)
test['industry'] = y_pred_test
df_plot = pd.DataFrame(y_pred_test)
plt.figure(figsize=(8, 10))
sns.countplot(y='industry', palette='viridis', data=test)
plt.title('Class Distribution', size=15)
plt.show()
"""# SUPPORT VECTOR MACHINE"""
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import svm
from sklearn.metrics import confusion_matrix,accuracy_score,roc_auc_score
clf=svm.SVC(kernel='linear')
model1=clf.fit(X_train,Y_train)
y_pred1=model1.predict(X_test)
acc1=accuracy_score(Y_test,y_pred1)
print(acc1)
f1 = f1_score(Y_test,y_pred1,average=None)
print("F1 score:",f1)
y_pred2=model1.predict(X_test_tfidf)
print(y_pred2)
test['svm_industry'] = y_pred2
plt.figure(figsize=(8, 10))
sns.countplot(y='svm_industry', palette='viridis', data=test)
plt.title('Class Distribution', size=15)
plt.show()
import pandas as pd
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
train=pd.read_csv('/content/Train - Email Classification.csv')
test=pd.read_csv('/content/Test - Email Classification.csv')
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('wordnet')
def preprocess_text(text):
text=text.lower()
tokens=word_tokenize(text)
stop_words=set(stopwords.words('english'))
tokens = [word for word in tokens if word not in stop_words]
lemmatizer = WordNetLemmatizer()
tokens = [lemmatizer.lemmatize(word) for word in tokens]
return ' '.join(tokens)
train['proc_pre_text']=train['pre_text'].apply(preprocess_text)
train['proc_post_text']=train['post_text'].apply(preprocess_text)
train['new_col']=train['proc_pre_text']+train['proc_post_text']
print(train['new_col'].head().loc[0])
#NAIVE BAYES
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, classification_report
from sklearn.model_selection import train_test_split
X=train['new_col']
Y=train['industry']
tfidf_vectorizer = TfidfVectorizer()
X_tfidf = tfidf_vectorizer.fit_transform(X)
test['proc_pre_text']=test['pre_text'].apply(preprocess_text)
test['proc_post_text']=test['post_text'].apply(preprocess_text)
test['new_col']=test['proc_pre_text']+test['proc_post_text']
X_test_tfidf = tfidf_vectorizer.transform(test['new_col'])
X_train,X_test,Y_train,Y_test=train_test_split(X_tfidf,Y,test_size=0.25,random_state=42)
naive_bayes_classifier = MultinomialNB()
model=naive_bayes_classifier.fit(X_train,Y_train)
y_pred = model.predict(X_test)
print(y_pred)
accuracy = accuracy_score(Y_test, y_pred)
print("Accuracy NB:", accuracy)
y_pred_test = model.predict(X_test_tfidf)
print(y_pred_test)
#SVM
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import svm
from sklearn.metrics import confusion_matrix,accuracy_score,roc_auc_score
clf=svm.SVC(kernel='linear')
model1=clf.fit(X_train,Y_train)
y_pred1=model1.predict(X_test)
acc1=accuracy_score(Y_test,y_pred1)
print(acc1)
y_pred2=model1.predict(X_test_tfidf)
print(y_pred2)
import imaplib
import email
from datetime import datetime, timedelta
def extract_body(payload):
if isinstance(payload, str):
return payload
elif isinstance(payload, bytes):
return payload.decode('utf-8')
else:
return None
def mail_extract():
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('[email protected]', 'July@2023')
mail.select('inbox')
today = datetime.today().strftime('%d-%b-%Y')
result, data = mail.search(None, '(UNSEEN)', '(SINCE "' + today + '")')
emails_data = []
if result == 'OK':
mail_ids = data[0].split()
for mail_id in mail_ids:
result, message_data = mail.fetch(mail_id, '(RFC822)')
raw_email = message_data[0][1]
msg = email.message_from_bytes(raw_email)
email_subject = msg['subject']
email_from = msg['from']
# Extracting the email body
if msg.is_multipart():
for part in msg.walk():
content_type = part.get_content_type()
content_disposition = str(part.get("Content-Disposition"))
if "attachment" not in content_disposition:
body = part.get_payload(decode=True)
body = extract_body(body)
if body:
emails_data.append({'From': email_from, 'Subject': email_subject, 'Body': body})
else:
body = msg.get_payload(decode=True)
body = extract_body(body)
if body:
emails_data.append({'From': email_from, 'Subject': email_subject, 'Body': body})
else:
print("No unread emails found.")
mail.close()
mail.logout()
# Extract only the email bodies into a list
email_bodies = [email_data['Body'] for email_data in emails_data]
return email_bodies
# Usage example
email_bodies = mail_extract()
print(email_bodies)
import imaplib
import email
from datetime import datetime, timedelta
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
from sklearn.feature_extraction.text import TfidfVectorizer
# Define Gmail credentials
gmail_user = "[email protected]"
gmail_password = "July@2023"
# Define the label dictionary
'''label_dict = {
0: '[email protected]', # Technical
1: '[email protected]', # Finance
2: '[email protected]', # Energy
3: '[email protected]', # Pharmaceuticals
4: '[email protected]' # Travel
}'''
# Define your send_email function
def send_email(to, subject, body):
try:
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(gmail_user, to, msg.as_string())
server.close()
print("Email sent successfully!")
except smtplib.SMTPAuthenticationError:
print("Authentication error: Please check your Gmail username and password.")
except smtplib.SMTPException as e:
print(f"SMTP error: {e}")
except Exception as e:
print(f"Error occurred: {e}")
# Define your mail_extract function
def mail_extract():
try:
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(gmail_user, gmail_password)
mail.select('inbox')
today = (datetime.today() - timedelta(days=1)).strftime('%d-%b-%Y')
result, data = mail.search(None, '(UNSEEN)', '(SINCE "' + today + '")')
emails_data = []
if result == 'OK':
mail_ids = data[0].split()
for mail_id in mail_ids:
result, message_data = mail.fetch(mail_id, '(RFC822)')
raw_email = message_data[0][1]
msg = email.message_from_bytes(raw_email)
email_subject = msg['subject']
email_from = msg['from']
# Extracting the email body
if msg.is_multipart():
for part in msg.walk():
content_type = part.get_content_type()
content_disposition = str(part.get("Content-Disposition"))
if "attachment" not in content_disposition:
body = part.get_payload(decode=True)
body = extract_body(body)
if body:
emails_data.append({'From': email_from, 'Subject': email_subject, 'Body': body})
else:
body = msg.get_payload(decode=True)
body = extract_body(body)
if body:
emails_data.append({'From': email_from, 'Subject': email_subject, 'Body': body})
else:
print("No unread emails found.")
mail.close()
mail.logout()
# Extract email bodies
#email_bodies = [email_data['Body'] for email_data in emails_data]
return email_bodies
except Exception as e:
print("Error during email extraction:", e)
return []
def preprocess_text(text):
text=text.lower()
tokens=word_tokenize(text)
stop_words=set(stopwords.words('english'))
tokens = [word for word in tokens if word not in stop_words]
lemmatizer = WordNetLemmatizer()
tokens = [lemmatizer.lemmatize(word) for word in tokens]
return ' '.join(tokens)
# Define route function
def route(email_bodies, tfidf_vectorizer, model):
try:
for body in email_bodies:
email_text = preprocess_text(body)
if email_text:
X_tfidf = tfidf_vectorizer.transform([email_text])
pred = model.predict(X_tfidf)[0]
print("Predicted Label:", pred)
if pred == 'technical':
to_email = '[email protected]'
print(pred,"Email sent to:", to_email)
elif pred == 'finance':
to_email = '[email protected]'
print(pred,"Email sent to:", to_email)
elif pred == 'energy':
to_email = '[email protected]'
print(pred,"Email sent to:", to_email)
elif pred == 'pharmaceutical':
to_email = '[email protected]'
print(pred,"Email sent to:", to_email)
elif pred == 'travel':
to_email = '[email protected]'
print(pred,"Email sent to:", to_email)
else:
print("Label not found:", pred)
else:
print("No email body available for processing.")
except Exception as e:
print("Error during routing emails:", e)
# Call mail_extract function to get email bodies
email_bodies = mail_extract()
# Call route function with email bodies, TF-IDF vectorizer, and model1
route(email_bodies, tfidf_vectorizer, model1)
# Assuming you have a trained TF-IDF vectorizer named tfidf_vectorizer
# Assuming you have a trained model named model1
# Call mail_extract function to get email bodies
email_bodies = mail_extract()
# Call route function with email bodies, TF-IDF vectorizer, and model1
route(email_bodies, tfidf_vectorizer, model1)