CoolFace
Apppublic

Dave67350/First_agent_template

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
dma_third_party_access_register.py122 linesDownload Raw Back to tools
1# tools/dma_third_party_access_register.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"dma_third_party_access_{timestamp}.pdf"15 16    pdf = FPDF()17    pdf.add_page()18    pdf.set_auto_page_break(auto=True, margin=15)19    20    pdf.set_font("Arial", 'B', 16)21    pdf.set_text_color(0, 51, 102)22    title = "DMA Third-Party Access Register" if language == "en" else "Registre d'accès tiers - DMA"23    pdf.cell(0, 15, title, ln=True, align='C')24    pdf.ln(10)25 26    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('name', '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    pdf.set_font("Arial", '', 12)35    pdf.set_text_color(0, 0, 0)36    for line in text.strip().split('\n'):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        else:54            pdf.multi_cell(0, 10, line)55 56    pdf.output(output_path)57    return output_path58 59# === Questions ===60QUESTIONS = prepend_metadata_questions([61    ("third_party_name", "What is the name of the third-party entity?"),62    ("purpose_of_access", "What is the purpose of access?"),63    ("data_types_accessed", "What types of user data are being accessed?"),64    ("legal_basis", "What legal basis or contract governs this access?"),65    ("duration", "What is the duration or expiry date of access?"),66    ("security_measures", "What security measures are in place?"),67    ("user_consent_status", "Has user consent been properly documented?")68])69 70def get_questions():71    return QUESTIONS72 73# === Run Tool ===74def run_tool():75    state = {"step": 0, "answers": {}}76 77    def step_by_step_agent(user_input, state):78        step = state["step"]79        answers = state["answers"]80 81        if step > 0:82            key, _ = QUESTIONS[step - 1]83            answers[key] = user_input84 85        if step < len(QUESTIONS):86            next_q = QUESTIONS[step][1]87            state["step"] += 188            return next_q, state, None89 90        content = "\n".join([f"- **{label}**: {answers.get(key, '')}" for key, label in QUESTIONS])91        lang = detect(content) if len(content.strip()) > 3 else "en"92        metadata = {93            "organization": answers.get("organization_name", "N/A"),94            "name": answers.get("user_name", "N/A"),95            "role": answers.get("user_role", "N/A"),96            "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")97        }98        pdf_path = export_text_to_pdf(content, metadata=metadata, language=lang)99        return "✅ Register complete. Download your PDF below.", {"done": True}, pdf_path100 101    with gr.Blocks(title="DMA Third-Party Access Tool") as demo:102        chatbot = gr.Chatbot(label="🔗 DMA Third-Party Access Assistant", value=[{"role": "assistant", "content": QUESTIONS[0][1]}], type="messages")103        msg = gr.Textbox(label="Your answer")104        state_var = gr.State(state)105        file_output = gr.File(label="Download PDF")106        reset_btn = gr.Button("🔁 Restart")107 108        def chat_logic(msg_in, state_in):109            reply, updated_state, file = step_by_step_agent(msg_in, state_in)110            messages = [{"role": "user", "content": msg_in}]111            if reply:112                messages.append({"role": "assistant", "content": reply})113            return messages, updated_state, file114 115        def reset():116            return [{"role": "assistant", "content": QUESTIONS[0][1]}], {"step": 0, "answers": {}}, None117 118        msg.submit(chat_logic, [msg, state_var], [chatbot, state_var, file_output])119        reset_btn.click(reset, outputs=[chatbot, state_var, file_output])120 121    demo.launch(show_api=False)122