afouda's picture
Update app.py
5f0f965 verified
import os
import csv
import re
from datetime import datetime
import gradio as gr
from google import genai
from google.genai import types
# =================== Gemini Setup ===================
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "AIzaSyDZBYJJdwogN70NtdpL01YAL8hJl0FYcqs")
client = genai.Client(api_key=GEMINI_API_KEY)
GEMINI_MODEL = "gemini-2.5-flash"
SYSTEM_PROMPT_CSWORD = """
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. 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.Always aim to give short summaries.
Always use the Arabic name "سي سورد" whenever you refer to the brand Csword in Arabic text.
Always use the English name "Csword" whenever you refer to the brand Csword in English text.
-If the question is not related to cybersecurity, politely respond:
“I’m trained to help only with cybersecurity-related topics. Please ask something related to digital security, awareness, or our services.”
This includes technical coding questionscsword Next-Gen AI Platform for Cyber Awareness
- 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
- Our Mission
Empowering organizations to thrive securely with AI-led cybersecurity solutions that are proactive, dependable, and future-ready.
- Our Vision
Redefining cybersecurity by merging AI innovation with human insight to protect and empower organizations around the world.
- 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 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.
- 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.
-Platform Features & Services
i) AI-Powered Phishing Simulations (Backed by consistent positive outcomes)
Advanced AI creates realistic, targeted phishing campaigns to test your team's awareness.
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
ii) Intelligent LMS Training with AI Adaptation (Personalized Learning)
Personalized cybersecurity training modules adapted to each employee's role and risk level.
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
iii) Penetration Testing & Threat Simulation (Real-time Analytics)
Comprehensive testing for web, mobile, and networks, including Red & Purple teaming exercises.
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.
iv) Risk & Security Assessment Services (Always Available)
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.
- 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.
v) Digital Awareness Deliverables (Branded Content)
Custom-designed digital content to reinforce cybersecurity awareness across your organization.
* 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
VI) Interactive Awareness Sessions
Expert-led, hands-on sessions delivered online or in person
Types of Sessions:
• Online Leadership Briefings
• On-Site Hands-on Training
Process:
1. Pre-session consultation
2. Custom content creation
3. Live delivery by experts
4. Follow-up materials
Benefits:
• Higher engagement
• Real-world scenario practice
• Tailored content for your team
VII) 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.
-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
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
VIII) 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
IX) 24/7 AI Cybersecurity Consultant (Always Available)
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
*How It Works: Get Results in 3 Simple Steps
- 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
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.
*Solutions at a Glance
• AI-Powered Awareness
• Digital Awareness Deliverables
• Interactive Awareness Sessions
• Cybersecurity Events
• Penetration Testing & Threat Simulation
• Risk & Security Assessment
* What Happens 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
*Guarding Your Digital Future
Csword is not just a platform—it's your strategic partner in cybersecurity awareness.
From AI-powered training to deep risk analysis, we deliver the tools and insights to protect your people, data, and reputation.
"""
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?"),
("submitted", "Thank you! Your demo request has been submitted. Can I help you with anything else?")
],
"contact": [
("name", "Full Name:"),
("email", "Email Address:"),
("company", "Company:"),
("subject", "Subject:"),
("message", "Message:"),
("submitted", "Thank you! Your message has been submitted. Can I help you with anything else?"),
]
}
form_definitions_ar = {
"demo": [
("name", "الاسم الكامل:"),
("company", "اسم الشركة:"),
("email", "البريد الإلكتروني الخاص بالعمل:"),
("phone", "رقم الهاتف:"),
("employees", ["عدد الموظفين:", ["1-50", "51-200", "201-500", "+500"]]),
("services", ["الخدمات التي تهمك (يمكن اختيار أكثر من خدمة):", "checkboxes", service_options_ar]),
("specific_reqs", "هل لديك أي متطلبات أو أسئلة محددة؟"),
("submitted", " شكرًا لك! تم استلام طلب العرض التوضيحي. هل يمكنني مساعدتك في شيء آخر؟"),
],
"contact": [
("name", "الاسم الكامل:"),
("email", "البريد الإلكتروني:"),
("company", "اسم الشركة:"),
("subject", "الموضوع:"),
("message", "الرسالة:"),
("submitted", " شكرًا لك! تم إرسال رسالتك بنجاح. هل يمكنني مساعدتك في شيء آخر؟"),
]
}
def get_form_definition(form_type, lang="en"):
if lang == "ar":
return form_definitions_ar.get(form_type, [])
return form_definitions.get(form_type, [])
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
def wrap_text_direction(text, lang="en"):
if lang == "ar":
return f'<div dir="rtl" style="text-align:right">{text}</div>'
return text
def answer_question(query: str, is_general=False) -> str:
prompt = SYSTEM_PROMPT_CSWORD + "\n" + query
contents = [
types.Content(role="user", parts=[types.Part.from_text(text=prompt)]),
]
config = types.GenerateContentConfig(response_mime_type="text/plain")
try:
response = ""
for chunk in client.models.generate_content_stream(
model=GEMINI_MODEL,
contents=contents,
config=config,
):
response += chunk.text
return response.strip()
except Exception as e:
return f"Error: {e}"
form_type = None
user_form_data = {}
form_language = "en"
def chat_fn(message, history, checkbox_values=None):
global user_form_data, form_type, form_language
# Start of form: set language ONCE for the form session
if (
re.search(r"\b(demo|quote|custom|Product demo|Service|Showcase|Request)\b", message, re.IGNORECASE) or
re.search(r"\b(عرض توضيحي|تجربة منتج|أرغب في عرض|استعراض|خدمة|طلب)\b", message)
):
form_language = "ar" if re.search(r"[\u0600-\u06FF]", message) else "en"
form_type = "demo"
user_form_data = {}
form_questions = get_form_definition(form_type, form_language)
first_question = form_questions[0][1]
return history + [(message,
"شكرًا لاهتمامك بطلب عرض توضيحي (Demo) من سي سورد! يسعدنا أن نعرض لك كيف يمكن لمنصتنا أن تدعم احتياجاتك وتساعدك في تحقيق أهدافك. لضمان تقديم تجربة عرض مخصصة ومناسبة لك، نرجو منك تزويدنا بالمعلومات التالية:" if form_language == "ar"
else "Sure! Thank you for your interest in scheduling a demo with Csword! We’re excited to show you how our platform can support your needs and goals. To help us tailor the demo experience for you, please provide the following information:"
), ("", 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|consultation)\b", message, re.IGNORECASE) or
re.search(r"(تواصل|اتصال|أرسل\s+رسالة|أرغب\s+بالتواصل|أحتاج\s+للتواصل|أريد\s+التحدث|تكلمني|أتحدث|الدعم|الدعم\s+الفني|ارسل\s+استفسار|الاستشارة)", message)
):
form_language = "ar" if re.search(r"[\u0600-\u06FF]", message) else "en"
form_type = "contact"
user_form_data = {}
form_questions = get_form_definition(form_type, form_language)
first_question = form_questions[0][1]
welcome_msg = (
"شكرًا لتواصلك معنا! يُرجى تعبئة البيانات التالية حتى نتمكن من مساعدتك بأفضل شكل ممكن:" if form_language == "ar"
else "Of course! Thank you for reaching out! Please fill out the following information so we can assist you better:"
)
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)
# Form handling
if form_type and len(user_form_data) < len(get_form_definition(form_type, form_language)):
key, question = get_form_definition(form_type, form_language)[len(user_form_data)]
if isinstance(question, list):
if question[1] == "checkboxes":
if checkbox_values is None or len(checkbox_values) == 0:
return history + [(message, "Please select at least one service option." if form_language == "en" else "يرجى اختيار خدمة واحدة على الأقل.")], "", 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:
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:
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, "")]
if len(user_form_data) < len(get_form_definition(form_type, form_language)):
next_key, next_question = get_form_definition(form_type, form_language)[len(user_form_data)]
if isinstance(next_question, list):
if next_question[1] == "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:
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:
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 IS FILLED, WAIT FOR CONFIRMATION
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 != "confirmation_pending"]
summary = "\n".join(summary_lines)
confirm_msg = ("Here’s a summary of your data:\n" + summary +
"\nWould you like to submit this data now? (yes/no)") \
if form_language == "en" \
else ("ملخص البيانات:\n" + summary + "\nهل ترغب في إرسال البيانات الآن؟ (نعم/لا)")
return (history + [("", confirm_msg)],
"", gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False))
# Waiting for "yes"/"no"
if user_form_data.get("confirmation_pending"):
if re.search(r"^(no|cancel|stop|exit|abort|لا|إلغاء|مش عايز|خلص|مافيش داعي|كفاية|انهاء)$", message.strip().lower()):
user_form_data, form_type = {}, None
msg = "No problem. The form has been discarded. How else can I help you?" if form_language == "en" else "تم إلغاء النموذج. كيف يمكنني مساعدتك في شيء آخر؟"
return history + [("", msg)], "", gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
elif re.search(r"^(yes|submit|send|نعم|ارسل|أرسل|ارسال|إرسال)$", message.strip().lower()):
user_form_data["timestamp"] = datetime.now().isoformat()
user_form_data["type"] = form_type.capitalize()
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. Can I help you with anything else?" \
if form_language == "en" else "✅ تم استلام طلبك وحفظه بنجاح. هل يمكنني مساعدتك في شيء آخر؟"
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)
else:
msg = "Please respond with 'yes' or 'no'." if form_language == "en" else "يرجى الرد بـ (نعم) أو (لا)."
return history + [(message, msg)], "", gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
# Help and other chatbot logic
if re.search(r"\bhelp\b", message, re.IGNORECASE):
help_message = (
"Sure! I can help you with the following:\n"
"- 📌 Explain CSWORD services\n"
"- 📅 Schedule a product demo\n"
"- 🤝 Connect you with the CSWORD team\n\n"
"Just let me know what you’d like to do!"
)
return history + [(message, help_message)], "", gr.update(visible=True), gr.update(visible=False, choices=[]), gr.update(visible=False, value=[]), gr.update(visible=False)
if re.search(r"(مساعدة|مساعده|مساعدة؟|أحتاج مساعدة)", message):
help_message_ar = (
"بالطبع! يمكنني مساعدتك في الأمور التالية:\n"
"- 📌 شرح خدمات CSWORD\n"
"- 📅 تحديد موعد لعرض توضيحي\n"
"- 🤝 التواصل مع فريق CSWORD\n\n"
"فقط أخبرني بما تريد القيام به!"
)
return history + [(message, wrap_text_direction(help_message_ar, "ar"))], "", 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
language = "ar" if re.search(r"[\u0600-\u06FF]", message) else "en"
reply = answer_question(message)
reply_wrapped = wrap_text_direction(reply, language)
return history + [(message, reply_wrapped)], "", gr.update(visible=True), gr.update(visible=False, choices=[], value=None), gr.update(visible=False, value=[]), gr.update(visible=False)
# ================= Gradio Interface ================
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
)
services_checkboxes = gr.CheckboxGroup(
choices=service_options,
label="Select Services of Interest",
visible=False,
value=[]
)
send_services_btn = gr.Button("Send Selected Services", visible=False)
submit = gr.Button("Send")
def get_query(txt, drop, hist, checkbox_vals):
if dropdown_input.visible and drop:
return chat_fn(drop, hist)
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])
dropdown_input.select(handle_dropdown_selection, inputs=[dropdown_input, chatbot], outputs=[chatbot, user_input, user_input, dropdown_input, services_checkboxes, send_services_btn])
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()