File size: 17,558 Bytes
b0d5689
52aff78
 
 
 
 
 
 
 
 
 
 
 
 
 
b0d5689
52aff78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0d5689
 
52aff78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0d5689
52aff78
 
 
b0d5689
52aff78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0d5689
 
 
 
 
 
 
 
 
52aff78
 
 
b0d5689
43ab35b
 
fd0b808
 
 
 
 
 
 
 
43ab35b
fd0b808
 
 
 
a3479b8
fd0b808
 
 
 
 
 
 
 
 
 
 
 
 
43ab35b
 
 
 
 
 
fd0b808
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43ab35b
fd0b808
 
43ab35b
 
a3479b8
 
b0d5689
 
 
 
 
 
fd0b808
 
 
 
 
 
 
 
 
b0d5689
 
 
 
 
 
 
4001b90
b0d5689
fd0b808
 
 
b0d5689
 
fd0b808
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43ab35b
 
 
fd0b808
 
43ab35b
fd0b808
 
43ab35b
 
fd0b808
 
 
 
 
 
 
43ab35b
 
fd0b808
 
 
 
 
 
 
 
 
43ab35b
d5d7753
43ab35b
 
 
 
d5d7753
43ab35b
d5d7753
fd0b808
43ab35b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd0b808
43ab35b
fd0b808
 
 
 
 
 
 
 
 
 
 
 
 
43ab35b
a3479b8
43ab35b
fd0b808
 
a3479b8
b0d5689
 
 
 
fd0b808
 
 
 
 
 
 
 
 
43ab35b
 
 
fd0b808
 
 
43ab35b
 
fd0b808
 
43ab35b
 
 
 
 
 
 
 
 
fd0b808
 
 
 
 
 
 
 
43ab35b
 
 
 
 
 
 
 
fd0b808
 
 
 
b0d5689
 
 
 
 
 
a3479b8
b0d5689
 
a3479b8
fd0b808
52aff78
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


# import os
# import re
# import fitz  # PyMuPDF
# import tempfile
# import base64
# from datetime import datetime
# from gtts import gTTS
# import streamlit as st
# from transformers import pipeline
# from groq import Groq

# # βœ… Hugging Face and GROQ secrets loaded via Hugging Face Spaces Secrets interface

# # βšͺ Access secrets securely from environment variables
# GROQ_API_KEY = os.getenv("GROQ_API_KEY")
# HF_TOKEN = os.getenv("HF_TOKEN")
# KAGGLE_USERNAME = os.getenv("KAGGLE_USERNAME")
# KAGGLE_KEY = os.getenv("KAGGLE_KEY")

# # βœ… Validate secrets
# if not all([GROQ_API_KEY, HF_TOKEN, KAGGLE_USERNAME, KAGGLE_KEY]):
#     st.error("❌ One or more required API keys are missing from the environment.")
#     st.stop()

# # βœ… Initialize Groq client
# client = Groq(api_key=GROQ_API_KEY)

# # βœ… Load phishing detection pipeline from Hugging Face
# phishing_pipe = pipeline(
#     "text-classification",
#     model="ealvaradob/bert-finetuned-phishing",
#     token=HF_TOKEN
# )

# # βœ… Language and role options
# language_choices = ["English", "Urdu", "French"]
# role_choices = ["Admin", "Procurement", "Logistics"]

# # βœ… Glossary terms
# GLOSSARY = {
#     "phishing": "Phishing is a scam where attackers trick you into revealing personal information.",
#     "malware": "Malicious software designed to harm or exploit systems.",
#     "spam": "Unwanted or unsolicited messages.",
#     "tone": "The emotional character of the message."
# }

# # βœ… Translations (demo dictionary-based)
# TRANSLATIONS = {
#     "Phishing": {"Urdu": "فشنگ", "French": "HameΓ§onnage"},
#     "Spam": {"Urdu": "Ψ³ΩΎΫŒΩ…", "French": "Courrier indΓ©sirable"},
#     "Malware": {"Urdu": "Ω…ΫŒΩ„ΩˆΫŒΨ¦Ψ±", "French": "Logiciel malveillant"},
#     "Safe": {"Urdu": "Ω…Ψ­ΩΩˆΨΈ", "French": "SΓ»r"}
# }

# # βœ… In-memory history and audio
# if "history" not in st.session_state:
#     st.session_state.history = []
# if "audio_summary" not in st.session_state:
#     st.session_state.audio_summary = ""
# if "report_sent" not in st.session_state:
#     st.session_state.report_sent = False

# # =======================
# # Streamlit UI
# # =======================
# st.set_page_config(page_title="ZeroPhish Gate", layout="wide")

# st.title("πŸ›‘οΈ ZeroPhish Gate")
# st.markdown("AI-powered phishing message detection and explanation.")

# # Input fields
# col1, col2 = st.columns([3, 1])
# with col1:
#     text_input = st.text_area("βœ‰οΈ Paste Suspicious Message", height=200)
#     uploaded_file = st.file_uploader("πŸ“„ Upload PDF/TXT (optional)", type=["pdf", "txt"])

# with col2:
#     language = st.selectbox("🌐 Preferred Language", language_choices)
#     role = st.selectbox("πŸ§‘β€πŸ’Ό Your Role", role_choices)

# analyze_btn = st.button("πŸ” Analyze with AI")
# clear_btn = st.button("πŸ—‘οΈ Clear History")

# # =======================
# # Function Definitions
# # =======================
# def extract_text_from_file(file):
#     if file is None:
#         return ""
#     ext = file.name.split(".")[-1].lower()
#     if ext == "pdf":
#         doc = fitz.open(stream=file.read(), filetype="pdf")
#         return "\n".join(page.get_text() for page in doc)
#     elif ext == "txt":
#         return file.read().decode("utf-8")
#     return ""

# def analyze_with_huggingface(text):
#     try:
#         result = phishing_pipe(text)
#         label = result[0]['label']
#         confidence = round(result[0]['score'] * 100, 2)
#         threat_type = {
#             "PHISHING": "Phishing",
#             "SPAM": "Spam",
#             "MALWARE": "Malware",
#             "LEGITIMATE": "Safe"
#         }.get(label.upper(), "Unknown")
#         return label, confidence, threat_type
#     except Exception as e:
#         return "Error", 0, f"Error: {e}"

# def semantic_analysis(text):
#     response = client.chat.completions.create(
#         model="llama3-8b-8192",
#         messages=[
#             {"role": "system", "content": "You are a cybersecurity assistant."},
#             {"role": "user", "content": f"Explain this suspicious message for a {role} in {language} without ending in questions:\n{text}"}
#         ]
#     )
#     raw = response.choices[0].message.content
#     clean = re.sub(r"Is there anything else you'd like.*", "", raw, flags=re.I).strip()
#     return clean

# def translate_label(threat_type):
#     return TRANSLATIONS.get(threat_type, {}).get(language, threat_type)

# def text_to_speech(text):
#     try:
#         tts = gTTS(text=text, lang='en')
#         with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as fp:
#             tts.save(fp.name)
#             return fp.name
#     except Exception as e:
#         st.error(f"❌ Audio generation error: {e}")
#         return None

# def create_report(label, score, threat_type, explanation, text):
#     ts = datetime.now().strftime("%Y%m%d_%H%M%S")
#     filename = f"Zerophish_Report_{ts}.txt"
#     report = f"""
# πŸ” AI Threat Detection Report

# Input Message:
# {text}

# Prediction: {label}
# Threat Type: {threat_type}
# Confidence: {score}%

# ---

# 🧠 Explanation:
# {explanation}
# """
#     with open(filename, "w") as f:
#         f.write(report)
#     return filename

# def render_history():
#     with st.expander("πŸ•“ View Analysis History", expanded=True):
#         for i, record in enumerate(reversed(st.session_state.history)):
#             with st.container():
#                 st.markdown(f"**πŸ”’ Entry #{len(st.session_state.history) - i}**")
#                 st.markdown(f"**πŸ“ Input:** {record['input'][:100]}...")
#                 st.markdown(f"**πŸ” Type:** {record['threat']} | **πŸ“Š Confidence:** {record['score']}%")
#                 st.markdown(f"**πŸ“– Summary:** {record['summary'][:200]}...")
#                 st.markdown("---")

# # =======================
# # Run Analysis
# # =======================
# if clear_btn:
#     st.session_state.history.clear()
#     st.session_state.audio_summary = ""
#     st.session_state.report_sent = False
#     st.success("βœ… History cleared!")

# if analyze_btn:
#     st.session_state.report_sent = False
#     combined_text = text_input
#     if uploaded_file:
#         extracted = extract_text_from_file(uploaded_file)
#         combined_text += "\n" + extracted

#     if not combined_text.strip():
#         st.warning("⚠️ Please enter some text or upload a file to analyze.")
#     else:
#         label, score, threat_type = analyze_with_huggingface(combined_text)
#         translated_threat = translate_label(threat_type)

#         st.subheader("πŸ” AI Threat Detection Result")
#         st.markdown(f"**Prediction:** {label}")
#         st.markdown(f"**Threat Type:** {threat_type} ({translated_threat})")
#         st.markdown(f"**Confidence:** {score}%")

#         summary = ""
#         if threat_type.lower() != "safe":
#             with st.expander("🧠 Semantic Reanalysis by LLaMA"):
#                 summary = semantic_analysis(combined_text)
#                 st.write(summary)

#                 st.session_state.audio_summary = summary  # Save for audio playback

#                 audio_path = text_to_speech(summary)
#                 if audio_path:
#                     with open(audio_path, "rb") as f:
#                         st.markdown("### πŸ”Š Audio Explanation")
#                         st.audio(f.read(), format="audio/mp3")
#                     os.remove(audio_path)

#         # Save history
#         st.session_state.history.append({
#             "input": combined_text,
#             "threat": threat_type,
#             "score": score,
#             "summary": summary
#         })

#         # Generate and offer download link
#         if summary:
#             report_path = create_report(label, score, threat_type, summary, combined_text)
#             with open(report_path, "rb") as f:
#                 b64 = base64.b64encode(f.read()).decode()
#                 href = f'<a href="data:file/txt;base64,{b64}" download="{report_path}">πŸ“„ Download Full Report</a>'
#                 st.markdown(href, unsafe_allow_html=True)

#         with st.expander("πŸ“œ Glossary Help"):
#             for term, definition in GLOSSARY.items():
#                 st.markdown(f"**{term.capitalize()}**: {definition}")

# # βœ… Report to IT section - outside the expander and stable
# st.markdown("---")
# report_it = st.button("πŸ“€ Report to IT", key="report_it_btn")
# if report_it:
#     st.session_state.report_sent = True

# if st.session_state.report_sent:
#     st.success("πŸ“¨ Report sent to IT successfully.")

# render_history()



# app.py

import os
import re
import fitz  # PyMuPDF
import tempfile
import base64
from datetime import datetime
from gtts import gTTS
import streamlit as st
from transformers import pipeline
from groq import Groq

# βœ… Hugging Face and GROQ secrets loaded via Hugging Face Spaces Secrets interface

# βšͺ Access secrets securely from environment variables
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
HF_TOKEN = os.getenv("HF_TOKEN")
KAGGLE_USERNAME = os.getenv("KAGGLE_USERNAME")
KAGGLE_KEY = os.getenv("KAGGLE_KEY")

# βœ… Validate secrets
if not all([GROQ_API_KEY, HF_TOKEN, KAGGLE_USERNAME, KAGGLE_KEY]):
    st.error("❌ One or more required API keys are missing from the environment.")
    st.stop()

# βœ… Initialize Groq client
client = Groq(api_key=GROQ_API_KEY)

# βœ… Load phishing detection pipeline from Hugging Face
phishing_pipe = pipeline(
    "text-classification",
    model="ealvaradob/bert-finetuned-phishing",
    token=HF_TOKEN
)

