Daemontatox commited on
Commit
555d8b5
·
verified ·
1 Parent(s): 5afef42

Create No_textfield_ver.py

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