-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1828 lines (1543 loc) · 70.1 KB
/
app.py
File metadata and controls
1828 lines (1543 loc) · 70.1 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
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
PhishGuard - AI-Powered Adaptive Phishing Defense
Streamlit Dashboard for Gmail Email Analysis and Phishing Detection
"""
import streamlit as st
from datetime import datetime, timedelta
import re
import time
from typing import Dict, List, Optional
from gmail_client import GmailClient
from parser_heuristics import EmailParser, PhishingHeuristics
from gemini_engine import analyze_email, is_mock_mode, set_mock_mode
from policy import map_score_to_label, merge_heuristic_and_ai_scores
from crypto_simple import load_encrypted
from signing import verify_analysis, sign_analysis
from storage import insert_analysis, load_analyses, count_analyses, mark_signature_as_valid
# Page configuration
st.set_page_config(
page_title="PhishGuard - Email Security",
page_icon="🛡️",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS - Clean Dark Theme
st.markdown("""
<style>
/* Dark theme base */
.stApp {
background-color: #0e1117;
}
.main {
background-color: #0e1117;
}
.block-container {
padding: 2rem 3rem;
max-width: 100%;
}
/* Top bar / Header - Make it dark */
header[data-testid="stHeader"] {
background-color: #0e1117 !important;
}
/* Toolbar */
[data-testid="stToolbar"] {
background-color: #0e1117 !important;
}
/* Sidebar dark theme */
[data-testid="stSidebar"] {
background-color: #1a1d24;
border-right: 1px solid #2d3139;
}
[data-testid="stSidebar"] h2,
[data-testid="stSidebar"] h3,
[data-testid="stSidebar"] p,
[data-testid="stSidebar"] label,
[data-testid="stSidebar"] .stMarkdown {
color: #e8e8e8 !important;
}
/* Main content text */
h1, h2, h3, h4, h5, h6 {
color: #ffffff !important;
font-weight: 600 !important;
}
p, span, label, div {
color: #c9d1d9 !important;
}
/* Buttons - Sidebar only green */
[data-testid="stSidebar"] .stButton>button {
background-color: #238636;
color: #ffffff !important;
border: 1px solid #2ea043;
border-radius: 6px;
padding: 0.5rem 1rem;
font-weight: 600;
transition: all 0.2s;
}
[data-testid="stSidebar"] .stButton>button:hover {
background-color: #2ea043;
border-color: #3fb950;
}
/* Override ALL main area buttons to dark theme */
.main .stButton>button,
.main button,
button[kind="secondary"],
button[kind="primary"] {
background-color: #21262d !important;
color: #c9d1d9 !important;
border: 1px solid #30363d !important;
}
.main .stButton>button:hover,
.main button:hover {
background-color: #30363d !important;
}
/* Email list buttons - Force dark theme, no green */
div[data-testid="column"]:first-child button,
div[data-testid="column"]:first-child button[kind="secondary"],
div[data-testid="column"]:first-child button[kind="primary"],
div[data-testid="column"]:first-child div[data-testid="column"] button {
background: #21262d !important;
color: #e8e8e8 !important;
border: 1px solid #30363d !important;
border-radius: 8px !important;
padding: 1rem !important;
text-align: left !important;
margin-bottom: 0.6rem !important;
transition: all 0.2s ease !important;
width: 100% !important;
box-shadow: none !important;
border-left: 3px solid #30363d !important;
}
div[data-testid="column"]:first-child button:hover,
div[data-testid="column"]:first-child button[kind="secondary"]:hover,
div[data-testid="column"]:first-child div[data-testid="column"] button:hover {
background: #30363d !important;
border-left-color: #58a6ff !important;
transform: translateX(3px) !important;
box-shadow: 0 2px 8px rgba(88, 166, 255, 0.15) !important;
}
div[data-testid="column"]:first-child button[kind="primary"] {
background: #0d1117 !important;
border-color: #58a6ff !important;
border-left: 4px solid #58a6ff !important;
box-shadow: 0 2px 8px rgba(88, 166, 255, 0.2) !important;
}
div[data-testid="column"]:first-child button p,
div[data-testid="column"]:first-child div[data-testid="column"] button p {
color: #e8e8e8 !important;
margin: 0.25rem 0 !important;
font-size: 14px !important;
line-height: 1.4 !important;
}
div[data-testid="column"]:first-child button p strong {
font-weight: 600 !important;
font-size: 15px !important;
color: #ffffff !important;
}
/* Metrics */
[data-testid="stMetricValue"] {
color: #58a6ff !important;
font-size: 1.8rem !important;
font-weight: 700 !important;
}
[data-testid="stMetricLabel"] {
color: #8b949e !important;
}
/* Text input and text area */
textarea, input {
background-color: #0d1117 !important;
color: #c9d1d9 !important;
border: 1px solid #30363d !important;
border-radius: 6px !important;
}
/* Code blocks */
code {
background-color: #161b22 !important;
color: #79c0ff !important;
padding: 0.2rem 0.4rem !important;
border-radius: 4px !important;
border: 1px solid #30363d !important;
}
pre {
background-color: #161b22 !important;
border: 1px solid #30363d !important;
border-radius: 6px !important;
}
/* Info/warning boxes */
.stAlert {
background-color: #21262d !important;
color: #c9d1d9 !important;
border: 1px solid #30363d !important;
border-radius: 6px !important;
}
/* Divider */
hr {
border-color: #21262d !important;
margin: 1rem 0 !important;
}
/* Toggle switch */
.stCheckbox label {
color: #c9d1d9 !important;
}
/* Slider */
.stSlider label {
color: #c9d1d9 !important;
}
/* Severity badges */
.badge {
display: inline-block;
padding: 0.25rem 0.75rem;
border-radius: 12px;
font-size: 12px;
font-weight: 600;
margin-right: 0.5rem;
}
.badge-safe {
background-color: #1a7f37;
color: #ffffff;
}
.badge-review {
background-color: #9e6a03;
color: #ffffff;
}
.badge-high {
background-color: #da3633;
color: #ffffff;
}
/* Stats card */
.stats-card {
background-color: #161b22;
border: 1px solid #30363d;
border-radius: 8px;
padding: 1rem;
margin: 0.5rem 0;
}
/* Indicator card */
.indicator-card {
background-color: #21262d;
border-left: 3px solid #58a6ff;
padding: 0.75rem;
margin: 0.5rem 0;
border-radius: 4px;
color: #c9d1d9 !important;
}
/* Email detail card */
.detail-card {
background-color: #161b22;
border: 1px solid #30363d;
border-radius: 8px;
padding: 1.5rem;
margin: 1rem 0;
}
/* Header card */
.header-card {
background-color: #161b22;
border: 1px solid #30363d;
border-radius: 8px;
padding: 1rem 1.5rem;
margin-bottom: 1.5rem;
}
</style>
""", unsafe_allow_html=True)
# Initialize session state for caching
if 'emails' not in st.session_state:
st.session_state.emails = []
if 'selected_email_id' not in st.session_state:
st.session_state.selected_email_id = None
if 'gmail_client' not in st.session_state:
st.session_state.gmail_client = None
if 'scanning_complete' not in st.session_state:
st.session_state.scanning_complete = False
if 'auto_refresh_enabled' not in st.session_state:
st.session_state.auto_refresh_enabled = False
if 'last_refresh_time' not in st.session_state:
st.session_state.last_refresh_time = None
if 'refresh_interval' not in st.session_state:
st.session_state.refresh_interval = 30
if 'last_fetch_count' not in st.session_state:
st.session_state.last_fetch_count = 30
if 'secrets' not in st.session_state:
st.session_state.secrets = None
if 'secrets_loaded' not in st.session_state:
st.session_state.secrets_loaded = False
if 'app_start_time' not in st.session_state:
st.session_state.app_start_time = datetime.now()
if 'mongo_enabled' not in st.session_state:
st.session_state.mongo_enabled = False
def initialize_gmail_client():
"""
Initialize Gmail API client
Handles authentication and creates client instance
"""
try:
if st.session_state.gmail_client is None:
with st.spinner('🔐 Authenticating with Gmail API...'):
st.session_state.gmail_client = GmailClient()
return True
except Exception as e:
st.error(f"❌ Authentication failed: {str(e)}")
st.info("📝 Make sure Gmail_Credentials.json is in the project root and complete the OAuth flow.")
return False
def fetch_and_scan_emails(max_results=30, is_auto_refresh=False):
"""
Fetch emails from Gmail and scan for phishing indicators
Accumulates new emails instead of replacing existing ones
Args:
max_results: Number of recent emails to fetch
is_auto_refresh: If True, only adds new emails not already in the list
"""
if not st.session_state.gmail_client:
st.error("Gmail client not initialized")
return
with st.spinner(f'📧 Fetching {max_results} recent emails...'):
# Fetch email list
email_list = st.session_state.gmail_client.list_recent(max_results=max_results)
if not email_list:
st.warning("No emails found in inbox")
return
# Get existing email IDs to avoid duplicates
existing_ids = {email['id'] for email in st.session_state.emails}
# Filter out emails we already have
new_emails = [email for email in email_list if email['id'] not in existing_ids]
if not new_emails:
if is_auto_refresh:
status_text = st.empty()
status_text.info("✓ No new emails")
time.sleep(1)
status_text.empty()
else:
st.info("All fetched emails are already in the list")
return
# Show AI mode
mode_status = "🤖 Mock AI" if is_mock_mode() else "🤖 Live AI (Gemini)"
st.info(f"Found {len(new_emails)} new emails. Analyzing with {mode_status}...")
# Progress bar for scanning
progress_bar = st.progress(0)
status_text = st.empty()
scanned_emails = []
for idx, email_meta in enumerate(new_emails):
# Update progress
progress = (idx + 1) / len(new_emails)
progress_bar.progress(progress)
status_text.text(f"Scanning email {idx + 1}/{len(new_emails)}: {email_meta['subject'][:50]}...")
# Fetch full raw email
raw_bytes = st.session_state.gmail_client.get_raw(email_meta['id'])
if raw_bytes:
# Parse email
parsed = EmailParser.parse_raw(raw_bytes)
# Run heuristic analysis
heuristics = PhishingHeuristics.extract_indicators(parsed)
# Run AI analysis with error handling
try:
ai_result = analyze_email(parsed, heuristics['indicators'])
# Check if API failed and fell back to mock
if ai_result.get('error') or ai_result.get('fallback'):
if not is_mock_mode(): # Only show error if we expected live mode
st.warning(f"⚠️ Gemini API error: {ai_result.get('error', 'Unknown error')}. Using mock mode.")
except Exception as e:
st.error(f"❌ AI Analysis failed: {str(e)}")
# Create fallback result
ai_result = {
'risk_score': heuristics['risk_score'] * 10,
'intents': ['unknown'],
'indicators': [],
'safe_summary': 'AI analysis unavailable',
'recommendations': ['Manual review required'],
'processed_at': datetime.now().isoformat(),
'mock_mode': True,
'error': str(e)
}
# Merge scores: heuristic (0-10) to (0-100) + AI (0-100)
heuristic_score_normalized = heuristics['risk_score'] * 10
final_score = merge_heuristic_and_ai_scores(
heuristic_score=heuristic_score_normalized,
ai_score=ai_result['risk_score'],
ai_weight=0.7 # 70% AI, 30% heuristics
)
# Map to policy category
policy = map_score_to_label(final_score)
# Combine metadata with analysis
email_data = {
**email_meta,
'parsed': parsed,
'heuristics': heuristics,
'ai_analysis': ai_result,
'policy': policy,
'final_risk_score': final_score
}
scanned_emails.append(email_data)
# Save to MongoDB (M4) - non-blocking
save_analysis_to_mongo(email_data)
# Clear progress indicators
progress_bar.empty()
status_text.empty()
# ACCUMULATE emails: prepend new emails to existing list (newest first)
st.session_state.emails = scanned_emails + st.session_state.emails
st.session_state.scanning_complete = True
# Show summary
ai_high_risk = sum(1 for e in scanned_emails if e['policy']['category'] == 'HIGH_RISK')
if is_auto_refresh:
st.success(f"✅ Auto-refresh: Added {len(scanned_emails)} new email(s). {ai_high_risk} high-risk. Total: {len(st.session_state.emails)}")
else:
st.success(f"✅ Analysis complete. Analyzed {len(scanned_emails)} new emails. {ai_high_risk} high-risk. Total: {len(st.session_state.emails)}")
def format_date(date_str):
"""
Format email date for display
Args:
date_str: Raw date string from email
Returns:
Formatted date string
"""
try:
# Try to parse and format date
if date_str:
# Simple display of first part before timezone info
return date_str.split('(')[0].strip()
return "Unknown Date"
except:
return date_str[:50] if date_str else "Unknown Date"
def generate_analysis_json(email_data):
"""
Generate standardized analysis JSON for M3 handoff
Args:
email_data: Complete email data dict with AI analysis
Returns:
dict: Standardized analysis JSON
"""
ai_analysis = email_data.get('ai_analysis', {})
heuristics = email_data.get('heuristics', {})
policy = email_data.get('policy', {})
return {
"email_id": email_data.get('id'),
"metadata": {
"subject": email_data.get('subject'),
"from": email_data.get('sender'),
"date": email_data.get('date'),
"has_attachments": len(email_data.get('parsed', {}).get('attachments', [])) > 0,
"attachment_count": len(email_data.get('parsed', {}).get('attachments', []))
},
"analysis": {
"final_risk_score": email_data.get('final_risk_score', 0),
"ai_risk_score": ai_analysis.get('risk_score', 0),
"heuristic_risk_score": heuristics.get('risk_score', 0) * 10,
"category": policy.get('category', 'UNKNOWN'),
"gmail_label": policy.get('label', ''),
"severity_level": policy.get('severity_level', 2)
},
"ai_insights": {
"intents": ai_analysis.get('intents', []),
"indicators": ai_analysis.get('indicators', []),
"safe_summary": ai_analysis.get('safe_summary', ''),
"recommendations": ai_analysis.get('recommendations', []),
"processed_at": ai_analysis.get('processed_at', '')
},
"heuristic_findings": {
"indicators": heuristics.get('indicators', []),
"urgency_found": heuristics.get('urgency_found', False),
"credential_found": heuristics.get('credential_found', False),
"severity": heuristics.get('severity', 'unknown')
},
"parsed_content": {
"links_count": len(email_data.get('parsed', {}).get('all_links', [])),
"has_html": email_data.get('parsed', {}).get('body_html') is not None,
"body_length": len(email_data.get('parsed', {}).get('body_text', ''))
},
"timestamp": ai_analysis.get('processed_at', datetime.now().isoformat())
}
def save_analysis_to_mongo(email_data):
"""
Save signed analysis to MongoDB (M4 integration)
Args:
email_data: Complete email data dict with AI analysis
Returns:
bool: True if saved successfully, False otherwise
"""
# Check if secrets are loaded
if not st.session_state.secrets_loaded or not st.session_state.secrets:
return False
try:
# Get MongoDB URI and signing secret from decrypted secrets
mongo_uri = st.session_state.secrets.get('MONGO_URI')
signing_secret = st.session_state.secrets.get('SIGNING_SECRET')
if not mongo_uri or not signing_secret:
return False
# Convert signing secret to bytes if needed
if isinstance(signing_secret, str):
signing_secret = signing_secret.encode('utf-8')
# Prepare analysis document
current_time = datetime.now()
analysis_doc = {
'gmail_id': email_data.get('id'),
'sender': email_data.get('sender'),
'subject': email_data.get('subject'),
'date': email_data.get('date'),
'risk_score': email_data.get('final_risk_score', 0),
'risk_label': email_data.get('policy', {}).get('category', 'UNKNOWN'),
'ai_risk_score': email_data.get('ai_analysis', {}).get('risk_score', 0),
'heuristic_risk_score': email_data.get('heuristics', {}).get('risk_score', 0) * 10,
'intents': email_data.get('ai_analysis', {}).get('intents', []),
'indicators': email_data.get('heuristics', {}).get('indicators', []),
'ai_summary': email_data.get('ai_analysis', {}).get('safe_summary', ''),
'recommendations': email_data.get('ai_analysis', {}).get('recommendations', []),
'processed_at': current_time.isoformat(), # Convert to ISO string for JSON serialization
'mock_mode': email_data.get('ai_analysis', {}).get('mock_mode', False)
}
# Sign the analysis
from signing import sign
signature = sign(analysis_doc, signing_secret)
analysis_doc['signature'] = signature
# Convert processed_at back to datetime for MongoDB
analysis_doc['processed_at'] = current_time
# Insert into MongoDB
success = insert_analysis(
analysis_doc,
st.session_state.app_start_time,
mongo_uri,
signing_secret
)
if success:
print(f"✅ Saved to MongoDB: {email_data.get('subject')[:50]}")
else:
print(f"⚠️ MongoDB save failed for: {email_data.get('subject')[:50]}")
return success
except Exception as e:
# Log error but don't disrupt main flow
print(f"❌ MongoDB save error: {str(e)}")
import traceback
traceback.print_exc()
return False
def extract_sender_name(from_field):
"""
Extract clean sender name from From field
Args:
from_field: Raw From header (e.g., "John Doe <john@example.com>")
Returns:
Clean sender name or email
"""
match = re.match(r'^([^<]+)<(.+)>$', from_field)
if match:
name = match.group(1).strip().strip('"')
return name if name else match.group(2)
return from_field
def get_label_for_display(category: str) -> Dict:
"""
Get display properties for a category
Args:
category: "SAFE", "REVIEW", or "HIGH_RISK"
Returns:
Dictionary with display properties
"""
display_map = {
"SAFE": {
"text": "Safe",
"badge_class": "badge-safe",
"emoji": "✅",
"color": "#1a7f37"
},
"REVIEW": {
"text": "Review",
"badge_class": "badge-review",
"emoji": "⚠️",
"color": "#9e6a03"
},
"HIGH_RISK": {
"text": "High Risk",
"badge_class": "badge-high",
"emoji": "🚫",
"color": "#da3633"
}
}
return display_map.get(category, display_map["REVIEW"])
def generate_analysis_json(email_data: Dict) -> Dict:
"""
Generate analysis JSON for M3 handoff
Args:
email_data: Complete email data with AI analysis
Returns:
Structured JSON for downstream processing
"""
import json
from datetime import datetime
ai_analysis = email_data.get('ai_analysis', {})
policy = email_data.get('policy', {})
heuristics = email_data.get('heuristics', {})
analysis_json = {
"email_id": email_data.get('id'),
"subject": email_data.get('subject'),
"sender": email_data.get('sender'),
"date": email_data.get('date'),
"processed_at": ai_analysis.get('processed_at', datetime.utcnow().isoformat()),
"risk_assessment": {
"final_score": email_data.get('final_risk_score', 0),
"ai_score": ai_analysis.get('risk_score', 0),
"heuristic_score": heuristics.get('risk_score', 0) * 10,
"category": policy.get('category', 'UNKNOWN'),
"severity_level": policy.get('severity_level', 2)
},
"policy": {
"category": policy.get('category', 'UNKNOWN'),
"gmail_label": policy.get('label', ''),
"action": policy.get('action', 'user_review'),
"description": policy.get('description', '')
},
"ai_analysis": {
"intents": ai_analysis.get('intents', []),
"indicators": ai_analysis.get('indicators', []),
"safe_summary": ai_analysis.get('safe_summary', ''),
"recommendations": ai_analysis.get('recommendations', []),
"mock_mode": ai_analysis.get('mock_mode', True)
},
"heuristic_analysis": {
"risk_score": heuristics.get('risk_score', 0),
"severity": heuristics.get('severity', 'unknown'),
"urgency_found": heuristics.get('urgency_found', False),
"credential_found": heuristics.get('credential_found', False),
"indicators": heuristics.get('indicators', [])
},
"email_metadata": {
"has_attachments": len(email_data.get('parsed', {}).get('attachments', [])) > 0,
"attachment_count": len(email_data.get('parsed', {}).get('attachments', [])),
"link_count": len(email_data.get('parsed', {}).get('all_links', [])),
"body_length": len(email_data.get('parsed', {}).get('body_text', ''))
}
}
return analysis_json
def get_severity_emoji(severity):
"""
Get emoji for severity level
Args:
severity: 'safe', 'review', or 'high_risk' (legacy) OR policy dict
Returns:
Emoji string
"""
# Handle new policy-based system
if isinstance(severity, dict):
return severity.get('severity_emoji', '⚠️')
# Handle legacy string-based severity
if severity == 'safe' or severity == 'SAFE':
return "✅"
elif severity == 'review' or severity == 'REVIEW':
return "⚠️"
else:
return "🚫"
def render_email_list():
"""
Render the left panel email list (inbox view)
"""
st.markdown("### 📬 Inbox")
if not st.session_state.emails:
st.info("Click 'Fetch & Scan Emails' to load your inbox")
return
# Statistics - use policy categories
total = len(st.session_state.emails)
safe = sum(1 for e in st.session_state.emails if e.get('policy', {}).get('category') == 'SAFE')
review = sum(1 for e in st.session_state.emails if e.get('policy', {}).get('category') == 'REVIEW')
high_risk = sum(1 for e in st.session_state.emails if e.get('policy', {}).get('category') == 'HIGH_RISK')
st.markdown(f"""
<div class="stats-card">
<strong style="color: #c9d1d9;">Total: {total}</strong> •
<span style="color: #3fb950;">Safe: {safe}</span> •
<span style="color: #d29922;">Review: {review}</span> •
<span style="color: #f85149;">Risk: {high_risk}</span>
</div>
""", unsafe_allow_html=True)
# Last refresh time
if st.session_state.last_refresh_time:
time_ago = datetime.now() - st.session_state.last_refresh_time
minutes_ago = int(time_ago.total_seconds() / 60)
if minutes_ago < 1:
st.caption("🔄 Updated just now")
else:
st.caption(f"🔄 Updated {minutes_ago}m ago")
st.markdown("---")
# Email list
for idx, email in enumerate(st.session_state.emails):
# Use policy if available, fallback to heuristics
policy = email.get('policy', {})
if policy:
emoji = policy.get('severity_emoji', '⚠️')
else:
severity = email.get('heuristics', {}).get('severity', 'review')
emoji = get_severity_emoji(severity)
sender = extract_sender_name(email['sender'])
subject = email['subject'][:55] + ('...' if len(email['subject']) > 55 else '')
is_selected = st.session_state.selected_email_id == email['id']
# Create clickable email card using columns to avoid green button
col1, col2 = st.columns([0.05, 0.95])
with col1:
st.markdown(f"<div style='font-size: 20px; padding-top: 0.5rem;'>{emoji}</div>", unsafe_allow_html=True)
with col2:
if st.button(
f"**{sender}**\n{subject}",
key=f"email_{email['id']}",
use_container_width=True,
type="primary" if is_selected else "secondary"
):
st.session_state.selected_email_id = email['id']
st.rerun()
def render_email_detail():
"""
Render the right panel email detail view
"""
if not st.session_state.selected_email_id:
st.info("← Select an email from the inbox to view details")
return
# Find selected email
selected = None
for email in st.session_state.emails:
if email['id'] == st.session_state.selected_email_id:
selected = email
break
if not selected:
st.warning("Email not found")
return
# Get policy and AI data
policy = selected.get('policy', {})
ai_analysis = selected.get('ai_analysis', {})
final_score = selected.get('final_risk_score', 0)
# Severity badge - use policy if available
if policy:
severity = policy.get('category', 'REVIEW')
emoji = policy.get('severity_emoji', '⚠️')
severity_label = severity.replace('_', ' ').title()
else:
severity = selected['heuristics']['severity']
emoji = get_severity_emoji(severity)
severity_label = severity.replace('_', ' ').title()
if severity == 'SAFE' or severity == 'safe':
badge_class = 'badge-safe'
elif severity == 'REVIEW' or severity == 'review':
badge_class = 'badge-review'
else:
badge_class = 'badge-high'
# Email header card
st.markdown(f"""
<div class="header-card">
<h2 style="margin: 0; color: #ffffff;">{selected['subject']}</h2>
<div style="margin-top: 1rem;">
<span class="badge {badge_class}">{emoji} {severity_label}</span>
</div>
</div>
""", unsafe_allow_html=True)
# Email metadata
col1, col2 = st.columns(2)
with col1:
st.markdown("**From**")
st.code(selected['sender'], language=None)
with col2:
st.markdown("**Date**")
st.code(format_date(selected['date']), language=None)
# Attachments
if selected['parsed']['attachments']:
st.markdown("**Attachments**")
st.code(', '.join(selected['parsed']['attachments']), language=None)
st.markdown("---")
# AI Analysis Section with Run Button
# Show appropriate title based on mode
if ai_analysis and ai_analysis.get('mock_mode'):
st.markdown("### 🔍 Pattern-Based Analysis")
st.caption("⚠️ Using rule-based detection (Mock Mode). Switch to Live mode in sidebar for real AI analysis.")
else:
st.markdown("### 🤖 AI Semantic Analysis")
if ai_analysis:
st.caption("✅ Analyzed with Google Gemini AI")
# Button row
col_btn1, col_btn2, col_btn3 = st.columns([1, 1, 2])
# Run AI Analysis button (if not analyzed yet)
if not ai_analysis:
with col_btn1:
if st.button("🔍 Run AI Analysis", key="run_ai_analysis", use_container_width=True):
with st.spinner("🤖 Analyzing email with AI..."):
try:
# Run AI analysis
ai_result = analyze_email(selected['parsed'], selected['heuristics']['indicators'])
# Check for API errors
if ai_result.get('error'):
st.error(f"❌ Gemini API Error: {ai_result['error']}")
if ai_result.get('fallback'):
st.info("ℹ️ Continuing with mock analysis results.")
elif not is_mock_mode() and ai_result.get('mock_mode'):
st.warning("⚠️ API call failed. Falling back to mock mode.")
# Merge scores
heuristic_score_normalized = selected['heuristics']['risk_score'] * 10
new_final_score = merge_heuristic_and_ai_scores(
heuristic_score=heuristic_score_normalized,
ai_score=ai_result['risk_score'],
ai_weight=0.7
)
# Map to policy
new_policy = map_score_to_label(new_final_score)
# Update email data
selected['ai_analysis'] = ai_result
selected['policy'] = new_policy
selected['final_risk_score'] = new_final_score
if not ai_result.get('error'):
st.success("✅ AI analysis complete!")
st.rerun()
except Exception as e:
st.error(f"❌ Analysis failed: {str(e)}")
st.info("💡 Try switching to Mock mode in the sidebar or check your API key.")
st.info("Click the button above to run AI semantic analysis on this email.")
else:
# Re-analyze button (if already analyzed)
with col_btn1:
if st.button("🔄 Re-analyze", key="reanalyze_ai", use_container_width=True):
with st.spinner("🤖 Re-analyzing email with AI..."):
try:
# Re-run AI analysis
ai_result = analyze_email(selected['parsed'], selected['heuristics']['indicators'])
# Check for API errors
if ai_result.get('error'):
st.error(f"❌ Gemini API Error: {ai_result['error']}")
if ai_result.get('fallback'):
st.info("ℹ️ Continuing with mock analysis results.")
elif not is_mock_mode() and ai_result.get('mock_mode'):
st.warning("⚠️ API call failed. Falling back to mock mode.")
# Merge scores
heuristic_score_normalized = selected['heuristics']['risk_score'] * 10
new_final_score = merge_heuristic_and_ai_scores(
heuristic_score=heuristic_score_normalized,
ai_score=ai_result['risk_score'],
ai_weight=0.7
)
# Map to policy
new_policy = map_score_to_label(new_final_score)
# Update in session state
for email in st.session_state.emails:
if email['id'] == selected['id']:
email['ai_analysis'] = ai_result
email['policy'] = new_policy
email['final_risk_score'] = new_final_score
break
if not ai_result.get('error'):
st.success("✅ AI analysis updated!")
st.rerun()
except Exception as e:
st.error(f"❌ Re-analysis failed: {str(e)}")
st.info("💡 Try switching to Mock mode in the sidebar or check your API key.")
if ai_analysis:
# Risk Score Gauge
risk_score_val = ai_analysis.get('risk_score', 0)
# Color based on risk level
if risk_score_val < 30:
gauge_color = "#1a7f37"
risk_label = "LOW RISK"
elif risk_score_val < 70:
gauge_color = "#9e6a03"
risk_label = "MEDIUM RISK"
else:
gauge_color = "#da3633"
risk_label = "HIGH RISK"
# Risk gauge visualization
st.markdown(f"""
<div style="background-color: #161b22; border: 1px solid #30363d; border-radius: 8px; padding: 1.5rem; margin-bottom: 1rem;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;">
<span style="color: #c9d1d9; font-size: 14px; font-weight: 600;">AI Risk Assessment</span>
<span style="color: {gauge_color}; font-size: 18px; font-weight: 700;">{risk_score_val:.1f}/100</span>
</div>
<div style="background-color: #0d1117; border-radius: 4px; height: 12px; overflow: hidden;">
<div style="background-color: {gauge_color}; height: 100%; width: {risk_score_val}%; transition: width 0.3s;"></div>
</div>
<div style="text-align: center; margin-top: 0.5rem;">
<span style="color: {gauge_color}; font-size: 12px; font-weight: 600;">{risk_label}</span>
</div>
</div>
""", unsafe_allow_html=True)
# Score breakdown
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Final Score", f"{final_score:.1f}/100")
with col2:
st.metric("AI Score", f"{ai_analysis.get('risk_score', 0):.1f}/100")
with col3: