IqraFatima commited on
Commit
52aff78
·
verified ·
1 Parent(s): 43ab35b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +237 -1
app.py CHANGED
@@ -1,3 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # app.py
2
 
3
  import os
@@ -207,7 +442,7 @@ if analyze_btn:
207
  st.audio(f.read(), format="audio/mp3")
208
  os.remove(audio_path)
209
 
210
- if st.button("📤 Send Report to IT"):
211
  st.success("📨 Report sent to IT successfully.")
212
 
213
  # Save history
@@ -231,3 +466,4 @@ if analyze_btn:
231
  st.markdown(f"**{term.capitalize()}**: {definition}")
232
 
233
  render_history()
 
 
1
+ # # app.py
2
+
3
+ # import os
4
+ # import re
5
+ # import fitz # PyMuPDF
6
+ # import tempfile
7
+ # import base64
8
+ # from datetime import datetime
9
+ # from gtts import gTTS
10
+ # import streamlit as st
11
+ # from transformers import pipeline
12
+ # from groq import Groq
13
+
14
+ # # ✅ Hugging Face and GROQ secrets loaded via Hugging Face Spaces Secrets interface
15
+
16
+ # # ⛳ Access secrets securely from environment variables
17
+ # GROQ_API_KEY = os.getenv("GROQ_API_KEY")
18
+ # HF_TOKEN = os.getenv("HF_TOKEN")
19
+ # KAGGLE_USERNAME = os.getenv("KAGGLE_USERNAME")
20
+ # KAGGLE_KEY = os.getenv("KAGGLE_KEY")
21
+
22
+ # # ✅ Validate secrets
23
+ # if not all([GROQ_API_KEY, HF_TOKEN, KAGGLE_USERNAME, KAGGLE_KEY]):
24
+ # st.error("❌ One or more required API keys are missing from the environment.")
25
+ # st.stop()
26
+
27
+ # # ✅ Initialize Groq client
28
+ # client = Groq(api_key=GROQ_API_KEY)
29
+
30
+ # # ✅ Load phishing detection pipeline from Hugging Face
31
+ # phishing_pipe = pipeline(
32
+ # "text-classification",
33
+ # model="ealvaradob/bert-finetuned-phishing",
34
+ # token=HF_TOKEN
35
+ # )
36
+
37
+ # # ✅ Language and role options
38
+ # language_choices = ["English", "Urdu", "French"]
39
+ # role_choices = ["Admin", "Procurement", "Logistics"]
40
+
41
+ # # ✅ Glossary terms
42
+ # GLOSSARY = {
43
+ # "phishing": "Phishing is a scam where attackers trick you into revealing personal information.",
44
+ # "malware": "Malicious software designed to harm or exploit systems.",
45
+ # "spam": "Unwanted or unsolicited messages.",
46
+ # "tone": "The emotional character of the message."
47
+ # }
48
+
49
+ # # ✅ Translations (demo dictionary-based)
50
+ # TRANSLATIONS = {
51
+ # "Phishing": {"Urdu": "فشنگ", "French": "Hameçonnage"},
52
+ # "Spam": {"Urdu": "سپیم", "French": "Courrier indésirable"},
53
+ # "Malware": {"Urdu": "میلویئر", "French": "Logiciel malveillant"},
54
+ # "Safe": {"Urdu": "محفوظ", "French": "Sûr"}
55
+ # }
56
+
57
+ # # ✅ In-memory history and audio
58
+ # if "history" not in st.session_state:
59
+ # st.session_state.history = []
60
+ # if "audio_summary" not in st.session_state:
61
+ # st.session_state.audio_summary = ""
62
+
63
+ # # =======================
64
+ # # Streamlit UI
65
+ # # =======================
66
+ # st.set_page_config(page_title="ZeroPhish Gate", layout="wide")
67
+
68
+ # st.title("🛡️ ZeroPhish Gate")
69
+ # st.markdown("AI-powered phishing message detection and explanation.")
70
+
71
+ # # Input fields
72
+ # col1, col2 = st.columns([3, 1])
73
+ # with col1:
74
+ # text_input = st.text_area("✉️ Paste Suspicious Message", height=200)
75
+ # uploaded_file = st.file_uploader("📄 Upload PDF/TXT (optional)", type=["pdf", "txt"])
76
+
77
+ # with col2:
78
+ # language = st.selectbox("🌐 Preferred Language", language_choices)
79
+ # role = st.selectbox("🧑‍💼 Your Role", role_choices)
80
+
81
+ # analyze_btn = st.button("🔍 Analyze with AI")
82
+ # clear_btn = st.button("🗑️ Clear History")
83
+
84
+ # # =======================
85
+ # # Function Definitions
86
+ # # =======================
87
+ # def extract_text_from_file(file):
88
+ # if file is None:
89
+ # return ""
90
+ # ext = file.name.split(".")[-1].lower()
91
+ # if ext == "pdf":
92
+ # doc = fitz.open(stream=file.read(), filetype="pdf")
93
+ # return "\n".join(page.get_text() for page in doc)
94
+ # elif ext == "txt":
95
+ # return file.read().decode("utf-8")
96
+ # return ""
97
+
98
+ # def analyze_with_huggingface(text):
99
+ # try:
100
+ # result = phishing_pipe(text)
101
+ # label = result[0]['label']
102
+ # confidence = round(result[0]['score'] * 100, 2)
103
+ # threat_type = {
104
+ # "PHISHING": "Phishing",
105
+ # "SPAM": "Spam",
106
+ # "MALWARE": "Malware",
107
+ # "LEGITIMATE": "Safe"
108
+ # }.get(label.upper(), "Unknown")
109
+ # return label, confidence, threat_type
110
+ # except Exception as e:
111
+ # return "Error", 0, f"Error: {e}"
112
+
113
+ # def semantic_analysis(text):
114
+ # response = client.chat.completions.create(
115
+ # model="llama3-8b-8192",
116
+ # messages=[
117
+ # {"role": "system", "content": "You are a cybersecurity assistant."},
118
+ # {"role": "user", "content": f"Explain this suspicious message for a {role} in {language} without ending in questions:\n{text}"}
119
+ # ]
120
+ # )
121
+ # raw = response.choices[0].message.content
122
+ # clean = re.sub(r"Is there anything else you'd like.*", "", raw, flags=re.I).strip()
123
+ # return clean
124
+
125
+ # def translate_label(threat_type):
126
+ # return TRANSLATIONS.get(threat_type, {}).get(language, threat_type)
127
+
128
+ # def text_to_speech(text):
129
+ # try:
130
+ # tts = gTTS(text=text, lang='en')
131
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as fp:
132
+ # tts.save(fp.name)
133
+ # return fp.name
134
+ # except Exception as e:
135
+ # st.error(f"❌ Audio generation error: {e}")
136
+ # return None
137
+
138
+ # def create_report(label, score, threat_type, explanation, text):
139
+ # ts = datetime.now().strftime("%Y%m%d_%H%M%S")
140
+ # filename = f"Zerophish_Report_{ts}.txt"
141
+ # report = f"""
142
+ # 🔍 AI Threat Detection Report
143
+
144
+ # Input Message:
145
+ # {text}
146
+
147
+ # Prediction: {label}
148
+ # Threat Type: {threat_type}
149
+ # Confidence: {score}%
150
+
151
+ # ---
152
+
153
+ # 🧠 Explanation:
154
+ # {explanation}
155
+ # """
156
+ # with open(filename, "w") as f:
157
+ # f.write(report)
158
+ # return filename
159
+
160
+ # def render_history():
161
+ # with st.expander("🕓 View Analysis History", expanded=True):
162
+ # for i, record in enumerate(reversed(st.session_state.history)):
163
+ # with st.container():
164
+ # st.markdown(f"**🔢 Entry #{len(st.session_state.history) - i}**")
165
+ # st.markdown(f"**📝 Input:** {record['input'][:100]}...")
166
+ # st.markdown(f"**🔐 Type:** {record['threat']} | **📊 Confidence:** {record['score']}%")
167
+ # st.markdown(f"**📖 Summary:** {record['summary'][:200]}...")
168
+ # st.markdown("---")
169
+
170
+ # # =======================
171
+ # # Run Analysis
172
+ # # =======================
173
+ # if clear_btn:
174
+ # st.session_state.history.clear()
175
+ # st.session_state.audio_summary = ""
176
+ # st.success("✅ History cleared!")
177
+
178
+ # if analyze_btn:
179
+ # combined_text = text_input
180
+ # if uploaded_file:
181
+ # extracted = extract_text_from_file(uploaded_file)
182
+ # combined_text += "\n" + extracted
183
+
184
+ # if not combined_text.strip():
185
+ # st.warning("⚠️ Please enter some text or upload a file to analyze.")
186
+ # else:
187
+ # label, score, threat_type = analyze_with_huggingface(combined_text)
188
+ # translated_threat = translate_label(threat_type)
189
+
190
+ # st.subheader("🔍 AI Threat Detection Result")
191
+ # st.markdown(f"**Prediction:** {label}")
192
+ # st.markdown(f"**Threat Type:** {threat_type} ({translated_threat})")
193
+ # st.markdown(f"**Confidence:** {score}%")
194
+
195
+ # summary = ""
196
+ # if threat_type.lower() != "safe":
197
+ # with st.expander("🧠 Semantic Reanalysis by LLaMA"):
198
+ # summary = semantic_analysis(combined_text)
199
+ # st.write(summary)
200
+
201
+ # st.session_state.audio_summary = summary # Save for audio playback
202
+
203
+ # audio_path = text_to_speech(summary)
204
+ # if audio_path:
205
+ # with open(audio_path, "rb") as f:
206
+ # st.markdown("### 🔊 Audio Explanation")
207
+ # st.audio(f.read(), format="audio/mp3")
208
+ # os.remove(audio_path)
209
+
210
+ # if st.button("📤 Send Report to IT"):
211
+ # st.success("📨 Report sent to IT successfully.")
212
+
213
+ # # Save history
214
+ # st.session_state.history.append({
215
+ # "input": combined_text,
216
+ # "threat": threat_type,
217
+ # "score": score,
218
+ # "summary": summary
219
+ # })
220
+
221
+ # # Generate and offer download link
222
+ # if summary:
223
+ # report_path = create_report(label, score, threat_type, summary, combined_text)
224
+ # with open(report_path, "rb") as f:
225
+ # b64 = base64.b64encode(f.read()).decode()
226
+ # href = f'<a href="data:file/txt;base64,{b64}" download="{report_path}">📄 Download Full Report</a>'
227
+ # st.markdown(href, unsafe_allow_html=True)
228
+
229
+ # with st.expander("📜 Glossary Help"):
230
+ # for term, definition in GLOSSARY.items():
231
+ # st.markdown(f"**{term.capitalize()}**: {definition}")
232
+
233
+ # render_history()
234
+
235
+
236
  # app.py
237
 
238
  import os
 
442
  st.audio(f.read(), format="audio/mp3")
443
  os.remove(audio_path)
444
 
445
+ if st.button("📤 Report to IT"):
446
  st.success("📨 Report sent to IT successfully.")
447
 
448
  # Save history
 
466
  st.markdown(f"**{term.capitalize()}**: {definition}")
467
 
468
  render_history()
469
+