CoolFace
Apppublic

Dave67350/First_agent_template

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
nis2_security_audit.py124 linesDownload Raw Back to tools
1#!/usr/bin/env python2# coding=utf-83import datetime4import re5from fpdf import FPDF6from langdetect import detect7import gradio as gr8from tools.common import prepend_metadata_questions9 10# === PDF Export ===11def export_text_to_pdf(text, metadata=None, output_path=None, language="en"):12    if output_path is None:13        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")14        output_path = f"security_audit_record_{timestamp}.pdf"15 16    pdf = FPDF()17    pdf.add_page()18    pdf.set_auto_page_break(auto=True, margin=15)19 20    pdf.set_font("Arial", 'B', 16)21    pdf.set_text_color(0, 51, 102)22    title = "Security Audit Record (NIS2)"23    pdf.cell(0, 15, title, ln=True, align='C')24    pdf.ln(10)25 26    # Metadata Section27    if metadata:28        pdf.set_font("Arial", '', 12)29        pdf.set_text_color(90, 90, 90)30        pdf.multi_cell(0, 10, f"Organization: {metadata.get('organization_name', 'N/A')}")31        pdf.multi_cell(0, 10, f"Completed by: {metadata.get('user_name', 'N/A')} ({metadata.get('user_role', 'N/A')})")32        pdf.multi_cell(0, 10, f"Timestamp: {metadata.get('timestamp', 'N/A')}")33        pdf.ln(5)34 35    # Main Content36    pdf.set_font("Arial", '', 12)37    pdf.set_text_color(0, 0, 0)38    for line in text.strip().split("\n"):39        line = line.strip()40        if line.startswith("## "):41            section = line.replace("## ", "").strip()42            pdf.set_font("Arial", 'B', 13)43            pdf.set_text_color(30, 30, 120)44            pdf.ln(8)45            pdf.cell(0, 10, section, ln=True)46            pdf.set_font("Arial", '', 12)47            pdf.set_text_color(0, 0, 0)48        elif line.startswith("- **"):49            match = re.match(r"- \*\*(.+?)\*\*: (.+)", line)50            if match:51                label, val = match.groups()52                pdf.set_font("Arial", 'B', 12)53                pdf.cell(0, 10, f"{label}:", ln=True)54                pdf.set_font("Arial", '', 12)55                pdf.multi_cell(0, 10, val)56        else:57            pdf.multi_cell(0, 10, line)58 59    pdf.output(output_path)60    return output_path61 62# === Questions ===63QUESTIONS = prepend_metadata_questions([64    ("audit_date", "When was the security audit conducted?"),65    ("audit_scope", "What was the scope of the audit?"),66    ("tools_used", "What tools or frameworks were used?"),67    ("vulnerabilities_found", "List key vulnerabilities or findings."),68    ("recommendations", "What recommendations were made?"),69    ("implementation_status", "Status of implementation for recommendations."),70    ("next_audit", "When is the next audit planned?")71])72 73def get_questions():74    return QUESTIONS75 76# === Launch Tool ===77def run_tool():78    state = {"step": 0, "answers": {}}79 80    def step_by_step_agent(user_input, state):81        step = state["step"]82        answers = state["answers"]83        if step > 0:84            key, _ = QUESTIONS[step - 1]85            answers[key] = user_input86 87        if step < len(QUESTIONS):88            next_q = QUESTIONS[step][1]89            state["step"] += 190            return next_q, state, None91 92        content = "\n".join([f"- **{label}**: {answers.get(key, '')}" for key, label in QUESTIONS])93        lang = detect(content)94        metadata = {95            "organization_name": answers.get("organization_name", "N/A"),96            "user_name": answers.get("user_name", "N/A"),97            "user_role": answers.get("user_role", "N/A"),98            "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")99        }100        pdf_path = export_text_to_pdf(content, metadata=metadata, language=lang)101        return "โœ… Security Audit Record completed. Download your PDF below.", {"done": True}, pdf_path102 103    with gr.Blocks(title="Security Audit Record Tool") as demo:104        chatbot = gr.Chatbot(label="๐Ÿ›ก๏ธ Audit Assistant", value=[{"role": "assistant", "content": QUESTIONS[0][1]}], type="messages")105        msg = gr.Textbox(label="Your answer")106        state_var = gr.State(state)107        file_output = gr.File(label="Download PDF")108        reset_btn = gr.Button("๐Ÿ” Restart")109 110        def chat_logic(msg_in, state_in):111            reply, updated_state, file = step_by_step_agent(msg_in, state_in)112            messages = [{"role": "user", "content": msg_in}]113            if reply:114                messages.append({"role": "assistant", "content": reply})115            return messages, updated_state, file116 117        def reset():118            return [{"role": "assistant", "content": QUESTIONS[0][1]}], {"step": 0, "answers": {}}, None119 120        msg.submit(chat_logic, [msg, state_var], [chatbot, state_var, file_output])121        reset_btn.click(reset, outputs=[chatbot, state_var, file_output])122 123    demo.launch(show_api=False)124