CoolFace
Apppublic

Dave67350/First_agent_template

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
dsa_risk_mitigation_log.py129 linesDownload Raw Back to tools
1# tools/dsa_risk_mitigation_log.py2 3from datetime import datetime4from fpdf import FPDF5import re6import gradio as gr7from langdetect import detect8 9# === PDF Export Function ===10def export_text_to_pdf(text, metadata=None, output_path=None, language="en"):11    if output_path is None:12        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")13        output_path = f"dsa_risk_mitigation_log_{timestamp}.pdf"14 15    pdf = FPDF()16    pdf.add_page()17    pdf.set_auto_page_break(auto=True, margin=15)18 19    # Title20    pdf.set_font("Arial", 'B', 16)21    pdf.set_text_color(0, 51, 102)22    pdf.cell(0, 15, "DSA Risk Mitigation Log", ln=True, align='C')23    pdf.ln(8)24 25    # Metadata26    if metadata:27        pdf.set_font("Arial", '', 12)28        pdf.set_text_color(90, 90, 90)29        pdf.multi_cell(0, 10, f"Organization: {metadata.get('organization', 'N/A')}")30        pdf.multi_cell(0, 10, f"Completed by: {metadata.get('completed_by', 'N/A')} ({metadata.get('role', 'N/A')})")31        pdf.multi_cell(0, 10, f"Timestamp: {metadata.get('timestamp', 'N/A')}")32        pdf.ln(5)33 34    # Body35    pdf.set_font("Arial", '', 12)36    pdf.set_text_color(0, 0, 0)37    for line in text.strip().split('\n'):38        if line.startswith("## "):39            section = line.replace("## ", "").strip()40            pdf.set_font("Arial", 'B', 13)41            pdf.set_text_color(30, 30, 120)42            pdf.ln(6)43            pdf.cell(0, 10, section, ln=True)44            pdf.set_font("Arial", '', 12)45            pdf.set_text_color(0, 0, 0)46        elif line.startswith("- **"):47            match = re.match(r"- \*\*(.+?)\*\*: (.+)", line)48            if match:49                label, value = match.groups()50                pdf.set_font("Arial", 'B', 12)51                pdf.cell(0, 10, f"{label}:", ln=True)52                pdf.set_font("Arial", '', 12)53                pdf.multi_cell(0, 10, value)54        else:55            pdf.multi_cell(0, 10, line)56 57    pdf.output(output_path)58    return output_path59 60# === Questions ===61QUESTIONS = [62    ("organization", "What is the name of your organization?"),63    ("completed_by", "Who is completing this log?"),64    ("role", "What is your role?"),65    ("risk_description", "Describe the systemic or platform-related risk identified."),66    ("impact_scope", "What is the scope and impact of the risk?"),67    ("mitigation_measures", "What mitigation measures were implemented?"),68    ("timeline", "What was the timeline for implementation?"),69    ("monitoring_plan", "What monitoring or evaluation is in place?"),70    ("outcome", "What was the outcome or effectiveness of the mitigation?")71]72 73def get_questions():74    return QUESTIONS75 76# === Run 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        try:94            lang = detect(content) if len(content.strip()) > 3 else "en"95        except:96            lang = "en"97 98        metadata = {99            "organization": answers.get("organization"),100            "completed_by": answers.get("completed_by"),101            "role": answers.get("role"),102            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")103        }104 105        pdf_path = export_text_to_pdf(content, metadata=metadata, language=lang)106        return "โœ… Risk mitigation log completed. Download below.", {"done": True}, pdf_path107 108    with gr.Blocks(title="DSA Risk Mitigation Log Tool") as demo:109        chatbot = gr.Chatbot(label="๐Ÿ›ก๏ธ Risk Mitigation Assistant", value=[{"role": "assistant", "content": QUESTIONS[0][1]}], type="messages")110        msg = gr.Textbox(label="Your answer")111        state_var = gr.State(state)112        file_output = gr.File(label="Download PDF")113        reset_btn = gr.Button("๐Ÿ” Restart")114 115        def chat_logic(msg_in, state_in):116            reply, updated_state, file = step_by_step_agent(msg_in, state_in)117            messages = [{"role": "user", "content": msg_in}]118            if reply:119                messages.append({"role": "assistant", "content": reply})120            return messages, updated_state, file121 122        def reset():123            return [{"role": "assistant", "content": QUESTIONS[0][1]}], {"step": 0, "answers": {}}, None124 125        msg.submit(chat_logic, [msg, state_var], [chatbot, state_var, file_output])126        reset_btn.click(reset, outputs=[chatbot, state_var, file_output])127 128    demo.launch(show_api=False)129