Spaces:
Running
Running
# csword_ai_chatbot.py (Fixed Version with Dropdowns + Validation + Admin + General Q&A) | |
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 | |
# load_context() alternative using a saved HTML file | |
def load_context(): | |
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)) | |
# 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 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. | |
- content website: https://csword.ai | |
csword 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 | |
- 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- 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." | |
# Try to load context, fallback if file doesn't exist | |
try: | |
CONTEXT = load_context() | |
except FileNotFoundError: | |
CONTEXT = "CSWORD.ai is a cybersecurity awareness and training platform that leverages AI to deliver personalized, adaptive education." | |
if not CONTEXT.strip(): | |
CONTEXT = "CSWORD.ai is a cybersecurity awareness and training platform that leverages AI to deliver personalized, adaptive education." | |
# 3. Form state | |
form_type = None | |
user_form_data = {} | |
final_question = ("final_note", "Would you like any further assistance with cybersecurity-related topics?") | |
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 if needed):\n" | |
"- AI Phishing Simulation Platform\n" | |
"- AI-Tailored LMS Training\n" | |
"- Cybersecurity Events\n" | |
"- Digital Awareness Deliverables\n" | |
"- Executive Reporting & Risk Scoring\n" | |
"- On-Site Awareness Sessions\n" | |
"- Penetration Testing & Threat Simulation\n" | |
"- Risk & Security Assessment\n" | |
"- 24/7 AI Cybersecurity Consultant"), | |
("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 | |
] | |
} | |
# 4. Validation | |
def validate_input(key, value): | |
if 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): | |
global user_form_data, form_type | |
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"] | |
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) | |
key, question = form_definitions[form_type][len(user_form_data)] | |
if isinstance(question, list): | |
# 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) | |
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) | |
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): | |
# Next question is a dropdown - hide text input, 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) | |
else: | |
# Next question is text - show text input, hide dropdown | |
return history + [("", next_question)], "", gr.update(visible=True), gr.update(visible=False, choices=[], value=None) | |
else: | |
# Form complete | |
user_form_data["timestamp"] = datetime.now().isoformat() | |
user_form_data["type"] = form_type.capitalize() | |
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(user_form_data.keys())) | |
if not file_exists: | |
writer.writeheader() | |
writer.writerow(user_form_data) | |
msg1 = f"Thank you! Your {form_type} request has been received and saved." | |
msg2 = final_question[1] | |
user_form_data, form_type = {}, None | |
return history + [("", msg1), ("", msg2)], "", gr.update(visible=True), gr.update(visible=False, choices=[], value=None) | |
except Exception as e: | |
msg1 = f"Thank you! Your {form_type} request has been received (Note: Could not save to file: {e})." | |
msg2 = final_question[1] | |
user_form_data, form_type = {}, None | |
return history + [("", msg1), ("", msg2)], "", gr.update(visible=True), gr.update(visible=False, choices=[], value=None) | |
# 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=[]) | |
# Form triggers | |
if re.search(r"\b(demo|quote|custom)\b", message, re.IGNORECASE): | |
form_type = "demo" | |
user_form_data = {} | |
first_question = form_definitions[form_type][0][1] | |
return history + [(message, "Sure! Let's start with a few details."), ("", first_question)], "", gr.update(visible=True), gr.update(visible=False, choices=[]) | |
if re.search(r"\b(contact|message|speak)\b", message, re.IGNORECASE): | |
form_type = "contact" | |
user_form_data = {} | |
first_question = form_definitions[form_type][0][1] | |
return history + [(message, "Of course! Please fill out the following."), ("", first_question)], "", gr.update(visible=True), gr.update(visible=False, choices=[]) | |
# 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=[]) | |
# 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=[]) | |
# Default response for everything else | |
reply = answer_question(message) | |
return history + [(message, reply)], "", gr.update(visible=True), gr.update(visible=False, choices=[], value=None) | |
# 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 | |
) | |
submit = gr.Button("Send") | |
def get_query(txt, drop, hist): | |
# 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() | |
def handle_dropdown_selection(drop, hist): | |
# Handle dropdown selection directly | |
if drop: | |
return chat_fn(drop, hist) | |
else: | |
return hist, "", gr.update(), gr.update() | |
submit.click(get_query, inputs=[user_input, dropdown_input, chatbot], outputs=[chatbot, user_input, user_input, dropdown_input]) | |
user_input.submit(get_query, inputs=[user_input, dropdown_input, chatbot], outputs=[chatbot, user_input, user_input, dropdown_input]) | |
# Handle dropdown selection - automatically process when user selects an option | |
dropdown_input.select(handle_dropdown_selection, inputs=[dropdown_input, chatbot], outputs=[chatbot, user_input, user_input, dropdown_input]) | |
if __name__ == "__main__": | |
demo.launch() |