AYI-NEDJIMI's picture
Upload app.py with huggingface_hub
a1bf777 verified
Raw History Blame Contribute Delete
55.5 kB
import gradio as gr
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime
import json
import io
from typing import Dict, List, Tuple
from huggingface_hub import InferenceClient
# ============================================================================
# Configuration
# ============================================================================
import os
# Get HF token from environment variable (set in Space secrets)
HF_TOKEN = os.getenv("HF_TOKEN", "")
# Initialize Inference Client for AI guidance
try:
if HF_TOKEN:
client = InferenceClient(token=HF_TOKEN)
else:
client = None
print("Warning: HF_TOKEN not set. AI guidance features will be limited.")
except:
client = None
# ============================================================================
# Data: RGPD/GDPR Compliance
# ============================================================================
RGPD_REQUIREMENTS = [
{"id": "GDPR-1", "requirement": "Lawful basis for processing personal data documented", "category": "Legal Basis", "severity": "Critical", "article": "Art. 6"},
{"id": "GDPR-2", "requirement": "Consent mechanisms implemented when required", "category": "Legal Basis", "severity": "Critical", "article": "Art. 7"},
{"id": "GDPR-3", "requirement": "Privacy Policy published and accessible", "category": "Transparency", "severity": "High", "article": "Art. 13-14"},
{"id": "GDPR-4", "requirement": "Data Processing Agreements (DPA) with processors", "category": "Legal Basis", "severity": "Critical", "article": "Art. 28"},
{"id": "GDPR-5", "requirement": "Data minimization principle applied", "category": "Data Protection", "severity": "High", "article": "Art. 5(1)(c)"},
{"id": "GDPR-6", "requirement": "Purpose limitation documented", "category": "Data Protection", "severity": "High", "article": "Art. 5(1)(b)"},
{"id": "GDPR-7", "requirement": "Storage limitation policy enforced", "category": "Data Protection", "severity": "High", "article": "Art. 5(1)(e)"},
{"id": "GDPR-8", "requirement": "Encryption of personal data at rest and in transit", "category": "Security", "severity": "Critical", "article": "Art. 32"},
{"id": "GDPR-9", "requirement": "Right to access procedures implemented", "category": "Data Subject Rights", "severity": "High", "article": "Art. 15"},
{"id": "GDPR-10", "requirement": "Right to erasure (right to be forgotten) documented", "category": "Data Subject Rights", "severity": "High", "article": "Art. 17"},
{"id": "GDPR-11", "requirement": "Data portability procedures", "category": "Data Subject Rights", "severity": "Medium", "article": "Art. 20"},
{"id": "GDPR-12", "requirement": "Right to object procedures", "category": "Data Subject Rights", "severity": "High", "article": "Art. 21"},
{"id": "GDPR-13", "requirement": "Data Protection Officer (DPO) appointed if required", "category": "Governance", "severity": "Critical", "article": "Art. 37"},
{"id": "GDPR-14", "requirement": "Data Protection Impact Assessment (DPIA) for high-risk processing", "category": "Risk Management", "severity": "Critical", "article": "Art. 35"},
{"id": "GDPR-15", "requirement": "Breach notification procedures (72 hours to authority)", "category": "Incident Response", "severity": "Critical", "article": "Art. 33"},
{"id": "GDPR-16", "requirement": "Records of processing activities (ROPA) maintained", "category": "Documentation", "severity": "High", "article": "Art. 30"},
{"id": "GDPR-17", "requirement": "Standard Contractual Clauses (SCCs) for international transfers", "category": "Data Transfers", "severity": "Critical", "article": "Art. 46"},
{"id": "GDPR-18", "requirement": "Privacy by Design and by Default implemented", "category": "Technical Measures", "severity": "High", "article": "Art. 25"},
{"id": "GDPR-19", "requirement": "Data subject notification for breaches affecting rights", "category": "Incident Response", "severity": "Critical", "article": "Art. 34"},
{"id": "GDPR-20", "requirement": "Regular data protection training for staff", "category": "Awareness", "severity": "High", "article": "Art. 32"},
]
# ============================================================================
# Data: ISO 27001 Controls (Annex A)
# ============================================================================
ISO27001_CONTROLS = [
# Organizational Controls (A.5)
{"id": "A.5.1", "control": "Policies for information security", "theme": "Organizational", "clause": "5", "priority": "Critical"},
{"id": "A.5.2", "control": "Information security roles and responsibilities", "theme": "Organizational", "clause": "5", "priority": "Critical"},
{"id": "A.5.3", "control": "Segregation of duties", "theme": "Organizational", "clause": "5", "priority": "High"},
{"id": "A.5.4", "control": "Management responsibilities", "theme": "Organizational", "clause": "5", "priority": "High"},
{"id": "A.5.5", "control": "Contact with authorities", "theme": "Organizational", "clause": "5", "priority": "Medium"},
{"id": "A.5.6", "control": "Contact with special interest groups", "theme": "Organizational", "clause": "5", "priority": "Medium"},
{"id": "A.5.7", "control": "Threat intelligence", "theme": "Organizational", "clause": "5", "priority": "High"},
# People Controls (A.6)
{"id": "A.6.1", "control": "Screening", "theme": "People", "clause": "6", "priority": "High"},
{"id": "A.6.2", "control": "Terms and conditions of employment", "theme": "People", "clause": "6", "priority": "High"},
{"id": "A.6.3", "control": "Information security awareness, education and training", "theme": "People", "clause": "6", "priority": "Critical"},
{"id": "A.6.4", "control": "Disciplinary process", "theme": "People", "clause": "6", "priority": "Medium"},
{"id": "A.6.5", "control": "Responsibilities after termination or change of employment", "theme": "People", "clause": "6", "priority": "High"},
{"id": "A.6.6", "control": "Confidentiality or non-disclosure agreements", "theme": "People", "clause": "6", "priority": "High"},
{"id": "A.6.7", "control": "Remote working", "theme": "People", "clause": "6", "priority": "High"},
{"id": "A.6.8", "control": "Information security event reporting", "theme": "People", "clause": "6", "priority": "Critical"},
# Physical Controls (A.7)
{"id": "A.7.1", "control": "Physical security perimeters", "theme": "Physical", "clause": "7", "priority": "High"},
{"id": "A.7.2", "control": "Physical entry", "theme": "Physical", "clause": "7", "priority": "High"},
{"id": "A.7.3", "control": "Securing offices, rooms and facilities", "theme": "Physical", "clause": "7", "priority": "Medium"},
{"id": "A.7.4", "control": "Physical security monitoring", "theme": "Physical", "clause": "7", "priority": "Medium"},
{"id": "A.7.5", "control": "Protecting against physical and environmental threats", "theme": "Physical", "clause": "7", "priority": "High"},
{"id": "A.7.6", "control": "Working in secure areas", "theme": "Physical", "clause": "7", "priority": "Medium"},
{"id": "A.7.7", "control": "Clear desk and clear screen", "theme": "Physical", "clause": "7", "priority": "Medium"},
{"id": "A.7.8", "control": "Equipment siting and protection", "theme": "Physical", "clause": "7", "priority": "Medium"},
{"id": "A.7.9", "control": "Security of assets off-premises", "theme": "Physical", "clause": "7", "priority": "High"},
{"id": "A.7.10", "control": "Storage media", "theme": "Physical", "clause": "7", "priority": "High"},
{"id": "A.7.11", "control": "Supporting utilities", "theme": "Physical", "clause": "7", "priority": "High"},
{"id": "A.7.12", "control": "Cabling security", "theme": "Physical", "clause": "7", "priority": "Medium"},
{"id": "A.7.13", "control": "Equipment maintenance", "theme": "Physical", "clause": "7", "priority": "Medium"},
{"id": "A.7.14", "control": "Secure disposal or re-use of equipment", "theme": "Physical", "clause": "7", "priority": "High"},
# Technological Controls (A.8)
{"id": "A.8.1", "control": "User endpoint devices", "theme": "Technological", "clause": "8", "priority": "High"},
{"id": "A.8.2", "control": "Privileged access rights", "theme": "Technological", "clause": "8", "priority": "Critical"},
{"id": "A.8.3", "control": "Information access restriction", "theme": "Technological", "clause": "8", "priority": "Critical"},
{"id": "A.8.4", "control": "Access to source code", "theme": "Technological", "clause": "8", "priority": "High"},
{"id": "A.8.5", "control": "Secure authentication", "theme": "Technological", "clause": "8", "priority": "Critical"},
{"id": "A.8.6", "control": "Capacity management", "theme": "Technological", "clause": "8", "priority": "Medium"},
{"id": "A.8.7", "control": "Protection against malware", "theme": "Technological", "clause": "8", "priority": "Critical"},
{"id": "A.8.8", "control": "Management of technical vulnerabilities", "theme": "Technological", "clause": "8", "priority": "Critical"},
{"id": "A.8.9", "control": "Configuration management", "theme": "Technological", "clause": "8", "priority": "High"},
{"id": "A.8.10", "control": "Information deletion", "theme": "Technological", "clause": "8", "priority": "High"},
{"id": "A.8.11", "control": "Data masking", "theme": "Technological", "clause": "8", "priority": "Medium"},
{"id": "A.8.12", "control": "Data leakage prevention", "theme": "Technological", "clause": "8", "priority": "High"},
{"id": "A.8.13", "control": "Information backup", "theme": "Technological", "clause": "8", "priority": "Critical"},
{"id": "A.8.14", "control": "Redundancy of information processing facilities", "theme": "Technological", "clause": "8", "priority": "High"},
{"id": "A.8.15", "control": "Logging", "theme": "Technological", "clause": "8", "priority": "Critical"},
{"id": "A.8.16", "control": "Monitoring activities", "theme": "Technological", "clause": "8", "priority": "Critical"},
{"id": "A.8.17", "control": "Clock synchronization", "theme": "Technological", "clause": "8", "priority": "Medium"},
{"id": "A.8.18", "control": "Use of privileged utility programs", "theme": "Technological", "clause": "8", "priority": "High"},
{"id": "A.8.19", "control": "Installation of software on operational systems", "theme": "Technological", "clause": "8", "priority": "High"},
{"id": "A.8.20", "control": "Networks security", "theme": "Technological", "clause": "8", "priority": "Critical"},
{"id": "A.8.21", "control": "Security of network services", "theme": "Technological", "clause": "8", "priority": "High"},
{"id": "A.8.22", "control": "Segregation of networks", "theme": "Technological", "clause": "8", "priority": "High"},
{"id": "A.8.23", "control": "Web filtering", "theme": "Technological", "clause": "8", "priority": "Medium"},
{"id": "A.8.24", "control": "Use of cryptography", "theme": "Technological", "clause": "8", "priority": "Critical"},
{"id": "A.8.25", "control": "Secure development life cycle", "theme": "Technological", "clause": "8", "priority": "High"},
{"id": "A.8.26", "control": "Application security requirements", "theme": "Technological", "clause": "8", "priority": "High"},
{"id": "A.8.27", "control": "Secure system architecture and engineering principles", "theme": "Technological", "clause": "8", "priority": "High"},
{"id": "A.8.28", "control": "Secure coding", "theme": "Technological", "clause": "8", "priority": "High"},
{"id": "A.8.29", "control": "Security testing in development and acceptance", "theme": "Technological", "clause": "8", "priority": "High"},
{"id": "A.8.30", "control": "Outsourced development", "theme": "Technological", "clause": "8", "priority": "High"},
{"id": "A.8.31", "control": "Separation of development, test and production environments", "theme": "Technological", "clause": "8", "priority": "High"},
{"id": "A.8.32", "control": "Change management", "theme": "Technological", "clause": "8", "priority": "Critical"},
{"id": "A.8.33", "control": "Test information", "theme": "Technological", "clause": "8", "priority": "Medium"},
{"id": "A.8.34", "control": "Protection of information systems during audit testing", "theme": "Technological", "clause": "8", "priority": "Medium"},
]
# ISO 27001 Clauses
ISO27001_CLAUSES = [
{"clause": "4", "title": "Context of the Organization", "requirements": ["Understanding organization and context", "Understanding needs of interested parties", "Determining scope of ISMS", "Information security management system"]},
{"clause": "5", "title": "Leadership", "requirements": ["Leadership and commitment", "Information security policy", "Organizational roles, responsibilities and authorities"]},
{"clause": "6", "title": "Planning", "requirements": ["Actions to address risks and opportunities", "Information security objectives and planning to achieve them"]},
{"clause": "7", "title": "Support", "requirements": ["Resources", "Competence", "Awareness", "Communication", "Documented information"]},
{"clause": "8", "title": "Operation", "requirements": ["Operational planning and control", "Information security risk assessment", "Information security risk treatment"]},
{"clause": "9", "title": "Performance Evaluation", "requirements": ["Monitoring, measurement, analysis and evaluation", "Internal audit", "Management review"]},
{"clause": "10", "title": "Improvement", "requirements": ["Nonconformity and corrective action", "Continual improvement"]},
]
# ============================================================================
# Data: NIS2 Directive
# ============================================================================
NIS2_REQUIREMENTS = [
{"id": "NIS2-1", "requirement": "Cybersecurity governance structure established", "category": "Governance", "severity": "Critical"},
{"id": "NIS2-2", "requirement": "CISO or equivalent role appointed", "category": "Governance", "severity": "Critical"},
{"id": "NIS2-3", "requirement": "Board-level oversight of cybersecurity", "category": "Governance", "severity": "Critical"},
{"id": "NIS2-4", "requirement": "Risk management framework implemented", "category": "Risk Management", "severity": "Critical"},
{"id": "NIS2-5", "requirement": "Annual cybersecurity risk assessment", "category": "Risk Management", "severity": "Critical"},
{"id": "NIS2-6", "requirement": "Supply chain risk assessment", "category": "Risk Management", "severity": "High"},
{"id": "NIS2-7", "requirement": "Third-party security requirements defined", "category": "Supply Chain", "severity": "High"},
{"id": "NIS2-8", "requirement": "Incident response plan documented and tested", "category": "Incident Response", "severity": "Critical"},
{"id": "NIS2-9", "requirement": "24-hour incident notification to CSIRT/authority", "category": "Incident Response", "severity": "Critical"},
{"id": "NIS2-10", "requirement": "72-hour detailed incident report", "category": "Incident Response", "severity": "Critical"},
{"id": "NIS2-11", "requirement": "Business continuity plans tested annually", "category": "Resilience", "severity": "Critical"},
{"id": "NIS2-12", "requirement": "Disaster recovery procedures documented", "category": "Resilience", "severity": "High"},
{"id": "NIS2-13", "requirement": "Multi-factor authentication implemented", "category": "Technical Measures", "severity": "Critical"},
{"id": "NIS2-14", "requirement": "Network segmentation implemented", "category": "Technical Measures", "severity": "High"},
{"id": "NIS2-15", "requirement": "Encryption for data at rest and in transit", "category": "Technical Measures", "severity": "Critical"},
{"id": "NIS2-16", "requirement": "Vulnerability management program", "category": "Technical Measures", "severity": "High"},
{"id": "NIS2-17", "requirement": "Security awareness training program", "category": "Awareness", "severity": "High"},
{"id": "NIS2-18", "requirement": "Phishing simulation exercises", "category": "Awareness", "severity": "Medium"},
{"id": "NIS2-19", "requirement": "Asset inventory maintained", "category": "Asset Management", "severity": "High"},
{"id": "NIS2-20", "requirement": "Logging and monitoring of security events", "category": "Monitoring", "severity": "Critical"},
]
NIS2_SECTORS = {
"Essential Entities": ["Energy", "Transport", "Banking", "Financial Market Infrastructure", "Health", "Drinking Water", "Wastewater", "Digital Infrastructure", "ICT Service Management", "Public Administration", "Space"],
"Important Entities": ["Postal Services", "Waste Management", "Chemicals", "Food", "Manufacturing", "Digital Providers", "Research"]
}
# ============================================================================
# Helper Functions
# ============================================================================
def calculate_compliance_score(requirements: List[Dict], checked_items: List[str]) -> Tuple[float, Dict]:
"""Calculate compliance score based on checked items."""
if not requirements:
return 0.0, {}
severity_weights = {"Critical": 4, "High": 3, "Medium": 2, "Low": 1}
total_weight = sum(severity_weights.get(req.get("severity", "Medium"), 2) for req in requirements)
compliant_weight = 0
category_stats = {}
for req in requirements:
req_id = req.get("id", "")
category = req.get("category", "Other")
severity = req.get("severity", "Medium")
weight = severity_weights.get(severity, 2)
if category not in category_stats:
category_stats[category] = {"total": 0, "compliant": 0, "weight_total": 0, "weight_compliant": 0}
category_stats[category]["total"] += 1
category_stats[category]["weight_total"] += weight
if req_id in checked_items:
compliant_weight += weight
category_stats[category]["compliant"] += 1
category_stats[category]["weight_compliant"] += weight
score = (compliant_weight / total_weight * 100) if total_weight > 0 else 0
return score, category_stats
def get_ai_guidance(prompt: str, max_tokens: int = 500) -> str:
"""Get AI guidance from Hugging Face models."""
if not client:
return "AI guidance temporarily unavailable."
try:
# Use a general model for compliance guidance
response = client.text_generation(
prompt,
model="mistralai/Mistral-7B-Instruct-v0.2",
max_new_tokens=max_tokens,
temperature=0.7,
)
return response
except Exception as e:
return f"AI guidance error: {str(e)}"
def create_gap_analysis(requirements: List[Dict], checked_items: List[str]) -> str:
"""Generate gap analysis report."""
gaps = []
critical_gaps = []
for req in requirements:
req_id = req.get("id", "")
if req_id not in checked_items:
gap_info = f"**{req_id}**: {req.get('requirement', 'N/A')} (Severity: {req.get('severity', 'Medium')})"
if req.get("category"):
gap_info += f" - Category: {req['category']}"
gaps.append(gap_info)
if req.get("severity") == "Critical":
critical_gaps.append(gap_info)
report = "## Gap Analysis\n\n"
if critical_gaps:
report += f"### Critical Gaps ({len(critical_gaps)})\n\n"
for gap in critical_gaps:
report += f"- {gap}\n"
report += "\n"
if gaps:
report += f"### All Gaps ({len(gaps)})\n\n"
for gap in gaps:
report += f"- {gap}\n"
else:
report += "No gaps identified. Full compliance achieved!\n"
return report
def create_action_plan(requirements: List[Dict], checked_items: List[str]) -> str:
"""Generate prioritized action plan."""
gaps = []
for req in requirements:
req_id = req.get("id", "")
if req_id not in checked_items:
gaps.append(req)
# Sort by severity (Critical > High > Medium > Low)
severity_order = {"Critical": 0, "High": 1, "Medium": 2, "Low": 3}
gaps.sort(key=lambda x: severity_order.get(x.get("severity", "Medium"), 2))
report = "## Action Plan\n\n"
report += "Prioritized by severity (Critical items first):\n\n"
for i, req in enumerate(gaps, 1):
report += f"### {i}. {req.get('id', 'N/A')}\n"
report += f"**Requirement**: {req.get('requirement', 'N/A')}\n\n"
report += f"**Severity**: {req.get('severity', 'Medium')}\n\n"
if req.get("category"):
report += f"**Category**: {req['category']}\n\n"
# Add implementation guidance
report += "**Action Steps**:\n"
report += "1. Assess current state and document gaps\n"
report += "2. Define implementation approach and timeline\n"
report += "3. Allocate resources and assign responsibilities\n"
report += "4. Implement controls and document evidence\n"
report += "5. Test and validate implementation\n"
report += "6. Update policies and procedures\n\n"
report += "---\n\n"
if not gaps:
report += "No action items. All requirements are compliant!\n"
return report
def create_risk_assessment(requirements: List[Dict], checked_items: List[str]) -> str:
"""Generate risk assessment based on gaps."""
gaps = []
for req in requirements:
req_id = req.get("id", "")
if req_id not in checked_items:
gaps.append(req)
critical_count = sum(1 for g in gaps if g.get("severity") == "Critical")
high_count = sum(1 for g in gaps if g.get("severity") == "High")
medium_count = sum(1 for g in gaps if g.get("severity") == "Medium")
report = "## Risk Assessment\n\n"
# Overall risk level
if critical_count > 0:
report += "**Overall Risk Level**: CRITICAL\n\n"
report += f"There are {critical_count} critical compliance gaps that require immediate attention.\n\n"
elif high_count > 3:
report += "**Overall Risk Level**: HIGH\n\n"
report += f"There are {high_count} high-severity gaps that should be addressed promptly.\n\n"
elif high_count > 0 or medium_count > 5:
report += "**Overall Risk Level**: MEDIUM\n\n"
report += "Several compliance gaps exist that require planned remediation.\n\n"
else:
report += "**Overall Risk Level**: LOW\n\n"
report += "Compliance posture is strong with minor gaps.\n\n"
report += "### Risk Summary\n\n"
report += f"- **Critical Gaps**: {critical_count}\n"
report += f"- **High Severity Gaps**: {high_count}\n"
report += f"- **Medium Severity Gaps**: {medium_count}\n\n"
report += "### Key Risks\n\n"
for gap in gaps[:5]: # Top 5 risks
if gap.get("severity") in ["Critical", "High"]:
report += f"- **{gap.get('id')}**: {gap.get('requirement')} (Severity: {gap.get('severity')})\n"
report += f" - Impact: Non-compliance may result in regulatory penalties, security breaches, or operational disruption\n"
report += f" - Likelihood: Medium to High\n\n"
return report
def create_gauge_chart(score: float, title: str = "Compliance Score") -> go.Figure:
"""Create a gauge chart for compliance score."""
fig = go.Figure(go.Indicator(
mode="gauge+number+delta",
value=score,
domain={"x": [0, 1], "y": [0, 1]},
title={"text": title},
delta={"reference": 80},
gauge={
"axis": {"range": [0, 100]},
"bar": {"color": "darkblue"},
"steps": [
{"range": [0, 25], "color": "#ff4444"},
{"range": [25, 50], "color": "#ffaa44"},
{"range": [50, 75], "color": "#ffff44"},
{"range": [75, 100], "color": "#44ff44"}
],
"threshold": {
"line": {"color": "red", "width": 4},
"thickness": 0.75,
"value": 80
}
}
))
fig.update_layout(height=350, paper_bgcolor="#1e1e1e", font={"color": "#ffffff"})
return fig
def create_category_chart(category_stats: Dict, title: str = "Compliance by Category") -> go.Figure:
"""Create category breakdown chart."""
if not category_stats:
return go.Figure()
categories = list(category_stats.keys())
scores = [(stats["weight_compliant"] / stats["weight_total"] * 100) if stats["weight_total"] > 0 else 0
for stats in category_stats.values()]
fig = go.Figure(data=[
go.Bar(x=categories, y=scores, marker_color='#3498db')
])
fig.update_layout(
title=title,
xaxis_title="Category",
yaxis_title="Compliance Score (%)",
height=400,
paper_bgcolor="#1e1e1e",
plot_bgcolor="#2d2d2d",
font={"color": "#ffffff"},
yaxis={"range": [0, 100]}
)
return fig
def generate_soa(selected_controls: List[str]) -> str:
"""Generate Statement of Applicability (SoA) for ISO 27001."""
soa = "# Statement of Applicability (SoA)\n\n"
soa += f"**Date**: {datetime.now().strftime('%Y-%m-%d')}\n\n"
soa += "## ISO/IEC 27001:2022 Annex A Controls\n\n"
for control in ISO27001_CONTROLS:
control_id = control["id"]
status = "Applicable - Implemented" if control_id in selected_controls else "Not Applicable / Not Implemented"
soa += f"### {control_id}: {control['control']}\n"
soa += f"- **Theme**: {control['theme']}\n"
soa += f"- **Priority**: {control['priority']}\n"
soa += f"- **Status**: {status}\n"
soa += f"- **Justification**: {'Control is implemented and operational.' if control_id in selected_controls else 'Control not yet implemented or not applicable to current scope.'}\n\n"
return soa
def generate_compliance_report(framework: str, checked_items: List[str], score: float,
category_stats: Dict, gap_analysis: str, action_plan: str,
risk_assessment: str) -> str:
"""Generate comprehensive compliance report."""
report = f"# Compliance Assessment Report: {framework}\n\n"
report += f"**Generated**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
report += f"**Overall Compliance Score**: {score:.1f}%\n\n"
report += "## Executive Summary\n\n"
if score >= 80:
report += f"The organization demonstrates strong compliance with {framework} requirements, achieving {score:.1f}% compliance.\n\n"
elif score >= 60:
report += f"The organization shows moderate compliance with {framework} requirements at {score:.1f}%. Several gaps require attention.\n\n"
elif score >= 40:
report += f"The organization has significant compliance gaps with {framework}, currently at {score:.1f}%. Immediate action is required.\n\n"
else:
report += f"The organization has critical compliance gaps with {framework} at {score:.1f}%. Urgent remediation is necessary.\n\n"
report += "## Compliance by Category\n\n"
for category, stats in category_stats.items():
cat_score = (stats["weight_compliant"] / stats["weight_total"] * 100) if stats["weight_total"] > 0 else 0
report += f"- **{category}**: {cat_score:.1f}% ({stats['compliant']}/{stats['total']} requirements)\n"
report += "\n"
report += gap_analysis + "\n"
report += risk_assessment + "\n"
report += action_plan + "\n"
report += "---\n\n"
report += "*Generated by Compliance Assistant - AYI-NEDJIMI Consultants*\n"
return report
# ============================================================================
# Gradio Interface
# ============================================================================
def create_interface():
"""Create the main Gradio interface."""
# Custom dark theme
theme = gr.themes.Soft(
primary_hue="blue",
secondary_hue="indigo",
neutral_hue="slate",
).set(
body_background_fill="#0f0f0f",
body_background_fill_dark="#0f0f0f",
block_background_fill="#1e1e1e",
block_background_fill_dark="#1e1e1e",
input_background_fill="#2d2d2d",
input_background_fill_dark="#2d2d2d",
)
with gr.Blocks(theme=theme, title="Compliance Assistant", css="""
.compliance-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 30px;
border-radius: 10px;
color: white;
text-align: center;
margin-bottom: 20px;
}
.stat-box {
background: #2d2d2d;
padding: 20px;
border-radius: 8px;
border-left: 4px solid #3498db;
}
""") as demo:
gr.HTML("""
<div class="compliance-header">
<h1>πŸ›‘οΈ Compliance Assistant</h1>
<p>Multi-Framework Compliance Management: RGPD/GDPR β€’ ISO 27001 β€’ NIS2</p>
<p style="font-size: 14px; margin-top: 10px;">Step-by-step wizard for comprehensive compliance assessment</p>
</div>
""")
with gr.Tabs() as tabs:
# ===================================================================
# Tab 1: RGPD/GDPR Compliance
# ===================================================================
with gr.Tab("πŸ“‹ RGPD/GDPR Compliance"):
gr.Markdown("## RGPD/GDPR Compliance Assessment")
gr.Markdown("Assess your compliance with the General Data Protection Regulation")
with gr.Row():
with gr.Column(scale=2):
gr.Markdown("### Requirements Checklist")
rgpd_checklist = gr.CheckboxGroup(
choices=[f"{req['id']}: {req['requirement']}" for req in RGPD_REQUIREMENTS],
label="Check all implemented requirements",
value=[]
)
with gr.Column(scale=1):
gr.Markdown("### Compliance Score")
rgpd_score_display = gr.Markdown("**Score**: 0%")
rgpd_gauge = gr.Plot(label="RGPD Compliance")
with gr.Row():
rgpd_category_chart = gr.Plot(label="Compliance by Category")
with gr.Tabs():
with gr.Tab("Gap Analysis"):
rgpd_gap_btn = gr.Button("Generate Gap Analysis", variant="primary")
rgpd_gap_output = gr.Markdown()
with gr.Tab("Risk Assessment"):
rgpd_risk_btn = gr.Button("Generate Risk Assessment", variant="primary")
rgpd_risk_output = gr.Markdown()
with gr.Tab("Action Plan"):
rgpd_action_btn = gr.Button("Generate Action Plan", variant="primary")
rgpd_action_output = gr.Markdown()
with gr.Tab("AI Guidance"):
rgpd_ai_question = gr.Textbox(
label="Ask a question about RGPD/GDPR compliance",
placeholder="e.g., How do I implement a DPIA process?"
)
rgpd_ai_btn = gr.Button("Get AI Guidance", variant="secondary")
rgpd_ai_output = gr.Markdown()
# Event handlers for RGPD tab
def update_rgpd_score(checked):
checked_ids = [item.split(":")[0] for item in checked]
score, category_stats = calculate_compliance_score(RGPD_REQUIREMENTS, checked_ids)
score_text = f"**Score**: {score:.1f}%"
gauge = create_gauge_chart(score, "RGPD/GDPR Compliance")
cat_chart = create_category_chart(category_stats, "RGPD Compliance by Category")
return score_text, gauge, cat_chart
rgpd_checklist.change(
update_rgpd_score,
inputs=[rgpd_checklist],
outputs=[rgpd_score_display, rgpd_gauge, rgpd_category_chart]
)
def generate_rgpd_gap(checked):
checked_ids = [item.split(":")[0] for item in checked]
return create_gap_analysis(RGPD_REQUIREMENTS, checked_ids)
rgpd_gap_btn.click(
generate_rgpd_gap,
inputs=[rgpd_checklist],
outputs=[rgpd_gap_output]
)
def generate_rgpd_risk(checked):
checked_ids = [item.split(":")[0] for item in checked]
return create_risk_assessment(RGPD_REQUIREMENTS, checked_ids)
rgpd_risk_btn.click(
generate_rgpd_risk,
inputs=[rgpd_checklist],
outputs=[rgpd_risk_output]
)
def generate_rgpd_action(checked):
checked_ids = [item.split(":")[0] for item in checked]
return create_action_plan(RGPD_REQUIREMENTS, checked_ids)
rgpd_action_btn.click(
generate_rgpd_action,
inputs=[rgpd_checklist],
outputs=[rgpd_action_output]
)
def get_rgpd_ai_guidance(question):
prompt = f"As a GDPR compliance expert, answer this question: {question}\n\nProvide practical, actionable guidance for organizations."
return get_ai_guidance(prompt)
rgpd_ai_btn.click(
get_rgpd_ai_guidance,
inputs=[rgpd_ai_question],
outputs=[rgpd_ai_output]
)
# ===================================================================
# Tab 2: ISO 27001 Compliance
# ===================================================================
with gr.Tab("πŸ”’ ISO 27001 Compliance"):
gr.Markdown("## ISO 27001:2022 Compliance Assessment")
gr.Markdown("Assess your Information Security Management System")
with gr.Tabs():
with gr.Tab("Clauses 4-10"):
gr.Markdown("### ISO 27001 Clauses Checklist")
iso_clause_checks = {}
for clause in ISO27001_CLAUSES:
with gr.Accordion(f"Clause {clause['clause']}: {clause['title']}", open=False):
iso_clause_checks[clause['clause']] = gr.CheckboxGroup(
choices=clause['requirements'],
label=f"Requirements for Clause {clause['clause']}",
value=[]
)
with gr.Tab("Annex A Controls (93 controls)"):
gr.Markdown("### Annex A Controls Selector")
with gr.Row():
iso_theme_filter = gr.Dropdown(
choices=["All", "Organizational", "People", "Physical", "Technological"],
value="All",
label="Filter by Theme"
)
iso_controls_checklist = gr.CheckboxGroup(
choices=[f"{ctrl['id']}: {ctrl['control']}" for ctrl in ISO27001_CONTROLS],
label="Select applicable controls",
value=[]
)
def filter_controls(theme):
if theme == "All":
return gr.update(choices=[f"{ctrl['id']}: {ctrl['control']}" for ctrl in ISO27001_CONTROLS])
else:
filtered = [f"{ctrl['id']}: {ctrl['control']}" for ctrl in ISO27001_CONTROLS if ctrl['theme'] == theme]
return gr.update(choices=filtered)
iso_theme_filter.change(
filter_controls,
inputs=[iso_theme_filter],
outputs=[iso_controls_checklist]
)
with gr.Tab("Statement of Applicability (SoA)"):
gr.Markdown("### Generate SoA")
iso_soa_btn = gr.Button("Generate Statement of Applicability", variant="primary")
iso_soa_output = gr.Markdown()
def generate_iso_soa(checked):
checked_ids = [item.split(":")[0] for item in checked]
return generate_soa(checked_ids)
iso_soa_btn.click(
generate_iso_soa,
inputs=[iso_controls_checklist],
outputs=[iso_soa_output]
)
with gr.Tab("Risk Register"):
gr.Markdown("### ISO 27001 Risk Register Template")
iso_risk_template = gr.Markdown("""
## Risk Register Template
| Risk ID | Asset | Threat | Vulnerability | Likelihood | Impact | Risk Level | Treatment | Owner | Status |
|---------|-------|--------|---------------|------------|--------|------------|-----------|-------|--------|
| R-001 | [Asset name] | [Threat description] | [Vulnerability] | [L/M/H] | [L/M/H] | [L/M/H/C] | [Accept/Mitigate/Transfer/Avoid] | [Name] | [Open/Closed] |
| R-002 | | | | | | | | | |
| R-003 | | | | | | | | | |
### Risk Assessment Criteria
**Likelihood:**
- Low (L): Unlikely to occur (< 10%)
- Medium (M): May occur (10-50%)
- High (H): Likely to occur (> 50%)
**Impact:**
- Low (L): Minor impact on operations
- Medium (M): Moderate impact, some disruption
- High (H): Significant impact, major disruption
- Critical (C): Catastrophic impact
**Risk Level:** Likelihood Γ— Impact
- Low: Acceptable risk, monitor
- Medium: Risk reduction measures recommended
- High: Risk reduction measures required
- Critical: Immediate action required
### Next Steps
1. Identify and document all information assets
2. Assess threats and vulnerabilities for each asset
3. Determine likelihood and impact
4. Calculate risk level
5. Select risk treatment option
6. Implement risk treatment plans
7. Monitor and review risks regularly
""")
with gr.Row():
with gr.Column():
gr.Markdown("### ISO 27001 Compliance Score")
iso_score_display = gr.Markdown("**Score**: 0%")
iso_gauge = gr.Plot(label="ISO 27001 Compliance")
with gr.Column():
iso_category_chart = gr.Plot(label="Controls by Theme")
# Event handlers for ISO tab
def update_iso_score(checked):
checked_ids = [item.split(":")[0] for item in checked]
# Create a simplified requirements list for scoring
iso_reqs = [{"id": ctrl["id"], "severity": ctrl["priority"], "category": ctrl["theme"]} for ctrl in ISO27001_CONTROLS]
score, category_stats = calculate_compliance_score(iso_reqs, checked_ids)
score_text = f"**Score**: {score:.1f}%"
gauge = create_gauge_chart(score, "ISO 27001 Compliance")
cat_chart = create_category_chart(category_stats, "ISO 27001 Controls by Theme")
return score_text, gauge, cat_chart
iso_controls_checklist.change(
update_iso_score,
inputs=[iso_controls_checklist],
outputs=[iso_score_display, iso_gauge, iso_category_chart]
)
# ===================================================================
# Tab 3: NIS2 Directive
# ===================================================================
with gr.Tab("🌐 NIS2 Directive"):
gr.Markdown("## NIS2 Directive Compliance Assessment")
gr.Markdown("EU Directive on Network and Information Security")
with gr.Tabs():
with gr.Tab("Applicability Checker"):
gr.Markdown("### Check if NIS2 applies to your organization")
nis2_sector = gr.Dropdown(
choices=["Energy", "Transport", "Banking", "Financial Market Infrastructure", "Health",
"Drinking Water", "Wastewater", "Digital Infrastructure", "ICT Service Management",
"Public Administration", "Space", "Postal Services", "Waste Management",
"Chemicals", "Food", "Manufacturing", "Digital Providers", "Research"],
label="Select your sector"
)
nis2_size = gr.Radio(
choices=["< 50 employees", "50-249 employees (Medium)", "β‰₯ 250 employees (Large)"],
label="Organization size",
value="50-249 employees (Medium)"
)
nis2_check_btn = gr.Button("Check Applicability", variant="primary")
nis2_applicability = gr.Markdown()
def check_nis2_applicability(sector, size):
if not sector:
return "Please select a sector"
result = "## NIS2 Applicability Assessment\n\n"
is_essential = sector in NIS2_SECTORS["Essential Entities"]
is_important = sector in NIS2_SECTORS["Important Entities"]
if is_essential:
result += f"**Classification**: Essential Entity\n\n"
result += f"**Sector**: {sector}\n\n"
if "< 50" not in size:
result += "**NIS2 Applies**: YES - Your organization is subject to NIS2 requirements\n\n"
result += "**Supervision**: Strict regulatory oversight and enforcement\n\n"
result += "**Penalties**: Up to €10M or 2% of global annual turnover\n\n"
else:
result += "**NIS2 Applies**: Possibly - Small organizations may be exempt, but check national implementation\n\n"
elif is_important:
result += f"**Classification**: Important Entity\n\n"
result += f"**Sector**: {sector}\n\n"
if "β‰₯ 250" in size or "50-249" in size:
result += "**NIS2 Applies**: YES - Your organization is subject to NIS2 requirements\n\n"
result += "**Supervision**: Regular oversight and enforcement\n\n"
result += "**Penalties**: Up to €7M or 1.4% of global annual turnover\n\n"
else:
result += "**NIS2 Applies**: Likely exempt - Small organizations typically not covered\n\n"
else:
result += "**NIS2 Applies**: Unlikely - Sector not explicitly covered\n\n"
result += "### Key Requirements if NIS2 Applies\n\n"
result += "1. Implement cybersecurity risk management measures\n"
result += "2. Report significant incidents within 24 hours\n"
result += "3. Establish governance and accountability\n"
result += "4. Conduct regular risk assessments\n"
result += "5. Implement business continuity and crisis management\n"
result += "6. Supply chain security measures\n"
result += "7. Security awareness training\n"
result += "8. Multi-factor authentication and encryption\n\n"
result += "*Note: This is a preliminary assessment. Consult with legal counsel for definitive determination.*\n"
return result
nis2_check_btn.click(
check_nis2_applicability,
inputs=[nis2_sector, nis2_size],
outputs=[nis2_applicability]
)
with gr.Tab("Requirements Checklist"):
gr.Markdown("### NIS2 Requirements")
nis2_checklist = gr.CheckboxGroup(
choices=[f"{req['id']}: {req['requirement']}" for req in NIS2_REQUIREMENTS],
label="Check all implemented requirements",
value=[]
)
with gr.Row():
with gr.Column():
nis2_score_display = gr.Markdown("**Score**: 0%")
nis2_gauge = gr.Plot(label="NIS2 Compliance")
with gr.Column():
nis2_category_chart = gr.Plot(label="Compliance by Category")
def update_nis2_score(checked):
checked_ids = [item.split(":")[0] for item in checked]
score, category_stats = calculate_compliance_score(NIS2_REQUIREMENTS, checked_ids)
score_text = f"**Score**: {score:.1f}%"
gauge = create_gauge_chart(score, "NIS2 Compliance")
cat_chart = create_category_chart(category_stats, "NIS2 Compliance by Category")
return score_text, gauge, cat_chart
nis2_checklist.change(
update_nis2_score,
inputs=[nis2_checklist],
outputs=[nis2_score_display, nis2_gauge, nis2_category_chart]
)
with gr.Tab("Incident Reporting Workflow"):
gr.Markdown("### NIS2 Incident Reporting Timeline")
gr.Markdown("""
## Incident Reporting Process
### Timeline Requirements
**Within 24 hours of detection:**
- Early warning to CSIRT or competent authority
- Basic information about the incident
- Indication of potential cross-border impact
**Within 72 hours:**
- Incident notification with available details:
- Nature of the incident
- Indicators of compromise
- Severity and impact assessment
- Affected systems and services
- Update on ongoing response activities
**Within 1 month:**
- Final report including:
- Detailed description of the incident
- Type of threat and root cause
- Applied mitigation measures
- Cross-border impact (if any)
- Severity assessment (critical/high/medium/low)
### Incident Severity Classification
**Critical:**
- Major service disruption (>100,000 users)
- Significant financial impact (>€1M)
- Threat to public safety or security
- Wide geographical impact
**High:**
- Substantial service degradation
- Moderate financial impact
- Potential safety implications
**Medium/Low:**
- Limited service impact
- Minimal financial consequences
- Contained geographical scope
### Required Information
1. **Incident identification**
- Date and time of detection
- Incident type (malware, DDoS, unauthorized access, etc.)
- Affected infrastructure/services
2. **Impact assessment**
- Number of affected users
- Service availability impact
- Data breach (yes/no)
- Estimated recovery time
3. **Response actions**
- Containment measures
- Eradication steps
- Recovery procedures
- Lessons learned
### Contact Points
- National CSIRT: [Your national CSIRT contact]
- Competent Authority: [National NIS2 authority]
- Emergency Hotline: [24/7 incident reporting number]
### Best Practices
1. Maintain an incident response playbook
2. Conduct regular incident response drills
3. Pre-register with national CSIRT
4. Establish clear escalation procedures
5. Document all incidents comprehensively
6. Review and update procedures quarterly
""")
# ===================================================================
# Tab 4: Compliance Report
# ===================================================================
with gr.Tab("πŸ“Š Compliance Report"):
gr.Markdown("## Generate Comprehensive Compliance Report")
with gr.Row():
report_framework = gr.Dropdown(
choices=["RGPD/GDPR", "ISO 27001", "NIS2", "All Frameworks"],
value="All Frameworks",
label="Select Framework"
)
with gr.Row():
report_format = gr.Radio(
choices=["Markdown", "HTML", "JSON"],
value="Markdown",
label="Export Format"
)
generate_report_btn = gr.Button("Generate Report", variant="primary", size="lg")
report_output = gr.Markdown()
with gr.Accordion("Framework Comparison", open=False):
gr.Markdown("""
### Framework Overlap and Relationships
**RGPD/GDPR ↔ ISO 27001:**
- ISO 27001 Annex A.18 (Compliance) supports GDPR requirements
- ISO 27001 A.8.8 (Information backup) supports GDPR data availability
- ISO 27001 A.5.34 (Privacy) directly addresses GDPR principles
- GDPR Article 32 (Security) aligns with ISO 27001 security controls
**NIS2 ↔ ISO 27001:**
- NIS2 cybersecurity measures align with ISO 27001 controls
- Both require risk assessment and management
- Incident response requirements overlap significantly
- ISO 27001 certification can demonstrate NIS2 compliance
**RGPD ↔ NIS2:**
- Both require incident notification (different timelines)
- GDPR focuses on personal data, NIS2 on critical infrastructure
- Supply chain requirements overlap
- Governance and accountability requirements align
### Integrated Compliance Approach
1. **Foundation**: Implement ISO 27001 ISMS
2. **Data Protection**: Add GDPR-specific controls
3. **Sector-Specific**: Layer NIS2 requirements if applicable
4. **Continuous**: Monitor, audit, and improve
### Common Controls Across Frameworks
- Risk assessment and management
- Incident response and notification
- Security awareness training
- Access control and authentication
- Encryption and data protection
- Business continuity planning
- Third-party management
- Documentation and record-keeping
""")
def generate_full_report(framework, format_type):
# This is a simplified version - in production, you'd gather actual checklist states
report = f"# Multi-Framework Compliance Report\n\n"
report += f"**Generated**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
report += f"**Framework Scope**: {framework}\n\n"
if framework == "All Frameworks" or framework == "RGPD/GDPR":
report += "## RGPD/GDPR Compliance Summary\n\n"
report += "Review the RGPD/GDPR Compliance tab for detailed assessment.\n\n"
if framework == "All Frameworks" or framework == "ISO 27001":
report += "## ISO 27001 Compliance Summary\n\n"
report += "Review the ISO 27001 Compliance tab for detailed assessment.\n\n"
if framework == "All Frameworks" or framework == "NIS2":
report += "## NIS2 Directive Compliance Summary\n\n"
report += "Review the NIS2 Directive tab for detailed assessment.\n\n"
report += "---\n\n"
report += "*For complete assessment, please fill out the checklists in each framework tab.*\n\n"
if format_type == "JSON":
json_report = {
"generated": datetime.now().isoformat(),
"framework": framework,
"summary": "Please complete assessments in individual tabs"
}
return f"```json\n{json.dumps(json_report, indent=2)}\n```"
elif format_type == "HTML":
html_report = f"<html><body>{report.replace('#', '<h1>').replace('</h1>', '</h1>').replace('##', '<h2>').replace('</h2>', '</h2>')}</body></html>"
return f"```html\n{html_report}\n```"
else:
return report
generate_report_btn.click(
generate_full_report,
inputs=[report_framework, report_format],
outputs=[report_output]
)
# Footer
gr.HTML("""
<div style='text-align:center; padding:30px; margin-top:40px; border-top:1px solid #444; color:#888;'>
<h3 style='color:#fff; margin-bottom:15px;'>Compliance Assistant</h3>
<p><strong>Created by <a href='https://www.ayinedjimi-consultants.fr' target='_blank' style='color:#3498db;'>AYI NEDJIMI Consultants</a></strong></p>
<p>Senior Offensive Cybersecurity & AI Consultant | GRC Expert</p>
<p style='margin-top:15px;'>
<a href='https://www.linkedin.com/in/ayi-nedjimi' target='_blank' style='color:#3498db; margin:0 10px;'>LinkedIn</a> |
<a href='https://github.com/AYI-NEDJIMI' target='_blank' style='color:#3498db; margin:0 10px;'>GitHub</a> |
<a href='https://x.com/AyiNedjimi' target='_blank' style='color:#3498db; margin:0 10px;'>X/Twitter</a> |
<a href='https://www.ayinedjimi-consultants.fr' target='_blank' style='color:#3498db; margin:0 10px;'>Website</a>
</p>
<p style='font-size:12px; margin-top:15px; color:#666;'>
Supporting: RGPD/GDPR β€’ ISO 27001:2022 β€’ NIS2 Directive<br>
Multi-framework compliance assessment and reporting platform
</p>
</div>
""")
return demo
# ============================================================================
# Main
# ============================================================================
if __name__ == "__main__":
demo = create_interface()
demo.launch()