CoolFace
Apppublic

Dave67350/First_agent_template

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
nis2_system_testing.py126 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 Function ===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"system_testing_record_{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 = "System Testing Record (NIS2)"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_title = 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_title, 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    ("system_name", "What is the name of the system being tested?"),65    ("test_scope", "What areas or functionalities were covered in the test?"),66    ("test_objectives", "What were the objectives of the testing effort?"),67    ("test_methods", "What methods or tools were used during testing?"),68    ("test_environment", "Describe the environment used for testing."),69    ("findings", "Summarize key issues or bugs identified."),70    ("remediation", "Describe how the issues were addressed or resolved."),71    ("validation", "Was a validation or re-test conducted?"),72    ("tester_name", "Who performed the test?")73])74 75def get_questions():76    return QUESTIONS77 78# === Run Tool ===79def run_tool():80    state = {"step": 0, "answers": {}}81 82    def step_by_step_agent(user_input, state):83        step = state["step"]84        answers = state["answers"]85        if step > 0:86            key, _ = QUESTIONS[step - 1]87            answers[key] = user_input88 89        if step < len(QUESTIONS):90            next_q = QUESTIONS[step][1]91            state["step"] += 192            return next_q, state, None93 94        content = "\n".join([f"- **{label}**: {answers.get(key, '')}" for key, label in QUESTIONS])95        lang = detect(content)96        metadata = {97            "organization_name": answers.get("organization_name", "N/A"),98            "user_name": answers.get("user_name", "N/A"),99            "user_role": answers.get("user_role", "N/A"),100            "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")101        }102        pdf_path = export_text_to_pdf(content, metadata=metadata, language=lang)103        return "โœ… Testing Record completed. Download your PDF below.", {"done": True}, pdf_path104 105    with gr.Blocks(title="System Testing Log Tool") as demo:106        chatbot = gr.Chatbot(label="๐Ÿงช Testing Assistant", value=[{"role": "assistant", "content": QUESTIONS[0][1]}], type="messages")107        msg = gr.Textbox(label="Your answer")108        state_var = gr.State(state)109        file_output = gr.File(label="Download PDF")110        reset_btn = gr.Button("๐Ÿ” Restart")111 112        def chat_logic(msg_in, state_in):113            reply, updated_state, file = step_by_step_agent(msg_in, state_in)114            messages = [{"role": "user", "content": msg_in}]115            if reply:116                messages.append({"role": "assistant", "content": reply})117            return messages, updated_state, file118 119        def reset():120            return [{"role": "assistant", "content": QUESTIONS[0][1]}], {"step": 0, "answers": {}}, None121 122        msg.submit(chat_logic, [msg, state_var], [chatbot, state_var, file_output])123        reset_btn.click(reset, outputs=[chatbot, state_var, file_output])124 125    demo.launch(show_api=False)126