CoolFace
Apppublic

Dave67350/First_agent_template

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
Gradio_UI.py253 linesDownload Raw Back to root
1import gradio as gr2from fpdf import FPDF3from langdetect import detect4import time5import importlib6 7# === Map document choices to modules ===8DOCUMENT_TO_MODULE = {9    "AI Act": {10        "Compliance Register": "tools.ai_act_generator",11        "High-Risk System Record": "tools.high_risk_ai_register",12        "Technical Documentation Template": "tools.ai_technical_doc",13        "Post-Market Monitoring Plan": "tools.post_market_monitoring",14        "Risk-Management Plan": "tools.risk_management_plan",15        "Data Governance Record": "tools.data_governance_record",16        "Human Oversight Strategy (Art. 14)": "tools.human_oversight_strategy",17        "Corrective Action Log": "tools.corrective_action_log"18    },19    "GDPR": {20        "Data Processing Record": "tools.gdpr_data_record",21        "DPIA (Data Protection Impact Assessment)": "tools.gdpr_dpia",22        "Data Breach Notification Log": "tools.gdpr_breach_log",23        "Subject Access Request Record": "tools.gdpr_sar_log",24        "Consent Management Log": "tools.gdpr_consent_log",25        "Data Processor Agreements": "tools.gdpr_dpa_log"26    },27    "NIS2": {28        "Access Control Log": "tools.nis2_access_control_log",29        "Asset Inventory": "tools.nis2_asset_inventory",30        "Backup & Recovery Log": "tools.nis2_backup_recovery_log",31        "Business Continuity Plan": "tools.nis2_business_continuity",32        "Compliance Audit Log": "tools.nis2_compliance_audit_log",33        "Data Encryption Inventory": "tools.nis2_data_encryption_inventory",34        "Disaster Recovery Plan": "tools.nis2_disaster_recovery_plan",35        "Incident Communication Plan": "tools.nis2_incident_communication",36        "Incident Response Log": "tools.nis2_incident_log",37        "Logging & Monitoring Policy": "tools.nis2_logging_monitoring_policy",38        "Network Architecture Diagram Log": "tools.nis2_network_architecture_log",39        "Penetration Test Summary": "tools.nis2_penetration_test_summary",40        "Physical Security Checklist": "tools.nis2_physical_security_checklist",41        "Risk Assessment Matrix": "tools.nis2_risk_assessment_matrix",42        "Risk Register": "tools.nis2_risk_register",43        "Security Audit Record": "tools.nis2_security_audit",44        "Security Testing Strategy": "tools.nis2_security_testing_strategy",45        "Security Awareness Training Record": "tools.nis2_security_training_record",46        "Supply Chain Risk Record": "tools.nis2_supply_chain_risk",47        "System Testing Record": "tools.nis2_system_testing",48        "Third-Party Access Review": "tools.nis2_third_party_access_review",49        "Vulnerability Management Log": "tools.nis2_vulnerability_log"50    },51    "DORA": {52        "Third-Party ICT Risk Register": "tools.nis2_third_party_access_review",53        "ICT Asset Inventory": "tools.nis2_asset_inventory",54        "Incident Reporting Log": "tools.nis2_incident_log",55        "Risk Register": "tools.nis2_risk_register",56        "Backup & Recovery": "tools.nis2_backup_recovery_log",57        "Penetration Testing Summary": "tools.nis2_penetration_test_summary",58        "Disaster Recovery Plan": "tools.nis2_disaster_recovery_plan",59        "Security Testing Strategy": "tools.nis2_security_testing_strategy",60        "Backup Strategy Summary": "tools.dora_backup_strategy_summary",61        "Capacity Management Log": "tools.dora_capacity_management_log",62        "Cloud Resilience Assessment": "tools.dora_cloud_resilience_assessment",63        "Cloud Service Usage Log": "tools.dora_cloud_service_usage_log",64        "Communication Tree (Crisis)": "tools.dora_communication_tree",65        "Critical Function Inventory": "tools.dora_critical_function_inventory",66        "Data Integrity Strategy": "tools.dora_data_integrity_strategy",67        "Data Loss Prevention": "tools.dora_data_loss_prevention",68        "Encryption Strategy": "tools.dora_encryption_strategy",69        "ICT Asset Log": "tools.dora_ict_asset_log",70        "ICT Asset Register": "tools.dora_ict_asset_register",71        "Incident Notification Log": "tools.dora_incident_notification_log",72        "Network Resilience Assessment": "tools.dora_network_resilience_assessment",73        "Remote Access Policy": "tools.dora_remote_access_policy",74        "Risk Management Policy": "tools.dora_risk_management_policy",75        "Simulation Test Log": "tools.dora_simulation_test_log",76        "Third-Party Dependency Map": "tools.dora_third_party_dependency_map",77        "Third-Party Dependency Register": "tools.dora_third_party_dependency_register",78        "Third-Party Log": "tools.dora_third_party_log",79        "Third-Party Mapping": "tools.dora_third_party_mapping"80    },81        "DMA": {82        "Gatekeeper Service Log": "tools.dma_gatekeeper_service_log",83        "User Consent Overview": "tools.dma_user_consent_overview",84        "Interoperability Compliance Report": "tools.dma_interoperability_report",85        "Data Sharing Record": "tools.dma_data_sharing_record",86        "Complaint Handling Log": "tools.dma_complaint_log",87        "Self-Assessment Declaration": "tools.dma_self_assessment",88        "Third-Party Access Request Register": "tools.dma_third_party_access_register",89        "Transparency Obligation Record": "tools.dma_transparency_log"90    },91        "DSA": {92        "Content Moderation Log": "tools.dsa_content_moderation_log",93        "Transparency Report": "tools.dsa_transparency_report",94        "Complaint Handling Register": "tools.dsa_complaint_handling_log",95        "Risk Mitigation Measures": "tools.dsa_risk_mitigation_log",96        "Ad Targeting Policy Log": "tools.dsa_ad_targeting_log",97        "Trusted Flaggers Log": "tools.dsa_trusted_flaggers_log"98    }   99}100 101 102# === PDF Export Function ===103def export_pdf(title, answers, lang="en"):104    pdf = FPDF()105    pdf.add_page()106    pdf.set_auto_page_break(auto=True, margin=15)107 108    pdf.set_font("Arial", 'B', 16)109    pdf.set_text_color(0, 51, 102)110    pdf.cell(0, 10, title, ln=True, align='C')111    pdf.ln(8)112 113    company = answers.get("What is the name of your organization?", "N/A")114    name = answers.get("What is your name?", "N/A")115    role = answers.get("What is your role?", "N/A")116    timestamp = time.strftime("%Y-%m-%d %H:%M:%S")117 118    pdf.set_font("Arial", 'I', 11)119    pdf.set_text_color(80, 80, 80)120    pdf.cell(0, 8, f"Organization: {company}", ln=True, align='C')121    pdf.cell(0, 8, f"Completed by: {name} ({role})", ln=True, align='C')122    pdf.cell(0, 8, f"Timestamp: {timestamp}", ln=True, align='C')123    pdf.ln(10)124 125    # Add a draft disclaimer126    pdf.set_font("Arial", 'B', 12)127    pdf.set_text_color(200, 0, 0)  # Red color128    pdf.multi_cell(0, 10, "DRAFT: This document is a draft generated by an AI assistant.\nIt is not legal advice and should be reviewed by a qualified professional.")129    pdf.ln(10)130 131 132    pdf.set_font("Arial", '', 12)133    pdf.set_text_color(0, 0, 0)134    for label, value in answers.items():135        pdf.set_font("Arial", 'B', 12)136        pdf.multi_cell(0, 10, f"{label}:", align='L')137        pdf.set_font("Arial", '', 12)138        pdf.multi_cell(0, 10, value)139        pdf.ln(5)140 141    filename = f"{title.replace(' ', '_')}_{int(time.time())}.pdf"142    pdf.output(filename)143    return filename144 145# === State Memory ===146conversation_state = {147    "step": 0,148    "questions": [],149    "answers": {},150    "title": "",151    "lang": "en",152    "tool": None153}154 155# === Load Tool Dynamically ===156def start_conversation(reg, doc):157    conversation_state["step"] = 0158    conversation_state["answers"] = {}159    conversation_state["title"] = f"{reg} - {doc}"160 161    module_path = DOCUMENT_TO_MODULE[reg][doc]162    module = importlib.import_module(module_path)163    conversation_state["questions"] = module.get_questions()164    conversation_state["tool"] = module165 166    first_question = conversation_state["questions"][0][1]167    return [{"role": "assistant", "content": f"๐Ÿ“‹ {first_question}"}]168 169# === Continue Chat ===170def continue_conversation(user_input):171    messages = [{"role": "user", "content": user_input}]172    step = conversation_state["step"]173 174    if step < len(conversation_state["questions"]):175        key, question = conversation_state["questions"][step]176        conversation_state["answers"][question] = user_input177        conversation_state["step"] += 1178 179        try:180            if user_input and len(user_input.strip()) > 3:181                conversation_state["lang"] = detect(user_input)182        except:183            conversation_state["lang"] = "en"184 185    if conversation_state["step"] < len(conversation_state["questions"]):186        next_question = conversation_state["questions"][conversation_state["step"]][1]187        messages.append({"role": "assistant", "content": f"๐Ÿง  {next_question}"})188        return messages, None189    else:190        pdf_path = export_pdf(conversation_state["title"], conversation_state["answers"], lang=conversation_state["lang"])191        messages.append({"role": "assistant", "content": "โœ… Done! Your document is ready to download."})192        return messages, pdf_path193 194# === Gradio Interface ===195with gr.Blocks(196    title="Regulatory Compliance Generator",197    css="""198    footer, 199    a[href*="gradio.app"],200    a[href*="huggingface.co"] {201        display: none !important;202    }203 204    button[aria-label="Share"],205    button[title="Share"],206    button[data-testid="share-button"] {207        pointer-events: none !important;208        opacity: 0.4 !important;209        cursor: default !important;210    }211    """212) as demo:213    gr.Markdown("""214    ### ๐Ÿ”’ GDPR Notice  215    This assistant does not store any personal data.  216    All responses are processed temporarily to generate your document.  217    You are responsible for the accuracy and legality of the information submitted.218    """)219 220    with gr.Row():221        reg_dropdown = gr.Dropdown(222            choices=list(DOCUMENT_TO_MODULE.keys()),223            label="Select Regulation",224            value=None,225            interactive=True,226            info="-- Please choose a regulation --"227        )228        doc_dropdown = gr.Dropdown(229            label="Select Document Type",230            choices=[],231            value=None,232            interactive=True,233            info="-- Select a document after choosing a regulation --"234        )235 236    def update_doc_dropdown(selected_reg):237        if selected_reg in DOCUMENT_TO_MODULE:238            return gr.update(choices=list(DOCUMENT_TO_MODULE[selected_reg].keys()), value=None)239        return gr.update(choices=[], value=None)240 241    reg_dropdown.change(update_doc_dropdown, inputs=reg_dropdown, outputs=doc_dropdown)242 243    start_btn = gr.Button("๐Ÿš€ Start")244    chatbox = gr.Chatbot(label="๐Ÿง‘โ€โš–๏ธ Legalbot", value=[], type="messages", elem_classes=["chatbot"])245    user_input = gr.Textbox(label="Your answer", placeholder="Type your answer and press Enter")246    pdf_output = gr.File(label="Download PDF", visible=True)247 248    start_btn.click(start_conversation, inputs=[reg_dropdown, doc_dropdown], outputs=chatbox)249    user_input.submit(continue_conversation, inputs=user_input, outputs=[chatbox, pdf_output])250    user_input.submit(lambda: "", None, user_input)251 252demo.launch()253