-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemail_processor.py
More file actions
156 lines (126 loc) · 4.73 KB
/
email_processor.py
File metadata and controls
156 lines (126 loc) · 4.73 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
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
from flask import Flask, request, jsonify
import os
import json
from datetime import datetime
from spam_detec import EmailSpamDetector
app = Flask(__name__)
# Initialize spam detector
detector = EmailSpamDetector()
model_path = './trained_spam_model' if os.path.exists('./trained_spam_model') else None
detector.load_model(model_path)
# Store results for review
RESULTS_FILE = 'spam_results.json'
def load_results():
"""Load previous results."""
if os.path.exists(RESULTS_FILE):
with open(RESULTS_FILE, 'r') as f:
return json.load(f)
return []
def save_result(result):
"""Save spam detection result."""
results = load_results()
results.append({
'timestamp': datetime.now().isoformat(),
'result': result
})
# Keep only last 100 results
results = results[-100:]
with open(RESULTS_FILE, 'w') as f:
json.dump(results, f, indent=2)
@app.route('/check-email', methods=['POST'])
def check_email():
"""Endpoint to check a single email."""
data = request.json
if not data or 'email_content' not in data:
return jsonify({"error": "Missing email_content"}), 400
email_content = data['email_content']
sender = data.get('sender', 'Unknown')
subject = data.get('subject', 'No Subject')
# Combine subject and content for analysis
full_content = f"Subject: {subject}\nFrom: {sender}\n\n{email_content}"
# Get prediction
result = detector.predict([full_content])[0]
# Add metadata
result['sender'] = sender
result['subject'] = subject
result['timestamp'] = datetime.now().isoformat()
# Save result
save_result(result)
return jsonify(result)
@app.route('/results', methods=['GET'])
def get_results():
"""Get recent spam detection results."""
results = load_results()
# Summary statistics
total = len(results)
spam_count = sum(1 for r in results if r['result']['is_spam'])
return jsonify({
'total_checked': total,
'spam_detected': spam_count,
'recent_results': results[-20:] # Last 20 results
})
@app.route('/dashboard', methods=['GET'])
def dashboard():
"""Simple web dashboard to view results."""
results = load_results()
html = """
<!DOCTYPE html>
<html>
<head>
<title>Email Spam Detection Dashboard</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.spam { background-color: #ffebee; border-left: 4px solid #f44336; padding: 10px; margin: 10px 0; }
.legitimate { background-color: #e8f5e8; border-left: 4px solid #4caf50; padding: 10px; margin: 10px 0; }
.stats { background-color: #f5f5f5; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
</style>
</head>
<body>
<h1>Email Spam Detection Dashboard</h1>
"""
if results:
total = len(results)
spam_count = sum(1 for r in results if r['result']['is_spam'])
html += f"""
<div class="stats">
<h3>Statistics</h3>
<p>Total emails checked: {total}</p>
<p>Spam detected: {spam_count}</p>
<p>Legitimate emails: {total - spam_count}</p>
<p>Spam rate: {(spam_count/total*100):.1f}%</p>
</div>
<h3>Recent Results</h3>
"""
for entry in results[-20:]: # Show last 20
result = entry['result']
timestamp = entry['timestamp']
css_class = 'spam' if result['is_spam'] else 'legitimate'
status = 'SPAM' if result['is_spam'] else 'LEGITIMATE'
html += f"""
<div class="{css_class}">
<strong>{status}</strong> - {timestamp}<br>
<strong>From:</strong> {result.get('sender', 'Unknown')}<br>
<strong>Subject:</strong> {result.get('subject', 'No Subject')}<br>
<strong>Confidence:</strong> {result['spam_probability']:.2%}<br>
<em>Preview:</em> {result['text'][:150]}...
</div>
"""
else:
html += "<p>No emails checked yet.</p>"
html += """
<script>
// Auto-refresh every 30 seconds
setTimeout(function(){ location.reload(); }, 30000);
</script>
</body>
</html>
"""
return html
if __name__ == '__main__':
print("Email Processor API started!")
print("Endpoints:")
print("- POST /check-email: Check a single email")
print("- GET /results: Get detection results as JSON")
print("- GET /dashboard: View web dashboard")
print("\nDashboard available at: http://localhost:5001/dashboard")
app.run(host='0.0.0.0', port=5001, debug=False)