# βœ… Language and role options
language_choices = ["English", "Urdu", "French"]
role_choices = ["Admin", "Procurement", "Logistics"]

# βœ… Glossary terms
GLOSSARY = {
    "phishing": "Phishing is a scam where attackers trick you into revealing personal information.",
    "malware": "Malicious software designed to harm or exploit systems.",
    "spam": "Unwanted or unsolicited messages.",
    "tone": "The emotional character of the message."
}

# βœ… Translations (demo dictionary-based)
TRANSLATIONS = {
    "Phishing": {"Urdu": "فشنگ", "French": "HameΓ§onnage"},
    "Spam": {"Urdu": "Ψ³ΩΎΫŒΩ…", "French": "Courrier indΓ©sirable"},
    "Malware": {"Urdu": "Ω…ΫŒΩ„ΩˆΫŒΨ¦Ψ±", "French": "Logiciel malveillant"},
    "Safe": {"Urdu": "Ω…Ψ­ΩΩˆΨΈ", "French": "SΓ»r"}
}

# βœ… In-memory history and audio
if "history" not in st.session_state:
    st.session_state.history = []
if "audio_summary" not in st.session_state:
    st.session_state.audio_summary = ""
if "report_sent" not in st.session_state:
    st.session_state.report_sent = False
if "chat_active" not in st.session_state:
    st.session_state.chat_active = False
if "text_input" not in st.session_state:
    st.session_state.text_input = ""
if "uploaded_file" not in st.session_state:
    st.session_state.uploaded_file = None

# =======================
# Streamlit UI
# =======================
st.set_page_config(page_title="ZeroPhish Gate", layout="wide")

st.title("πŸ›‘οΈ ZeroPhish Gate")
st.markdown("AI-powered phishing message detection and explanation.")

# βœ… New Chat button
if st.button("πŸ†• New Chat"):
    st.session_state.chat_active = False
    st.session_state.audio_summary = ""
    st.session_state.report_sent = False
    st.session_state.text_input = ""
    st.session_state.uploaded_file = None
    

# Input fields
col1, col2 = st.columns([3, 1])
with col1:
    st.session_state.text_input = st.text_area("βœ‰οΈ Paste Suspicious Message", value=st.session_state.text_input, height=200)
    st.session_state.uploaded_file = st.file_uploader("πŸ“„ Upload PDF/TXT (optional)", type=["pdf", "txt"])

with col2:
    language = st.selectbox("🌐 Preferred Language", language_choices)
    role = st.selectbox("πŸ§‘β€πŸ’Ό Your Role", role_choices)

analyze_btn = st.button("πŸ” Analyze with AI")
clear_btn = st.button("πŸ—‘οΈ Clear History")

# =======================
# Function Definitions
# =======================
def extract_text_from_file(file):
    if file is None:
        return ""
    ext = file.name.split(".")[-1].lower()
    if ext == "pdf":
        doc = fitz.open(stream=file.read(), filetype="pdf")
        return "\n".join(page.get_text() for page in doc)
    elif ext == "txt":
        return file.read().decode("utf-8")
    return ""

def analyze_with_huggingface(text):
    try:
        result = phishing_pipe(text)
        label = result[0]['label']
        confidence = round(result[0]['score'] * 100, 2)
        threat_type = {
            "PHISHING": "Phishing",
            "SPAM": "Spam",
            "MALWARE": "Malware",
            "LEGITIMATE": "Safe"
        }.get(label.upper(), "Unknown")
        return label, confidence, threat_type
    except Exception as e:
        return "Error", 0, f"Error: {e}"

def semantic_analysis(text):
    response = client.chat.completions.create(
        model="llama3-8b-8192",
        messages=[
            {"role": "system", "content": "You are a cybersecurity assistant."},
            {"role": "user", "content": f"Explain this suspicious message for a {role} in {language} without ending in questions:\n{text}"}
        ]
    )
    raw = response.choices[0].message.content
    clean = re.sub(r"Is there anything else you'd like.*", "", raw, flags=re.I).strip()
    return clean

