CoolFace
Apppublic

Dave67350/First_agent_template

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
nis2_security_testing_strategy.py127 linesDownload Raw Back to tools
1# nis2_security_testing_strategy.py2import datetime3import re4from fpdf import FPDF5from langdetect import detect6import gradio as gr7from tools.common import prepend_metadata_questions8 9# === PDF Export ===10def export_text_to_pdf(text, metadata=None, output_path=None, language="en"):11    if output_path is None:12        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")13        output_path = f"security_testing_strategy_{timestamp}.pdf"14 15    pdf = FPDF()16    pdf.add_page()17    pdf.set_auto_page_break(auto=True, margin=15)18 19    pdf.set_font("Arial", 'B', 16)20    pdf.set_text_color(0, 51, 102)21    title = "Security Testing Strategy - NIS2" if language == "en" else "Stratégie de Tests de Sécurité - NIS2"22    pdf.cell(0, 15, title, ln=True, align='C')23    pdf.ln(10)24 25    if metadata:26        pdf.set_font("Arial", '', 12)27        pdf.set_text_color(90, 90, 90)28        pdf.multi_cell(0, 10, f"Organization: {metadata.get('organization_name', 'N/A')}")29        pdf.multi_cell(0, 10, f"Completed by: {metadata.get('user_name', 'N/A')} ({metadata.get('user_role', 'N/A')})")30        pdf.multi_cell(0, 10, f"Timestamp: {metadata.get('timestamp', 'N/A')}")31        pdf.ln(5)32 33    pdf.set_font("Arial", '', 12)34    pdf.set_text_color(0, 0, 0)35    for line in text.strip().split('\n'):36        line = line.strip()37        if line.startswith("## "):38            section = line.replace("## ", "").strip()39            pdf.set_font("Arial", 'B', 13)40            pdf.set_text_color(30, 30, 120)41            pdf.ln(8)42            pdf.cell(0, 10, section, ln=True)43            pdf.set_font("Arial", '', 12)44            pdf.set_text_color(0, 0, 0)45        elif line.startswith("- **"):46            match = re.match(r"- \*\*(.+?)\*\*: (.+)", line)47            if match:48                label, value = match.groups()49                pdf.set_font("Arial", 'B', 12)50                pdf.cell(0, 10, f"{label}:", ln=True)51                pdf.set_font("Arial", '', 12)52                pdf.multi_cell(0, 10, value)53        elif line == "---":54            pdf.line(10, pdf.get_y(), 200, pdf.get_y())55            pdf.ln(5)56        else:57            pdf.multi_cell(0, 10, line)58    pdf.output(output_path)59    return output_path60 61# === Questions ===62QUESTIONS = prepend_metadata_questions([63    ("testing_scope", "What is the scope of security testing (e.g., applications, network, systems)?"),64    ("testing_types", "Which types of testing are performed (e.g., pen tests, code review)?"),65    ("testing_frequency", "How often are tests conducted?"),66    ("responsible_roles", "Who is responsible for testing and reviewing results?"),67    ("tools_used", "What tools and platforms are used in testing?"),68    ("external_parties", "Are external auditors or testers involved? If so, who?"),69    ("remediation_plan", "What is the plan for addressing discovered vulnerabilities?"),70    ("documentation", "How are test results and actions documented and stored?")71])72 73 74def get_questions():75    return QUESTIONS76 77 78def run_tool():79    state = {"step": 0, "answers": {}}80 81    def step_by_step_agent(user_input, state):82        step = state["step"]83        answers = state["answers"]84 85        if step > 0:86            key, _ = QUESTIONS[step - 1]87            answers[key] = user_input88 89        if step < len(QUESTIONS):90            next_question = QUESTIONS[step][1]91            state["step"] += 192            return next_question, state, None93 94        metadata = {95            "user_name": answers.get("user_name", "N/A"),96            "user_role": answers.get("user_role", "N/A"),97            "organization_name": answers.get("organization_name", "N/A"),98            "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")99        }100 101        content = "\n".join([f"- **{label}**: {answers.get(key, '')}" for key, label in QUESTIONS])102        lang = detect(content)103        pdf_path = export_text_to_pdf(content, metadata=metadata, language=lang)104        return "✅ Strategy finalized. Download your PDF below.", {"done": True}, pdf_path105 106    with gr.Blocks(title="Security Testing Strategy Tool") as demo:107        chatbot = gr.Chatbot(label="🧪 Security Testing Assistant", value=[{"role": "assistant", "content": QUESTIONS[0][1]}], type="messages")108        msg = gr.Textbox(label="Your answer")109        state_var = gr.State(state)110        file_output = gr.File(label="Download PDF")111        reset_btn = gr.Button("🔁 Restart")112 113        def chat_logic(msg_in, state_in):114            reply, updated_state, file = step_by_step_agent(msg_in, state_in)115            messages = [{"role": "user", "content": msg_in}]116            if reply:117                messages.append({"role": "assistant", "content": reply})118            return messages, updated_state, file119 120        def reset():121            return [{"role": "assistant", "content": QUESTIONS[0][1]}], {"step": 0, "answers": {}}, None122 123        msg.submit(chat_logic, [msg, state_var], [chatbot, state_var, file_output])124        reset_btn.click(reset, outputs=[chatbot, state_var, file_output])125 126    demo.launch(show_api=False)127