IqraFatima commited on
Commit
feaee1b
Β·
verified Β·
1 Parent(s): 432344c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +158 -9
app.py CHANGED
@@ -1,18 +1,30 @@
1
- # βœ… app.py for Google OAuth Login on Hugging Face or server
2
 
3
- from flask import Flask, redirect, url_for, session
4
- from authlib.integrations.flask_client import OAuth
5
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- # πŸ” Secure from Hugging Face Secrets or local environment
8
  CLIENT_ID = os.getenv("GOOGLE_CLIENT_ID")
9
  CLIENT_SECRET = os.getenv("GOOGLE_CLIENT_SECRET")
 
 
 
10
 
11
- # πŸ”§ Flask App Setup
12
  app = Flask(__name__)
13
  app.secret_key = os.urandom(24)
14
-
15
- # 🌐 OAuth2 Config
16
  oauth = OAuth(app)
17
  google = oauth.register(
18
  name='google',
@@ -25,14 +37,152 @@ google = oauth.register(
25
  client_kwargs={'scope': 'openid email profile'},
26
  )
27
 
28
- # πŸ“ Routes
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  @app.route('/')
30
  def home():
31
  email = session.get('email', None)
32
  if email:
 
 
 
33
  return f"""
34
  <div style='display: flex; justify-content: center; align-items: center; height: 100vh; flex-direction: column; font-family: sans-serif;'>
35
  <h2>βœ… Logged in as: {email}</h2>
 
36
  <a href='/logout' style='margin-top: 10px; color: #c00;'>Logout</a>
37
  </div>
38
  """
@@ -62,6 +212,5 @@ def logout():
62
  session.clear()
63
  return redirect('/')
64
 
65
- # πŸš€ Run App
66
  if __name__ == "__main__":
67
  app.run(host="0.0.0.0", port=7860)
 
1
+ # βœ… Combined Flask + Gradio App with Google OAuth for CyberSentinel
2
 
 
 
3
  import os
4
+ import re
5
+ import csv
6
+ import fitz # PyMuPDF
7
+ import shutil
8
+ import smtplib
9
+ from datetime import datetime
10
+ from flask import Flask, redirect, url_for, session, request
11
+ from email.mime.text import MIMEText
12
+ from email.mime.multipart import MIMEMultipart
13
+ from authlib.integrations.flask_client import OAuth
14
+ import gradio as gr
15
+ from groq import Groq
16
+ from threading import Thread
17
 
18
+ # === Secrets ===
19
  CLIENT_ID = os.getenv("GOOGLE_CLIENT_ID")
20
  CLIENT_SECRET = os.getenv("GOOGLE_CLIENT_SECRET")
21
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
22
+ OFFICIAL_EMAIL = "iqrafatima1717@gmail.com"
23
+ OFFICIAL_EMAIL_PASS = os.getenv("OFFICIAL_EMAIL_APP_PASS")
24
 
25
+ # === Flask App ===
26
  app = Flask(__name__)
27
  app.secret_key = os.urandom(24)
 
 
28
  oauth = OAuth(app)
29
  google = oauth.register(
30
  name='google',
 
37
  client_kwargs={'scope': 'openid email profile'},
38
  )
39
 
40
+ # === Groq Client ===
41
+ os.environ["GROQ_API_KEY"] = GROQ_API_KEY
42
+ client = Groq(api_key=GROQ_API_KEY)
43
+
44
+ # === App State ===
45
+ session_email = ""
46
+ it_email_choices = ["fiqra753@gmail.com"]
47
+ language_choices = ["English", "Urdu", "Arabic", "French", "German", "Spanish", "Portuguese", "Hindi", "Turkish",
48
+ "Bengali", "Russian", "Chinese", "Japanese", "Korean", "Swahili", "Indonesian", "Italian",
49
+ "Dutch", "Polish", "Thai", "Vietnamese", "Romanian", "Persian", "Punjabi", "Greek", "Hebrew",
50
+ "Malay", "Czech", "Danish", "Finnish", "Hungarian", "Norwegian", "Slovak", "Swedish", "Tamil",
51
+ "Telugu", "Gujarati", "Marathi", "Pashto", "Serbian", "Croatian", "Ukrainian", "Bulgarian",
52
+ "Filipino", "Sinhala", "Mongolian", "Kazakh", "Azerbaijani", "Nepali", "Malayalam"]
53
+
54
+ # === Core Logic ===
55
+ def build_prompt_messages(user_input, language="English"):
56
+ system_prompt = f"""
57
+ You are a cybersecurity assistant built for employees in the supply chain industry.
58
+ Your job is to:
59
+ - Identify the tone
60
+ - Detect threat type
61
+ - Score risk 0–100%
62
+ - Explain in {language}
63
+ - Advise simply
64
+ """.strip()
65
+ user_prompt = f"""
66
+ Analyze:
67
+ {user_input}
68
+
69
+ Format:
70
+ 1. Tone:
71
+ 2. Threat Type:
72
+ 3. Threat Score:
73
+ 4. Explanation (in {language}):
74
+ 5. Advice (in {language}):
75
+ """.strip()
76
+ return [
77
+ {"role": "system", "content": system_prompt},
78
+ {"role": "user", "content": user_prompt}
79
+ ]
80
+
81
+ def extract_text_from_file(file_obj):
82
+ if file_obj is None:
83
+ return ""
84
+ filepath = file_obj.name
85
+ ext = filepath.split(".")[-1].lower()
86
+ if ext == "pdf":
87
+ doc = fitz.open(filepath)
88
+ return "\n".join(page.get_text() for page in doc)
89
+ elif ext == "txt":
90
+ with open(filepath, "r", encoding="utf-8") as f:
91
+ return f.read()
92
+ return ""
93
+
94
+ def analyze_message_interface(text_input, uploaded_file, language):
95
+ global session_email
96
+ file_text = extract_text_from_file(uploaded_file) if uploaded_file else ""
97
+ input_text = f"{text_input.strip()}\n\n{file_text.strip()}".strip()
98
+ if not input_text:
99
+ return "❌ No input provided.", gr.update(visible=False), gr.update(visible=False)
100
+ messages = build_prompt_messages(input_text, language)
101
+ response = client.chat.completions.create(
102
+ model="llama3-8b-8192", messages=messages, temperature=0.3, max_tokens=700
103
+ )
104
+ result = response.choices[0].message.content.strip()
105
+ is_threat = any(term in result.lower() for term in ["phishing", "spam", "malware"])
106
+ return result, gr.update(visible=is_threat), gr.update(visible=is_threat)
107
+
108
+ def save_report(email, result):
109
+ time_now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
110
+ with open("cyber_reports.csv", "a", newline='', encoding='utf-8') as csvfile:
111
+ csv.writer(csvfile).writerow([time_now, email, result])
112
+
113
+ def download_report():
114
+ global session_email
115
+ filtered = []
116
+ with open("cyber_reports.csv", "r", encoding='utf-8') as infile:
117
+ for row in csv.reader(infile):
118
+ if len(row) >= 2 and row[1].strip() == session_email:
119
+ filtered.append(row)
120
+ with open("report_download.csv", "w", newline='', encoding='utf-8') as outfile:
121
+ csv.writer(outfile).writerows(filtered)
122
+ return "report_download.csv"
123
+
124
+ def report_to_it(language, selected_email, analysis_result):
125
+ global session_email
126
+ subject = "🚨 Suspicious Activity Reported via CyberSentinel"
127
+ body = f"""Dear IT,
128
+
129
+ Reported by user: {session_email}
130
+
131
+ Result:
132
+ {analysis_result}
133
+
134
+ Please investigate.
135
+
136
+ β€” CyberSentinel"""
137
+ try:
138
+ save_report(session_email, analysis_result)
139
+ msg = MIMEMultipart()
140
+ msg["From"] = OFFICIAL_EMAIL
141
+ msg["To"] = selected_email
142
+ msg["Subject"] = subject
143
+ msg.attach(MIMEText(body, "plain"))
144
+ with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
145
+ server.login(OFFICIAL_EMAIL, OFFICIAL_EMAIL_PASS)
146
+ server.sendmail(OFFICIAL_EMAIL, selected_email, msg.as_string())
147
+ return "βœ… Report sent."
148
+ except Exception as e:
149
+ return f"❌ Email failed: {str(e)}"
150
+
151
+ # === Gradio UI ===
152
+ def start_gradio():
153
+ global session_email
154
+ with gr.Blocks(title="CyberSentinel") as demo:
155
+ text_input = gr.Textbox(label="βœ‰οΈ Paste Message", lines=6)
156
+ file_input = gr.File(label="πŸ“„ Upload PDF/TXT", file_types=[".pdf", ".txt"])
157
+ language = gr.Dropdown(label="🌐 Language", choices=language_choices, value="English")
158
+ analyze_btn = gr.Button("πŸ” Analyze")
159
+ output = gr.Textbox(label="🧠 Result", lines=10)
160
+ report_btn = gr.Button("🚨 Report to IT", visible=False)
161
+ it_email_dropdown = gr.Dropdown(label="πŸ“¬ IT Email", choices=it_email_choices, visible=False)
162
+ report_msg = gr.Textbox(label="πŸ“£ Confirmation", visible=False)
163
+ download_btn = gr.Button("⬇️ Download Reports")
164
+ download_file = gr.File(label="Download CSV", visible=False)
165
+
166
+ analyze_btn.click(fn=analyze_message_interface, inputs=[text_input, file_input, language], outputs=[output, report_btn, it_email_dropdown])
167
+ report_btn.click(fn=report_to_it, inputs=[language, it_email_dropdown, output], outputs=[report_msg])
168
+ report_btn.click(lambda: gr.update(visible=True), outputs=[report_msg])
169
+ download_btn.click(fn=download_report, outputs=[download_file])
170
+ download_btn.click(lambda: gr.update(visible=True), outputs=[download_file])
171
+
172
+ demo.launch(share=True)
173
+
174
+ # === Flask Routes ===
175
  @app.route('/')
176
  def home():
177
  email = session.get('email', None)
178
  if email:
179
+ global session_email
180
+ session_email = email
181
+ Thread(target=start_gradio).start()
182
  return f"""
183
  <div style='display: flex; justify-content: center; align-items: center; height: 100vh; flex-direction: column; font-family: sans-serif;'>
184
  <h2>βœ… Logged in as: {email}</h2>
185
+ <p>CyberSentinel interface launched in new tab. You can close this tab.</p>
186
  <a href='/logout' style='margin-top: 10px; color: #c00;'>Logout</a>
187
  </div>
188
  """
 
212
  session.clear()
213
  return redirect('/')
214
 
 
215
  if __name__ == "__main__":
216
  app.run(host="0.0.0.0", port=7860)