Dave67350/First_agent_template
0
1# tools/nis2_data_encryption_inventory.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"data_encryption_inventory_{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 = "Data Encryption Inventory" if language == "en" else "Inventaire du Chiffrement des Données"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 # Main content37 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 ("encryption_scope", "Which data categories are encrypted (e.g., PII, financial, etc.)?"),65 ("encryption_methods", "What encryption methods or algorithms are used?"),66 ("at_rest", "Is data encrypted at rest? If yes, how?"),67 ("in_transit", "Is data encrypted in transit? Describe the protocols used."),68 ("key_management", "How is key management handled?"),69 ("responsible_teams", "Which team or roles are responsible for encryption?"),70 ("compliance_alignment", "How does your encryption strategy align with regulatory requirements?")71])72 73def get_questions():74 return QUESTIONS75 76# === Gradio UI ===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 84 if step > 0:85 key, _ = QUESTIONS[step - 1]86 answers[key] = user_input87 88 if step < len(QUESTIONS):89 next_q = QUESTIONS[step][1]90 state["step"] += 191 return next_q, state, None92 93 content = "\n".join([f"- **{label}**: {answers.get(key, '')}" for key, label in QUESTIONS])94 lang = detect(content)95 96 metadata = {97 "user_name": answers.get("user_name", "N/A"),98 "user_role": answers.get("user_role", "N/A"),99 "organization_name": answers.get("organization_name", "N/A"),100 "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")101 }102 103 pdf_path = export_text_to_pdf(content, metadata=metadata, language=lang)104 return "✅ Inventory generated. Download below.", {"done": True}, pdf_path105 106 with gr.Blocks(title="Data Encryption Inventory") as demo:107 chatbot = gr.Chatbot(label="🔐 Encryption 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 