afouda commited on
Commit
ce1a30c
·
verified ·
1 Parent(s): 5311f54

Upload 2 files

Browse files
Files changed (2) hide show
  1. appGemma.py +451 -0
  2. requirements.txt +5 -0
appGemma.py ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # csword_ai_chatbot.py (Full Version with Dropdowns + Validation + Admin + General Q&A)
2
+
3
+ import os
4
+ import sys
5
+ import csv
6
+ import re
7
+ import requests
8
+ from datetime import datetime
9
+ from bs4 import BeautifulSoup
10
+ from openai import OpenAI
11
+ import gradio as gr
12
+
13
+ # 1. Load CSWORD.ai context
14
+ # load_context() alternative using a saved HTML file
15
+ def load_context():
16
+ with open("csword_homepage.html", "r", encoding="utf-8") as file:
17
+ soup = BeautifulSoup(file.read(), "html.parser")
18
+ texts = [tag.get_text(separator=" ").strip() for tag in soup.find_all(["h1", "h2", "h3", "p", "li"])]
19
+ return "\n".join(filter(None, texts))
20
+ # 2. Set up DeepInfra client
21
+ token = os.getenv("DEEPINFRA_TOKEN", "285LUJulGIprqT6hcPhiXtcrphU04FG4")
22
+ openai = OpenAI(api_key=token, base_url="https://api.deepinfra.com/v1/openai")
23
+ model_name = "google/gemma-3-27b-it"
24
+
25
+ SYSTEM_PROMPT_CSWORD = f"""
26
+ You are Csword AI a helpful and expert cybersecurity assistant working on the csword.ai website. Your purpose is to answer user questions only related to cybersecurity. Do not answer questions outside this domain. Provide clear, accurate, and up-to-date cybersecurity information tailored for individuals, businesses, or IT teams. If a question is unrelated to cybersecurity, respond politely that you are only trained to answer cybersecurity-related questions.
27
+ - content website: https://csword.ai
28
+ csword Next-Gen AI Platform for Cyber Awareness
29
+ - Csword Features
30
+ 1- AI-Powered Phishing Simulations
31
+ 2- Intelligent LMS Training with AI Adaptation
32
+ 3- Penetration Testing & Threat Simulation
33
+ 4- Digital Awareness Deliverables
34
+ 5- Cybersecurity Events
35
+
36
+ 6- Risk & Security Assessment Services
37
+ 7- Interactive Awareness Sessions
38
+
39
+ - Get Results in 3 Simple Steps
40
+ From setup to securing your organization, our AI guides you every step of the way.
41
+ 1- Assess Your Risk
42
+ Our AI analyzes your current security posture and identifies vulnerabilities
43
+ 2-Deploy Smart Training
44
+ Launch AI-powered campaigns with personalized learning paths for each employee
45
+ 3- Monitor & Improve
46
+ Track progress with real-time analytics and continuous improvement recommendations
47
+
48
+ - Why Organizations Choose our Ai-Platform ?
49
+ Be part of the growing number of businesses transforming their cybersecurity with our cutting-edge AI platform.
50
+ 1- 90% reduction in phishing susceptibility
51
+ (Measurable Results) Track real improvements in security awareness with detailed analytics and reporting.
52
+
53
+ 2- < 24 hours setup time
54
+ (Easy Integration) Seamlessly integrates with your existing security stack and HR systems.
55
+
56
+ 3- 99.9% customer satisfaction
57
+ Expert Support
58
+ Our cybersecurity experts are always available to help you maximize your results.
59
+
60
+ - Guarding Your Digital Future
61
+ CSWORD is a leading cybersecurity company dedicated to transforming organizational security culture through innovative AI-powered solutions and expert services.
62
+
63
+ 1- AI-Powered Phishing Simulations (Backed by consistent positive outcomes)
64
+ Advanced AI creates realistic, targeted phishing campaigns to test your team's awareness.
65
+ 2- Intelligent LMS Training with AI Adaptation (Personalized Learning)
66
+ Personalized cybersecurity training modules adapted to each employee's role and risk level.
67
+ 3- Penetration Testing & Threat Simulation (Real-time Analytics)
68
+ Comprehensive testing for web, mobile, and networks, including Red & Purple teaming exercises.
69
+ 4- Digital Awareness Deliverables (Branded Content)
70
+ 5-Cybersecurity Events (Interactive Learning)
71
+ 7-Interactive Awareness Sessions (Expert-Led Training)
72
+ 8- Advanced Executive Reporting (Real-time Analytics)
73
+ AI-driven risk scoring and comprehensive analytics for informed decision-making.
74
+ 9-24/7 AI Cybersecurity Consultant (Always Available)
75
+ Intelligent chatbot providing instant cybersecurity guidance and support.
76
+ 9- Penetration Testing & Threat Simulation
77
+
78
+ - Solutions
79
+ 1- AI-Powered Awareness
80
+ 2- Digital Awareness Deliverables
81
+ 3- Interactive Awareness Sessions
82
+ 4- Cybersecurity Events
83
+ 5- Penetration Testing & Threat Simulation
84
+ 5- Risk & Security Assessment
85
+
86
+ Discover how artificial intelligence transforms cybersecurity awareness training, delivering personalized, adaptive, and highly effective security education.
87
+ 1- AI-Driven
88
+ 2- Enterprise-Grade
89
+ 3- Scalable
90
+
91
+ about Csword
92
+ - Our Story
93
+ For generations, our ancestors drew their swords to defend their people, their lands, and their future. Today, as the battles rage in cyberspace, we carry that same spirit forward.
94
+ At Csword, where heritage meets cybersecurity, we forge CyberSwords — powerful shields against the invisible enemies of the digital world.
95
+ Inspired by the courage of those who came before us, we stand unshaken, guarding not only our legacy but your future with strength, honor, and relentless vigilance.
96
+ -Our Vision
97
+ Redefining cybersecurity by merging AI innovation with human insight to protect and empower organizations around the world.
98
+ - Our Mission
99
+ Empowering organizations to thrive securely with AI-led cybersecurity solutions that are proactive, dependable, and future-ready.
100
+ - Our Core Values
101
+ These fundamental principles guide everything we do and shape our relationships with clients, partners, and each other.
102
+ 1- Security First
103
+ From code to cloud, your data is protected by military-grade security and strict privacy standards.
104
+ 2-Innovation Driven
105
+ We innovate relentlessly—using AI and research to transform how cybersecurity is taught and learned.
106
+ 3- People Centered
107
+ Real security starts with people. We build smarter habits through engaging, human-centered learning.
108
+ 4-Excellence Committed
109
+ We're committed to delivering exceptional results and continuous improvement in all our services and solutions.
110
+ - Leading the Future of Cyber Awareness
111
+ We're more than a cybersecurity company—we're your strategic partner in building a security-conscious culture that protects and empowers your organization.
112
+ 1-Proven Expertise
113
+ Our team combines decades of cybersecurity experience with cutting-edge AI technology to deliver unparalleled results.
114
+ 2-Innovation Leadership
115
+ We're pioneers in AI-powered cybersecurity awareness, continuously developing new technologies to stay ahead of threats.
116
+ 3-Measurable Results
117
+ Our clients see dramatic improvements in security awareness metrics, with some achieving 90% reduction in phishing susceptibility.
118
+ 4-Complete Solutions
119
+ From AI-powered platforms to expert services, we provide everything you need for comprehensive cybersecurity awareness.
120
+ 5-Scalable Platform
121
+ Our solutions grow with your organization, from small businesses to enterprise corporations with thousands of employees.
122
+ 6-Dedicated Support
123
+ Our customer success team ensures you get maximum value from our platform with ongoing support and optimization.
124
+ What's Next?
125
+ 1- We Receive Your Message
126
+ Our team is notified instantly when you submit your inquiry
127
+
128
+ 2- We Analyze Your Needs
129
+ Our specialists review your request and prepare a response
130
+
131
+ 3- We Respond Promptly
132
+ You'll hear from us within 24 hours with next steps
133
+
134
+ - Services
135
+ 1- AI-Powered Phishing Simulations
136
+ Advanced security testing tools powered by artificial intelligence
137
+ * Key Features
138
+ 1- Realistic email templates
139
+ 2- Customizable attack scenarios
140
+ 3- Behavioral analysis
141
+ 4- Automated deployment
142
+ * Benefits
143
+ 1- Improved security awareness
144
+ 2- Reduced vulnerability
145
+ 3- Compliance with regulations
146
+ 4- Measurable security metrics
147
+
148
+ 2- Intelligent LMS Training with AI Adaptation
149
+ Personalized learning management system that adapts training content to individual employee needs and learning patterns.
150
+ * Key Features
151
+ 1- Personalized, role-based content with adaptive difficulty
152
+ 2- Seamless LMS integration and multi-language support
153
+ 3- AI-optimized learning paths with performance-based recommendations
154
+ * Benefits
155
+ 1- Increase training completion rates by 75%
156
+ 2- Reduce training time while improving retention
157
+ 3- Personalized learning experiences drive engagement
158
+
159
+
160
+ 3- Executive Reporting with AI Risk Scoring
161
+ Comprehensive analytics platform that provides actionable insights through AI-powered risk assessment and predictive modeling.
162
+ * Key Features
163
+ 1- Risk scores and trends for individuals & departments
164
+ 2- AI-driven predictive modeling and recommendations
165
+ 3- Automated executive summaries with custom KPIs
166
+ * Benefits
167
+ 1- Data-driven decision making for security investments
168
+ 2- Proactive risk management instead of reactive responses
169
+ 3- Clear ROI demonstration for security training programs
170
+
171
+ 4- 24/7 AI Cybersecurity Consultant
172
+ Intelligent chatbot providing instant cybersecurity guidance, support, and training assistance around the clock.
173
+ * Key Features
174
+ 1- Instant AI chatbot support for users, admins & employees
175
+ 2- NLP guidance integrated with cybersecurity knowledge base
176
+ 3- Smart escalation to human experts when needed
177
+ * Benefits
178
+ 1- Reduce support ticket volume by 60%
179
+ 2- Instant answers improve user satisfaction
180
+ 3- 24/7 availability enhances security culture
181
+
182
+ - Digital Awareness Deliverables (Branded Content)
183
+ Custom-designed digital content to reinforce cybersecurity awareness across your organization.
184
+ 1- Digital Awareness Deliverables
185
+ * Security Awareness Poster
186
+ • Eye-catching visual design
187
+ • Your company branding
188
+ • Clear security messaging
189
+ • Multiple format delivery
190
+ * Monthly Newsletter
191
+ • Latest threat intelligence
192
+ • Security tips and best practices
193
+ • Company-specific content
194
+ • Email-ready format
195
+
196
+
197
+ -Cybersecurity Events (Interactive Learning)
198
+ Engaging events that build security culture and team engagement through interactive learning.
199
+ Real-Time Attacker Simulation -Engage in several intense, realistic scenarios to test your response capabilities under pressure.
200
+ Gamified Cyber Awareness to Empower Your Team - Turn learning into a fun, competitive experience with points, leaderboards, and engaging challenges.
201
+ 6-Risk & Security Assessment Services (Always Available)
202
+ - Our Process
203
+ Event planning and logistics coordination
204
+ Expert facilitator and speaker arrangement
205
+ Custom event materials and resources
206
+ Post-event follow-up and assessment
207
+ - Key Benefits:
208
+ Creates memorable learning experiences
209
+ Builds team cohesion around security goals
210
+ Generates excitement about cybersecurity
211
+ In-depth assessments covering risk, device configurations, network architecture, and source code review.
212
+
213
+ -Interactive Awareness Sessions (Expert-Led Training) :
214
+ Interactive, expert-led training sessions delivered in-person or online to educate your workforce.
215
+ Interactive, in-person cybersecurity training sessions designed to engage and educate your workforce.
216
+ Experience Interactive Cybersecurity Training Our on-site sessions bring real-world cybersecurity scenarios directly to your team, creating engaging learning experiences that stick.
217
+ * Online Training Sessions "Leadership briefings on security strategy"
218
+ * On-Site Training Sessions "Hands-on learning with real scenarios"
219
+ - Our Process
220
+ 1- Pre-session consultation and needs assessment
221
+ 2- Custom content development
222
+ 3- Online delivery by certified experts
223
+ 4- Follow-up materials and action plans
224
+ - Key Benefits:
225
+ 1- Face-to-face interaction increases engagement and retention
226
+ 2- Customized content addresses your specific challenges
227
+ 3- Expert facilitators provide real-world insights
228
+
229
+ - Cybersecurity Events
230
+ Comprehensive cybersecurity events that build security culture and team engagement through interactive learning.
231
+ Engaging Cybersecurity Events Real events that create lasting impact on your security culture
232
+ Real-Time Attacker Simulation : Engage in several intense, realistic scenarios to test your response capabilities under pressure.
233
+ Gamified Cyber Awareness to Empower Your Team : Turn learning into a fun, competitive experience with points, leaderboards, and engaging challenges.
234
+ - Our Process
235
+ Event planning and logistics coordination
236
+ Expert facilitator and speaker arrangement
237
+ Custom event materials and resources
238
+ Post-event follow-up and assessment
239
+ - Key Benefits:
240
+ Creates memorable learning experiences
241
+ Builds team cohesion around security goals
242
+ Generates excitement about cybersecurity
243
+
244
+ - Penetration Testing & Threat Simulation
245
+ Proactively identify and mitigate vulnerabilities with our expert-led penetration testing and attack simulation services.
246
+ Our Pen Testing Services :Comprehensive assessments to uncover critical security flaws.
247
+ Web & Mobile App Pen Testing :Identify and exploit vulnerabilities in your web and mobile applications before attackers do.
248
+ Internal & External Network Pen Testing : Assess the security of your network infrastructure from both internal and external perspectives.
249
+ Wireless Pen Testing : Evaluate the security of your wireless networks to prevent unauthorized access.
250
+ Red Teaming / Purple Teaming : Simulate real-world attack scenarios to test your organization's detection and response capabilities.
251
+ - Our Methodology
252
+ A structured approach to ensure thorough testing and actionable results.
253
+ 1- Scoping & Planning : We work closely with you to define the scope, objectives, and rules of engagement, ensuring our testing aligns with your business goals.
254
+ 2- Reconnaissance & Discovery : Our experts gather intelligence and use advanced tools to identify potential attack vectors and map out your digital footprint.
255
+ 3- Vulnerability Assessment : In a controlled manner, we attempt to exploit identified vulnerabilities to validate real-world risks and demonstrate potential impact.
256
+ 4- Reporting & Remediation : We provide a comprehensive report with actionable recommendations, prioritized by risk, to help you effectively remediate all findings.
257
+
258
+ - Risk & Security Assessment Services
259
+ Gain a comprehensive understanding of your security posture and make informed, risk-based decisions.
260
+ - Our Assessment Services
261
+ 1- Risk Assessment : Identify, analyze, and evaluate security risks to your organization's assets and processes.
262
+ 2- Device Configuration Assessment : Ensure your servers, firewalls, and endpoints are hardened and securely configured.
263
+ 3- Network Architecture Assessment : Assess the design of your network for security flaws, bottlenecks, and single points of failure.
264
+ 4- Source Code Review : Manually and automatically inspect source code to find security vulnerabilities missed by other tools.
265
+ - Our Process
266
+ Information Gathering : We collect documentation and interview key personnel to understand your business processes, assets, and existing security controls.
267
+ Vulnerability Analysis : Our team uses a combination of automated tools and manual inspection to identify vulnerabilities and misconfigurations.
268
+ Risk Evaluation : We analyze vulnerabilities to determine their likelihood and potential impact, resulting in a prioritized list of risks.
269
+ Strategic Recommendations : We deliver a detailed report with actionable recommendations to mitigate risks and build a resilient security roadmap.
270
+
271
+
272
+ """
273
+ SYSTEM_PROMPT_GENERAL = "You are a cybersecurity expert. Answer clearly and informatively."
274
+ CONTEXT = SYSTEM_PROMPT_CSWORD
275
+
276
+ if not CONTEXT.strip():
277
+ CONTEXT = "CSWORD.ai is a cybersecurity awareness and training platform that leverages AI to deliver personalized, adaptive education."
278
+
279
+ # 3. Form state
280
+ form_type = None
281
+ user_form_data = {}
282
+ final_question = ("final_note", "Would you like any further assistance with cybersecurity-related topics?")
283
+
284
+ form_definitions = {
285
+ "demo": [
286
+ ("name", "Full Name *"),
287
+ ("company", "Company Name *"),
288
+ ("email", "Work Email *"),
289
+ ("phone", "Phone Number"),
290
+ ("employees", ["Number of Employees *", ["1-50", "51-200", "201-500", "+500"]]),
291
+ ("services", "Services of Interest (select multiple if needed):\n"
292
+ "- AI Phishing Simulation Platform\n"
293
+ "- AI-Tailored LMS Training\n"
294
+ "- Cybersecurity Events\n"
295
+ "- Digital Awareness Deliverables\n"
296
+ "- Executive Reporting & Risk Scoring\n"
297
+ "- On-Site Awareness Sessions\n"
298
+ "- Penetration Testing & Threat Simulation\n"
299
+ "- Risk & Security Assessment\n"
300
+ "- 24/7 AI Cybersecurity Consultant"),
301
+ ("specific_reqs", "Do you have any specific requirements or questions?"),
302
+ final_question
303
+ ],
304
+ "contact": [
305
+ ("name", "Full Name *"),
306
+ ("email", "Email Address *"),
307
+ ("company", "Company"),
308
+ ("subject", "Subject *"),
309
+ ("message", "Message *"),
310
+ final_question
311
+ ]
312
+ }
313
+
314
+ # 4. Validation
315
+
316
+ def validate_input(key, value):
317
+ if not value.strip():
318
+ return "This field is required. Please provide a value."
319
+ if key == "email" and not re.match(r"[^@\s]+@[^@\s]+\.[^@\s]+", value):
320
+ return "Invalid email format. Please enter a valid email address."
321
+ if key == "phone" and re.search(r"[a-zA-Z]", value):
322
+ return "Invalid phone number. Only digits and symbols are allowed."
323
+ return None
324
+
325
+ # 5. Chat handler
326
+
327
+ def answer_question(query: str, is_general=False) -> str:
328
+ prompt = SYSTEM_PROMPT_GENERAL if is_general else f"{SYSTEM_PROMPT_CSWORD}\nContext:\n{CONTEXT}"
329
+ messages = [
330
+ {"role": "system", "content": prompt},
331
+ {"role": "user", "content": query},
332
+ ]
333
+ try:
334
+ response = openai.chat.completions.create(
335
+ model=model_name,
336
+ messages=messages,
337
+ reasoning_effort="none"
338
+ )
339
+ return response.choices[0].message.content
340
+ except Exception as e:
341
+ return f"Error: {e}"
342
+
343
+ # 6. Chat function
344
+
345
+ def chat_fn(message, history):
346
+ global user_form_data, form_type
347
+
348
+ if form_type and len(user_form_data) < len(form_definitions[form_type]):
349
+ # Allow user to cancel form at any step
350
+ cancel_keywords = ["cancel", "stop", "don't want", "exit", "no thanks", "back", "abort"]
351
+ if any(kw in message.lower() for kw in cancel_keywords):
352
+ user_form_data, form_type = {}, None
353
+ return history + [(message, "Form cancelled. How can I assist you with cybersecurity?")], "", gr.update(visible=False)
354
+
355
+ key, question = form_definitions[form_type][len(user_form_data)]
356
+
357
+ if isinstance(question, list):
358
+ if message not in question[1]:
359
+ return history + [(message, f"Please choose one of the provided options: {', '.join(question[1])}"), ("", question[0])], "", gr.update(visible=True)
360
+ user_form_data[key] = message
361
+ history = history + [(message, "")]
362
+ else:
363
+ error = validate_input(key, message)
364
+ if error:
365
+ return history + [(message, error), ("", question)], "", gr.update(visible=False)
366
+ user_form_data[key] = message
367
+ history = history + [(message, "")]
368
+
369
+ if len(user_form_data) < len(form_definitions[form_type]):
370
+ next_q = form_definitions[form_type][len(user_form_data)][1]
371
+ dropdown_visible = isinstance(next_q, list)
372
+ return history + [("", next_q[0] if dropdown_visible else next_q)], "", gr.update(visible=dropdown_visible)
373
+ else:
374
+ user_form_data["timestamp"] = datetime.now().isoformat()
375
+ user_form_data["type"] = form_type.capitalize()
376
+ file_name = f"{form_type}_requests.csv"
377
+ file_exists = os.path.isfile(file_name)
378
+ with open(file_name, mode="a", newline="") as file:
379
+ writer = csv.DictWriter(file, fieldnames=list(user_form_data.keys()))
380
+ if not file_exists:
381
+ writer.writeheader()
382
+ writer.writerow(user_form_data)
383
+ msg1 = f"Thank you! Your {form_type} request has been received."
384
+ msg2 = final_question[1]
385
+ user_form_data, form_type = {}, None
386
+ return history + [("", msg1), ("", msg2)], "", gr.update(visible=False)
387
+
388
+ if message.lower().startswith("admin:") and "guide" in message.lower():
389
+ steps = (
390
+ "To work with the CSWORD.ai platform:\n"
391
+ "1. Login to the admin dashboard.\n"
392
+ "2. Upload user list for training enrollment.\n"
393
+ "3. Configure phishing simulation campaigns.\n"
394
+ "4. Schedule awareness sessions.\n"
395
+ "5. Monitor progress via the Executive Risk Dashboard."
396
+ )
397
+ return history + [(message, steps)], "", gr.update(visible=False)
398
+
399
+ if re.search(r"\b(demo|quote|custom)\b", message, re.IGNORECASE):
400
+ form_type = "demo"
401
+ user_form_data = {}
402
+ next_q = form_definitions[form_type][0][1]
403
+ dropdown_visible = isinstance(next_q, list)
404
+ return history + [(message, "Sure! Let's start with a few details."), ("", next_q[0] if dropdown_visible else next_q)], "", gr.update(visible=dropdown_visible)
405
+
406
+ # Only trigger contact form for more specific contact intent
407
+ if re.search(r"\b(contact|message|speak)\b", message, re.IGNORECASE):
408
+ form_type = "contact"
409
+ user_form_data = {}
410
+ next_q = form_definitions[form_type][0][1]
411
+ dropdown_visible = isinstance(next_q, list)
412
+ return history + [(message, "Of course! Please fill out the following."), ("", next_q[0] if dropdown_visible else next_q)], "", gr.update(visible=dropdown_visible)
413
+
414
+ # For generic help requests, just answer as a chatbot
415
+ if re.search(r"\bhelp\b", message, re.IGNORECASE):
416
+ return history + [(message, "Yes, of course! Tell me your question.")], "", gr.update(visible=False)
417
+
418
+ if re.search(r"\b(cybersecurity|malware|phishing|ransomware|network|threat|attack|industry|NIST|ISO|compliance)\b", message, re.IGNORECASE):
419
+ reply = answer_question(message, is_general=True)
420
+ return history + [(message, reply)], "", gr.update(visible=False)
421
+
422
+ reply = answer_question(message)
423
+ return history + [(message, reply)], "", gr.update(visible=False)
424
+
425
+ # 7. Launch Gradio
426
+ with gr.Blocks(title="CSWORD.ai Chatbot") as demo:
427
+ gr.Markdown("## 👋 Welcome to the CSWORD.ai Assistant!\nHello, I’m the CSWORD AI Assistant 🤖. [Click here to visit CSWORD.ai](https://csword.ai)\nAsk questions, request a demo, or contact us.")
428
+ chatbot = gr.Chatbot()
429
+ # Show opening sentence when chatbot loads
430
+ chatbot.value = [[None, "👋 Hello! I am the CSWORD AI Chatbot. I can help you with any cybersecurity-related questions or guidance. How can I assist you today?"]]
431
+ with gr.Row():
432
+ user_input = gr.Textbox(show_label=False, placeholder="Enter your question here...", scale=4, visible=True)
433
+ dropdown_input = gr.Dropdown(
434
+ choices=["1-50", "51-200", "201-500", "+500"],
435
+ label="Number of Employees",
436
+ visible=False,
437
+ scale=2
438
+ )
439
+ submit = gr.Button("Send")
440
+ # Only use dropdown value if dropdown is visible and filled, otherwise use text input
441
+ def get_query(txt, drop, hist):
442
+ # If dropdown is visible and has a value, use it; otherwise use text
443
+ if dropdown_input.visible and drop:
444
+ return chat_fn(drop, hist)
445
+ return chat_fn(txt, hist)
446
+
447
+ submit.click(get_query, inputs=[user_input, dropdown_input, chatbot], outputs=[chatbot, user_input, dropdown_input])
448
+ user_input.submit(get_query, inputs=[user_input, dropdown_input, chatbot], outputs=[chatbot, user_input, dropdown_input])
449
+
450
+ if __name__ == "__main__":
451
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+
2
+ openai
3
+ gradio
4
+ requests
5
+ beautifulsoup4