def translate_label(threat_type):
    return TRANSLATIONS.get(threat_type, {}).get(language, threat_type)

def text_to_speech(text):
    try:
        tts = gTTS(text=text, lang='en')
        with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as fp:
            tts.save(fp.name)
            return fp.name
    except Exception as e:
        st.error(f"❌ Audio generation error: {e}")
        return None

def create_report(label, score, threat_type, explanation, text):
    ts = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"Zerophish_Report_{ts}.txt"
    report = f"""
πŸ” AI Threat Detection Report

Input Message:
{text}

Prediction: {label}
Threat Type: {threat_type}
Confidence: {score}%

---

🧠 Explanation:
{explanation}
"""
    with open(filename, "w") as f:
        f.write(report)
    return filename

def render_history():
    with st.expander("πŸ•“ View Analysis History", expanded=True):
        for i, record in enumerate(reversed(st.session_state.history)):
            with st.container():
                st.markdown(f"**πŸ”’ Entry #{len(st.session_state.history) - i}**")
                st.markdown(f"**πŸ“ Input:** {record['input'][:100]}...")
                st.markdown(f"**πŸ” Type:** {record['threat']} | **πŸ“Š Confidence:** {record['score']}%")
                st.markdown(f"**πŸ“– Summary:** {record['summary'][:200]}...")
                st.markdown("---")

# =======================
# Run Analysis
# =======================
if clear_btn:
    st.session_state.history.clear()
    st.session_state.audio_summary = ""
    st.session_state.report_sent = False
    st.success("βœ… History cleared!")

if analyze_btn:
    st.session_state.report_sent = False
    st.session_state.chat_active = True
    combined_text = st.session_state.text_input
    if st.session_state.uploaded_file:
        extracted = extract_text_from_file(st.session_state.uploaded_file)
        combined_text += "\n" + extracted

    if not combined_text.strip():
        st.warning("⚠️ Please enter some text or upload a file to analyze.")
    else:
        label, score, threat_type = analyze_with_huggingface(combined_text)
        translated_threat = translate_label(threat_type)

        st.subheader("πŸ” AI Threat Detection Result")
        st.markdown(f"**Prediction:** {label}")
        st.markdown(f"**Threat Type:** {threat_type} ({translated_threat})")
        st.markdown(f"**Confidence:** {score}%")

        summary = ""
        if threat_type.lower() != "safe":
            with st.expander("🧠 Semantic Reanalysis by LLaMA"):
                summary = semantic_analysis(combined_text)
                st.write(summary)

                st.session_state.audio_summary = summary  # Save for audio playback

                audio_path = text_to_speech(summary)
                if audio_path:
                    with open(audio_path, "rb") as f:
                        st.markdown("### πŸ”Š Audio Explanation")
                        st.audio(f.read(), format="audio/mp3")
                    os.remove(audio_path)

        # Save history
        st.session_state.history.append({
            "input": combined_text,
            "threat": threat_type,
            "score": score,
            "summary": summary
        })

        # Generate and offer download link
        if summary:
            report_path = create_report(label, score, threat_type, summary, combined_text)
            with open(report_path, "rb") as f:
                b64 = base64.b64encode(f.read()).decode()
                href = f'<a href="data:file/txt;base64,{b64}" download="{report_path}">πŸ“„ Download Full Report</a>'
                st.markdown(href, unsafe_allow_html=True)

        with st.expander("πŸ“œ Glossary Help"):
            for term, definition in GLOSSARY.items():
                st.markdown(f"**{term.capitalize()}**: {definition}")

# βœ… Report to IT section - only visible after analysis
if st.session_state.chat_active:
    st.markdown("---")
    report_it = st.button("πŸ“€ Report to IT", key="report_it_btn")
    if report_it:
        st.session_state.report_sent = True

    if st.session_state.report_sent:
        st.success("πŸ“¨ Report sent to IT successfully.")

render_history()