Spaces:
Running
Running
# csword_ai_chatbot.py (Fixed Version with Multi-Select Services) | |
import os | |
import sys | |
import csv | |
import re | |
import requests | |
from datetime import datetime | |
from bs4 import BeautifulSoup | |
from openai import OpenAI | |
import gradio as gr | |
# 1. Load CSWORD.ai context | |
def load_context(): | |
try: | |
with open("csword_homepage.html", "r", encoding="utf-8") as file: | |
soup = BeautifulSoup(file.read(), "html.parser") | |
texts = [tag.get_text(separator=" ").strip() for tag in soup.find_all(["h1", "h2", "h3", "p", "li"])] | |
return "\n".join(filter(None, texts)) | |
except FileNotFoundError: | |
return "CSWORD.ai is a cybersecurity awareness and training platform that leverages AI to deliver personalized, adaptive education." | |
# 2. Set up DeepInfra client | |
token = os.getenv("DEEPINFRA_TOKEN", "285LUJulGIprqT6hcPhiXtcrphU04FG4") | |
openai = OpenAI(api_key=token, base_url="https://api.deepinfra.com/v1/openai") | |
model_name = "google/gemma-3-27b-it" | |
SYSTEM_PROMPT_CSWORD = f""" | |
You are Csword AI (سي سورد), a helpful and expert cybersecurity assistant working on the csword.ai website. Your main purpose is to answer user questions related to cybersecurity. You can also handle questions that are somewhat related and provide clear, concise, and informative code examples. If a question is completely unrelated to cybersecurity, respond politely that you are only trained to answer cybersecurity-related questions. You must answer clearly, briefly, and accurately — tailored to individuals, businesses, or IT teams. You also understand and respond in both Arabic and English.Do not mention any competing companies. | |
csword Next-Gen AI Platform for Cyber Awareness | |
-If the user asks a question in Arabic, respond only in Arabic. | |
-If the user asks a question in English, respond only in English. | |
- Csword Features | |
1- AI-Powered Phishing Simulations | |
2- Intelligent LMS Training with AI Adaptation | |
3- Penetration Testing & Threat Simulation | |
4- Digital Awareness Deliverables | |
5- Cybersecurity Events | |
6- Risk & Security Assessment Services | |
7- Interactive Awareness Sessions | |
- Get Results in 3 Simple Steps | |
From setup to securing your organization, our AI guides you every step of the way. | |
1- Assess Your Risk | |
Our AI analyzes your current security posture and identifies vulnerabilities | |
2-Deploy Smart Training | |
Launch AI-powered campaigns with personalized learning paths for each employee | |
3- Monitor & Improve | |
Track progress with real-time analytics and continuous improvement recommendations | |
- Why Organizations Choose our Ai-Platform ? | |
Be part of the growing number of businesses transforming their cybersecurity with our cutting-edge AI platform. | |
1- 90% reduction in phishing susceptibility | |
(Measurable Results) Track real improvements in security awareness with detailed analytics and reporting. | |
2- < 24 hours setup time | |
(Easy Integration) Seamlessly integrates with your existing security stack and HR systems. | |
3- 99.9% customer satisfaction | |
Expert Support | |
Our cybersecurity experts are always available to help you maximize your results. | |
- Guarding Your Digital Future | |
CSWORD is a leading cybersecurity company dedicated to transforming organizational security culture through innovative AI-powered solutions and expert services. | |
1- AI-Powered Phishing Simulations (Backed by consistent positive outcomes) | |
Advanced AI creates realistic, targeted phishing campaigns to test your team's awareness. | |
2- Intelligent LMS Training with AI Adaptation (Personalized Learning) | |
Personalized cybersecurity training modules adapted to each employee's role and risk level. | |
3- Penetration Testing & Threat Simulation (Real-time Analytics) | |
Comprehensive testing for web, mobile, and networks, including Red & Purple teaming exercises. | |
4- Digital Awareness Deliverables (Branded Content) | |
5-Cybersecurity Events (Interactive Learning) | |
7-Interactive Awareness Sessions (Expert-Led Training) | |
8- Advanced Executive Reporting (Real-time Analytics) | |
AI-driven risk scoring and comprehensive analytics for informed decision-making. | |
9-24/7 AI Cybersecurity Consultant (Always Available) | |
Intelligent chatbot providing instant cybersecurity guidance and support. | |
9- Penetration Testing & Threat Simulation | |
- Solutions | |
1- AI-Powered Awareness | |
2- Digital Awareness Deliverables | |
3- Interactive Awareness Sessions | |
4- Cybersecurity Events | |
5- Penetration Testing & Threat Simulation | |
5- Risk & Security Assessment | |
Discover how artificial intelligence transforms cybersecurity awareness training, delivering personalized, adaptive, and highly effective security education. | |
1- AI-Driven | |
2- Enterprise-Grade | |
3- Scalable | |
about Csword | |
- Our Story | |
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. | |
At Csword, where heritage meets cybersecurity, we forge CyberSwords — powerful shields against the invisible enemies of the digital world. | |
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. | |
-Our Vision | |
Redefining cybersecurity by merging AI innovation with human insight to protect and empower organizations around the world. | |
- Our Mission | |
Empowering organizations to thrive securely with AI-led cybersecurity solutions that are proactive, dependable, and future-ready. | |
- Our Core Values | |
These fundamental principles guide everything we do and shape our relationships with clients, partners, and each other. | |
1- Security First | |
From code to cloud, your data is protected by military-grade security and strict privacy standards. | |
2-Innovation Driven | |
We innovate relentlessly—using AI and research to transform how cybersecurity is taught and learned. | |
3- People Centered | |
Real security starts with people. We build smarter habits through engaging, human-centered learning. | |
4-Excellence Committed | |
We're committed to delivering exceptional results and continuous improvement in all our services and solutions. | |
- Leading the Future of Cyber Awareness | |
We're more than a cybersecurity company—we're your strategic partner in building a security-conscious culture that protects and empowers your organization. | |
1-Proven Expertise | |
Our team combines decades of cybersecurity experience with cutting-edge AI technology to deliver unparalleled results. | |
2-Innovation Leadership | |
We're pioneers in AI-powered cybersecurity awareness, continuously developing new technologies to stay ahead of threats. | |
3-Measurable Results | |
Our clients see dramatic improvements in security awareness metrics, with some achieving 90% reduction in phishing susceptibility. | |
4-Complete Solutions | |
From AI-powered platforms to expert services, we provide everything you need for comprehensive cybersecurity awareness. | |
5-Scalable Platform | |
Our solutions grow with your organization, from small businesses to enterprise corporations with thousands of employees. | |
6-Dedicated Support | |
Our customer success team ensures you get maximum value from our platform with ongoing support and optimization. | |
What's Next? | |
1- We Receive Your Message | |
Our team is notified instantly when you submit your inquiry | |
2- We Analyze Your Needs | |
Our specialists review your request and prepare a response | |
3- We Respond Promptly | |
You'll hear from us within 24 hours with next steps | |
- Services | |
1- Digital Awareness Deliverables | |
2- Interactive Awareness Sessions | |
3- Cybersecurity Events | |
4- Penetration Testing & Threat Simulation | |
5- Risk & Security Assessment | |
1- AI-Powered Phishing Simulations | |
Advanced security testing tools powered by artificial intelligence | |
* Key Features | |
1- Realistic email templates | |
2- Customizable attack scenarios | |
3- Behavioral analysis | |
4- Automated deployment | |
* Benefits | |
1- Improved security awareness | |
2- Reduced vulnerability | |
3- Compliance with regulations | |
4- Measurable security metrics | |
2- Intelligent LMS Training with AI Adaptation | |
Personalized learning management system that adapts training content to individual employee needs and learning patterns. | |
* Key Features | |
1- Personalized, role-based content with adaptive difficulty | |
2- Seamless LMS integration and multi-language support | |
3- AI-optimized learning paths with performance-based recommendations | |
* Benefits | |
1- Increase training completion rates by 75% | |
2- Reduce training time while improving retention | |
3- Personalized learning experiences drive engagement | |
3- Executive Reporting with AI Risk Scoring | |
Comprehensive analytics platform that provides actionable insights through AI-powered risk assessment and predictive modeling. | |
* Key Features | |
1- Risk scores and trends for individuals & departments | |
2- AI-driven predictive modeling and recommendations | |
3- Automated executive summaries with custom KPIs | |
* Benefits | |
1- Data-driven decision making for security investments | |
2- Proactive risk management instead of reactive responses | |
3- Clear ROI demonstration for security training programs | |
4- 24/7 AI Cybersecurity Consultant | |
Intelligent chatbot providing instant cybersecurity guidance, support, and training assistance around the clock. | |
* Key Features | |
1- Instant AI chatbot support for users, admins & employees | |
2- NLP guidance integrated with cybersecurity knowledge base | |
3- Smart escalation to human experts when needed | |
* Benefits | |
1- Reduce support ticket volume by 60% | |
2- Instant answers improve user satisfaction | |
3- 24/7 availability enhances security culture | |
- Digital Awareness Deliverables (Branded Content) | |
Custom-designed digital content to reinforce cybersecurity awareness across your organization. | |
1- Digital Awareness Deliverables | |
* Security Awareness Poster | |
• Eye-catching visual design | |
• Your company branding | |
• Clear security messaging | |
• Multiple format delivery | |
* Monthly Newsletter | |
• Latest threat intelligence | |
• Security tips and best practices | |
• Company-specific content | |
• Email-ready format | |
-Cybersecurity Events (Interactive Learning) | |
Engaging events that build security culture and team engagement through interactive learning. | |
Real-Time Attacker Simulation -Engage in several intense, realistic scenarios to test your response capabilities under pressure. | |
Gamified Cyber Awareness to Empower Your Team - Turn learning into a fun, competitive experience with points, leaderboards, and engaging challenges. | |
6-Risk & Security Assessment Services (Always Available) | |
- Our Process | |
Event planning and logistics coordination | |
Expert facilitator and speaker arrangement | |
Custom event materials and resources | |
Post-event follow-up and assessment | |
- Key Benefits: | |
Creates memorable learning experiences | |
Builds team cohesion around security goals | |
Generates excitement about cybersecurity | |
In-depth assessments covering risk, device configurations, network architecture, and source code review. | |
-Interactive Awareness Sessions (Expert-Led Training) : | |
Interactive, expert-led training sessions delivered in-person or online to educate your workforce. | |
Interactive, in-person cybersecurity training sessions designed to engage and educate your workforce. | |
Experience Interactive Cybersecurity Training Our on-site sessions bring real-world cybersecurity scenarios directly to your team, creating engaging learning experiences that stick. | |
* Online Training Sessions "Leadership briefings on security strategy" | |
* On-Site Training Sessions "Hands-on learning with real scenarios" | |
- Our Process | |
1- Pre-session consultation and needs assessment | |
2- Custom content development | |
3- Online delivery by certified experts | |
4- Follow-up materials and action plans | |
- Key Benefits: | |
1- Face-to-face interaction increases engagement and retention | |
2- Customized content addresses your specific challenges | |
3- Expert facilitators provide real-world insights | |
- Cybersecurity Events | |
Comprehensive cybersecurity events that build security culture and team engagement through interactive learning. | |
Engaging Cybersecurity Events Real events that create lasting impact on your security culture | |
Real-Time Attacker Simulation : Engage in several intense, realistic scenarios to test your response capabilities under pressure. | |
Gamified Cyber Awareness to Empower Your Team : Turn learning into a fun, competitive experience with points, leaderboards, and engaging challenges. | |
- Our Process | |
Event planning and logistics coordination | |
Expert facilitator and speaker arrangement | |
Custom event materials and resources | |
Post-event follow-up and assessment | |
- Key Benefits: | |
Creates memorable learning experiences | |
Builds team cohesion around security goals | |
Generates excitement about cybersecurity | |
- Penetration Testing & Threat Simulation | |
Proactively identify and mitigate vulnerabilities with our expert-led penetration testing and attack simulation services. | |
Our Pen Testing Services :Comprehensive assessments to uncover critical security flaws. | |
Web & Mobile App Pen Testing :Identify and exploit vulnerabilities in your web and mobile applications before attackers do. | |
Internal & External Network Pen Testing : Assess the security of your network infrastructure from both internal and external perspectives. | |
Wireless Pen Testing : Evaluate the security of your wireless networks to prevent unauthorized access. | |
Red Teaming / Purple Teaming : Simulate real-world attack scenarios to test your organization's detection and response capabilities. | |
- Our Methodology | |
A structured approach to ensure thorough testing and actionable results. | |
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. | |
2- Reconnaissance & Discovery : Our experts gather intelligence and use advanced tools to identify potential attack vectors and map out your digital footprint. | |
3- Vulnerability Assessment : In a controlled manner, we attempt to exploit identified vulnerabilities to validate real-world risks and demonstrate potential impact. | |
4- Reporting & Remediation : We provide a comprehensive report with actionable recommendations, prioritized by risk, to help you effectively remediate all findings. | |
- Risk & Security Assessment Services | |
Gain a comprehensive understanding of your security posture and make informed, risk-based decisions. | |
- Our Assessment Services | |
1- Risk Assessment : Identify, analyze, and evaluate security risks to your organization's assets and processes. | |
2- Device Configuration Assessment : Ensure your servers, firewalls, and endpoints are hardened and securely configured. | |
3- Network Architecture Assessment : Assess the design of your network for security flaws, bottlenecks, and single points of failure. | |
4- Source Code Review : Manually and automatically inspect source code to find security vulnerabilities missed by other tools. | |
- Our Process | |
Information Gathering : We collect documentation and interview key personnel to understand your business processes, assets, and existing security controls. | |
Vulnerability Analysis : Our team uses a combination of automated tools and manual inspection to identify vulnerabilities and misconfigurations. | |
Risk Evaluation : We analyze vulnerabilities to determine their likelihood and potential impact, resulting in a prioritized list of risks. | |
Strategic Recommendations : We deliver a detailed report with actionable recommendations to mitigate risks and build a resilient security roadmap. | |
""" | |
SYSTEM_PROMPT_GENERAL = "You are a cybersecurity expert. Answer clearly and informatively." | |
CONTEXT = load_context() | |
# 3. Form state | |
form_type = None | |
user_form_data = {} | |
# final_question = ("final_note", "Would you like any further assistance with cybersecurity-related topics?") | |
service_options = [ | |
"AI Phishing Simulation Platform", | |
"AI-Tailored LMS Training", | |
"Cybersecurity Events", | |
"Digital Awareness Deliverables", | |
"Executive Reporting & Risk Scoring", | |
"On-Site Awareness Sessions", | |
"Penetration Testing & Threat Simulation", | |
"Risk & Security Assessment", | |
"24/7 AI Cybersecurity Consultant" | |
] | |
service_options_ar = [ | |
"منصة محاكاة التصيد الاحتيالي بالذكاء الاصطناعي", | |
"تدريب مخصص عبر نظام إدارة التعلم باستخدام الذكاء الاصطناعي", | |
"فعاليات توعية بالأمن السيبراني", | |
"محتوى توعوي رقمي", | |
"تقارير تنفيذية وتقييم المخاطر", | |
"جلسات توعية ميدانية", | |
"اختبارات اختراق ومحاكاة للتهديدات", | |
"تقييم المخاطر والأمن السيبراني", | |
"مستشار أمن سيبراني يعمل بالذكاء الاصطناعي 24/7" | |
] | |
def get_service_options(lang="en"): | |
return service_options_ar if lang == "ar" else service_options | |
form_definitions = { | |
"demo": [ | |
("name", "Full Name *"), | |
("company", "Company Name *"), | |
("email", "Work Email *"), | |
("phone", "Phone Number"), | |
("employees", ["Number of Employees *", ["1-50", "51-200", "201-500", "+500"]]), | |
("services", ["Services of Interest (select multiple):", "checkboxes", service_options]), | |
("specific_reqs", "Do you have any specific requirements or questions?"), | |
# final_question | |
], | |
"contact": [ | |
("name", "Full Name *"), | |
("email", "Email Address *"), | |
("company", "Company"), | |
("subject", "Subject *"), | |
("message", "Message *"), | |
# final_question | |
] | |
} | |
form_definitions_ar = { | |
"demo": [ | |
("name", "الاسم الكامل *"), | |
("company", "اسم الشركة *"), | |
("email", "البريد الإلكتروني الخاص بالعمل *"), | |
("phone", "رقم الهاتف"), | |
("employees", ["عدد الموظفين *", ["1-50", "51-200", "201-500", "+500"]]), | |
("services", ["الخدمات التي تهمك (يمكن اختيار أكثر من خدمة):", "checkboxes", service_options]), | |
("specific_reqs", "هل لديك أي متطلبات أو أسئلة محددة؟"), | |
# final_question | |
], | |
"contact": [ | |
("name", "الاسم الكامل *"), | |
("email", "البريد الإلكتروني *"), | |
("company", "اسم الشركة"), | |
("subject", "الموضوع *"), | |
("message", "الرسالة *"), | |
# final_question | |
] | |
} | |
def get_form_definition(form_type, lang="en"): | |
if lang == "ar": | |
return form_definitions_ar.get(form_type, []) | |
return form_definitions.get(form_type, []) | |
# 4. Validation | |
def validate_input(key, value): | |
if not value or (isinstance(value, str) and not value.strip()): | |
return "This field is required. Please provide a value." | |
if key == "email" and not re.match(r"[^@\s]+@[^@\s]+\.[^@\s]+", value): | |
return "Invalid email format. Please enter a valid email address." | |
if key == "phone" and re.search(r"[a-zA-Z]", value): | |
return "Invalid phone number. Only digits and symbols are allowed." | |
return None | |
# 5. Chat handler | |
def answer_question(query: str, is_general=False) -> str: | |
prompt = SYSTEM_PROMPT_GENERAL if is_general else f"{SYSTEM_PROMPT_CSWORD}\nContext:\n{CONTEXT}" | |
messages = [ | |
{"role": "system", "content": prompt}, | |
{"role": "user", "content": query}, | |
] | |
try: | |
response = openai.chat.completions.create( | |
model=model_name, | |
messages=messages, | |
reasoning_effort="none" | |
) | |
return response.choices[0].message.content | |
except Exception as e: | |
return f"Error: {e}" | |
# 6. Chat function | |
def chat_fn(message, history, checkbox_values=None): | |
global user_form_data, form_type | |
language = "ar" if re.search(r"[\u0600-\u06FF]", message) else "en" | |
if form_type and len(user_form_data) < len(form_definitions[form_type]): | |
# Allow user to cancel form at any step | |
cancel_keywords = ["cancel", "stop", "don't want", "exit", "no thanks", "back", "abort"] | |
cancel_keywords_Ar =["إلغاء", "وقف", "مافيش داعي", "مش عايز", "لا شكراً", "رجوع", "ارجع", "انهاء", "خروج", "كفاية", "مش مهم", "سيبك", "خلص"] | |
if any(kw in message.lower() for kw in cancel_keywords): | |
user_form_data, form_type = {}, None | |
return history + [(message, "Form cancelled. How can I assist you with cybersecurity?")], "", gr.update(visible=True), gr.update(visible=False, choices=[], value=None), gr.update(visible=False, value=[]), gr.update(visible=False) | |
key, question = form_definitions[form_type][len(user_form_data)] | |
if isinstance(question, list): | |
if question[1] == "checkboxes": | |
# This is a checkbox question - handle checkbox values | |
if checkbox_values is None or len(checkbox_values) == 0: | |
return history + [(message, "Please select at least one service option.")], "", gr.update(visible=False), gr.update(visible=False, choices=[], value=None), gr.update(visible=True, value=[]), gr.update(visible=True) | |
user_form_data[key] = checkbox_values | |
history = history + [(message, f"Selected services: {', '.join(checkbox_values)}")] | |
else: | |
# This is a dropdown question | |
dropdown_options = question[1] | |
if message not in dropdown_options: | |
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), gr.update(visible=False, value=[]), gr.update(visible=False) | |
user_form_data[key] = message | |
history = history + [(message, f"Selected: {message}")] | |
else: | |
# This is a text question | |
error = validate_input(key, message) | |
if error: | |
return history + [(message, error)], "", gr.update(visible=True), gr.update(visible=False, choices=[], value=None), gr.update(visible=False, value=[]), gr.update(visible=False) | |
user_form_data[key] = message | |
history = history + [(message, "Thank you!")] | |
# Check if we have more questions | |
if len(user_form_data) < len(form_definitions[form_type]): | |
next_key, next_question = form_definitions[form_type][len(user_form_data)] | |
if isinstance(next_question, list): | |
if next_question[1] == "checkboxes": | |
# Next question is checkboxes - hide text input and dropdown, show checkboxes | |
return history + [("", next_question[0])], "", gr.update(visible=False), gr.update(visible=False, choices=[], value=None), gr.update(visible=True, value=[]), gr.update(visible=True) | |
else: | |
# Next question is dropdown - hide text input and checkboxes, show dropdown | |
dropdown_options = next_question[1] | |
return history + [("", next_question[0])], "", gr.update(visible=False), gr.update(visible=True, choices=dropdown_options, value=None), gr.update(visible=False, value=[]), gr.update(visible=False) | |
else: | |
# Next question is text - show text input, hide dropdown and checkboxes | |
return history + [("", next_question)], "", gr.update(visible=True), gr.update(visible=False, choices=[], value=None), gr.update(visible=False, value=[]), gr.update(visible=False) | |
else: | |
# Form complete | |
user_form_data["timestamp"] = datetime.now().isoformat() | |
user_form_data["type"] = form_type.capitalize() | |
# Check if form is done, but not yet confirmed | |
if form_type and user_form_data and len(user_form_data) == len(form_definitions[form_type]): | |
if "confirmation_pending" not in user_form_data: | |
user_form_data["confirmation_pending"] = True | |
summary_lines = [f"{k}: {', '.join(v) if isinstance(v, list) else v}" for k, v in user_form_data.items() if k not in ["confirmation_pending"]] | |
summary = "\n".join(summary_lines) | |
return ( | |
history + [("", f"Here’s a summary of your data:\n{summary}"), ("", "Would you like to submit this data now? (yes/no)")], | |
"", gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False) | |
) | |
# Handle user response to confirmation | |
if re.search(r"\b(no|cancel|stop|exit|abort|لا|إلغاء|مش عايز|خلص|مافيش داعي|كفاية|انهاء)\b", message.strip().lower()): | |
user_form_data["timestamp"] = datetime.now().isoformat() | |
user_form_data["type"] = form_type.capitalize() | |
# Convert list values to strings for CSV | |
csv_data = user_form_data.copy() | |
csv_data.pop("confirmation_pending", None) | |
for k, v in csv_data.items(): | |
if isinstance(v, list): | |
csv_data[k] = "; ".join(v) | |
file_name = f"{form_type}_requests.csv" | |
file_exists = os.path.isfile(file_name) | |
try: | |
with open(file_name, mode="a", newline="", encoding="utf-8") as file: | |
writer = csv.DictWriter(file, fieldnames=list(csv_data.keys())) | |
if not file_exists: | |
writer.writeheader() | |
writer.writerow(csv_data) | |
msg1 = f"✅ Thank you! Your {form_type} request has been received and saved." | |
except Exception as e: | |
msg1 = f"⚠️ Your request was received but could not be saved to file. Error: {e}" | |
user_form_data, form_type = {}, None | |
return history + [("", msg1)], "", gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False) | |
elif re.search(r"\b(no|cancel|exit|stop|لا|إلغاء|انهاء|خروج|مش عايز|مافيش داعي|كفاية|سيبك)\b", message.strip().lower()): | |
user_form_data, form_type = {}, None | |
return history + [("", "No problem. The form has been discarded. How else can I help you?")], "", gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False) | |
else: | |
return history + [(message, "Please respond with 'yes' or 'no' to confirm submission.")], "", gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False) | |
# Admin commands | |
if message.lower().startswith("admin:") and "guide" in message.lower(): | |
steps = ( | |
"To work with the CSWORD.ai platform:\n" | |
"1. Login to the admin dashboard.\n" | |
"2. Upload user list for training enrollment.\n" | |
"3. Configure phishing simulation campaigns.\n" | |
"4. Schedule awareness sessions.\n" | |
"5. Monitor progress via the Executive Risk Dashboard." | |
) | |
return history + [(message, steps)], "", gr.update(visible=True), gr.update(visible=False, choices=[]), gr.update(visible=False, value=[]), gr.update(visible=False) | |
# Form triggers | |
if re.search(r"\b(demo|quote|custom|Product|Service|Showcase|Request)\b", message, re.IGNORECASE) or re.search(r"\b(عرض توضيحي|تجربة منتج|أرغب في عرض|استعراض|خدمة|طلب)\b", message) : | |
form_type = "demo" | |
user_form_data = {} | |
form_questions = get_form_definition(form_type, language) | |
first_question = get_form_definition(form_type, language)[0][1] | |
return history + [(message, "بالتأكيد! لنبدأ ببعض المعلومات:" if language == "ar" else "Sure! Let's start with a few details."), ("", first_question)], "", gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False) | |
if ( | |
re.search(r"\b(contact|message|speak|talk|get in touch|reach out|support)\b", message, re.IGNORECASE) | |
or re.search(r"(تواصل|اتصال|أرسل\s+رسالة|أرغب\s+بالتواصل|أحتاج\s+للتواصل|أريد\s+التحدث|تكلمني|أتحدث|الدعم|الدعم\s+الفني|ارسل\s+استفسار)", message)): | |
form_type = "contact" | |
user_form_data = {} | |
form_questions = get_form_definition(form_type, language) | |
first_question = get_form_definition(form_type, language)[0][1] | |
welcome_msg = "بالطبع! يرجى تعبئة البيانات التالية:" if language == "ar" else "Of course! Please fill out the following." | |
return history + [(message, welcome_msg), ("", first_question)], "", gr.update(visible=True), gr.update(visible=False, choices=[]), gr.update(visible=False, value=[]), gr.update(visible=False) | |
# Generic help | |
if re.search(r"\bhelp\b", message, re.IGNORECASE): | |
return history + [(message, "Yes, of course! Tell me your question.")], "", gr.update(visible=True), gr.update(visible=False, choices=[]), gr.update(visible=False, value=[]), gr.update(visible=False) | |
# Cybersecurity questions | |
if re.search(r"\b(cybersecurity|malware|phishing|ransomware|network|threat|attack|industry|NIST|ISO|compliance)\b", message, re.IGNORECASE): | |
reply = answer_question(message, is_general=True) | |
return history + [(message, reply)], "", gr.update(visible=True), gr.update(visible=False, choices=[]), gr.update(visible=False, value=[]), gr.update(visible=False) | |
# Default response for everything else | |
reply = answer_question(message) | |
return history + [(message, reply)], "", gr.update(visible=True), gr.update(visible=False, choices=[], value=None), gr.update(visible=False, value=[]), gr.update(visible=False) | |
# 7. Launch Gradio | |
with gr.Blocks(title="CSWORD.ai Chatbot") as demo: | |
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.") | |
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?"]]) | |
with gr.Row(): | |
user_input = gr.Textbox(show_label=False, placeholder="Enter your question here...", scale=4) | |
dropdown_input = gr.Dropdown( | |
choices=[], | |
label="Please select an option", | |
visible=False, | |
scale=2, | |
interactive=True | |
) | |
# Add checkboxes for services | |
services_checkboxes = gr.CheckboxGroup( | |
choices=service_options, | |
label="Select Services of Interest", | |
visible=False, | |
value=[] | |
) | |
# Add send button for checkboxes | |
send_services_btn = gr.Button("Send Selected Services", visible=False) | |
submit = gr.Button("Send") | |
def get_query(txt, drop, hist, checkbox_vals): | |
# If dropdown is visible and has a value, use dropdown value | |
if dropdown_input.visible and drop: | |
return chat_fn(drop, hist) | |
# Otherwise use text input | |
elif txt.strip(): | |
return chat_fn(txt, hist) | |
else: | |
return hist, "", gr.update(), gr.update(), gr.update(), gr.update() | |
def handle_dropdown_selection(drop, hist): | |
if drop: | |
return chat_fn(drop, hist) | |
else: | |
return hist, "", gr.update(), gr.update(), gr.update(), gr.update() | |
def handle_services_submission(checkbox_vals, hist): | |
return chat_fn("services_selected", hist, checkbox_vals) | |
submit.click(get_query, inputs=[user_input, dropdown_input, chatbot, services_checkboxes], outputs=[chatbot, user_input, user_input, dropdown_input, services_checkboxes, send_services_btn]) | |
user_input.submit(get_query, inputs=[user_input, dropdown_input, chatbot, services_checkboxes], outputs=[chatbot, user_input, user_input, dropdown_input, services_checkboxes, send_services_btn]) | |
# Handle dropdown selection | |
dropdown_input.select(handle_dropdown_selection, inputs=[dropdown_input, chatbot], outputs=[chatbot, user_input, user_input, dropdown_input, services_checkboxes, send_services_btn]) | |
# Handle services submission | |
send_services_btn.click(handle_services_submission, inputs=[services_checkboxes, chatbot], outputs=[chatbot, user_input, user_input, dropdown_input, services_checkboxes, send_services_btn]) | |
if __name__ == "__main__": | |
demo.launch() |