CoolFace
Apppublic

Dave67350/First_agent_template

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
nis2_security_training_record.py123 linesDownload Raw Back to tools
1# tools/nis2_security_training_record.py2 3import 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_awareness_training_{timestamp}.pdf"15 16    pdf = FPDF()17    pdf.add_page()18    pdf.set_auto_page_break(auto=True, margin=15)19 20    # Title21    pdf.set_font("Arial", 'B', 16)22    pdf.set_text_color(0, 51, 102)23    title = "Security Awareness Training Record" if language == "en" else "Registre de Formation à la Sécurité"24    pdf.cell(0, 15, title, ln=True, align='C')25    pdf.ln(10)26 27    # Metadata28    if metadata:29        pdf.set_font("Arial", '', 12)30        pdf.set_text_color(90, 90, 90)31        pdf.multi_cell(0, 10, f"Organization: {metadata.get('organization_name', 'N/A')}")32        pdf.multi_cell(0, 10, f"Completed by: {metadata.get('user_name', 'N/A')} ({metadata.get('user_role', 'N/A')})")33        pdf.multi_cell(0, 10, f"Timestamp: {metadata.get('timestamp', 'N/A')}")34        pdf.ln(5)35 36    # Body37    pdf.set_font("Arial", '', 12)38    pdf.set_text_color(0, 0, 0)39    for line in text.strip().split('\n'):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, value = 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, value)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    ("training_policy", "Does your organization have a formal training policy?"),65    ("audience", "Who is required to attend security awareness training?"),66    ("topics_covered", "What topics are covered during training?"),67    ("frequency", "How often is training conducted?"),68    ("delivery_methods", "How is training delivered (e.g., online, in-person)?"),69    ("training_tracking", "How is participation tracked and recorded?"),70    ("improvement_feedback", "How is feedback used to improve future sessions?")71])72 73def get_questions():74    return QUESTIONS75 76# === Tool Execution ===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        if step < len(QUESTIONS):87            next_q = QUESTIONS[step][1]88            state["step"] += 189            return next_q, state, None90 91        content = "\n".join([f"- **{label}**: {answers.get(key, '')}" for key, label in QUESTIONS])92        lang = detect(content)93        metadata = {94            "user_name": answers.get("user_name", "N/A"),95            "user_role": answers.get("user_role", "N/A"),96            "organization_name": answers.get("organization_name", "N/A"),97            "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")98        }99        pdf_path = export_text_to_pdf(content, metadata=metadata, language=lang)100        return "✅ Training record completed. Download below.", {"done": True}, pdf_path101 102    with gr.Blocks(title="Security Awareness Training Tool") as demo:103        chatbot = gr.Chatbot(label="🎓 Security Training Assistant", value=[{"role": "assistant", "content": QUESTIONS[0][1]}], type="messages")104        msg = gr.Textbox(label="Your answer")105        state_var = gr.State(state)106        file_output = gr.File(label="Download PDF")107        reset_btn = gr.Button("🔁 Restart")108 109        def chat_logic(msg_in, state_in):110            reply, updated_state, file = step_by_step_agent(msg_in, state_in)111            messages = [{"role": "user", "content": msg_in}]112            if reply:113                messages.append({"role": "assistant", "content": reply})114            return messages, updated_state, file115 116        def reset():117            return [{"role": "assistant", "content": QUESTIONS[0][1]}], {"step": 0, "answers": {}}, None118 119        msg.submit(chat_logic, [msg, state_var], [chatbot, state_var, file_output])120        reset_btn.click(reset, outputs=[chatbot, state_var, file_output])121 122    demo.launch(show_api=False)123