CoolFace
Apppublic

Dave67350/First_agent_template

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
gdpr_sar_log.py125 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"sar_record_{timestamp}.pdf"15 16    pdf = FPDF()17    pdf.add_page()18    pdf.set_auto_page_break(auto=True, margin=15)19    pdf.set_font("Arial", 'B', 16)20    pdf.set_text_color(0, 51, 102)21    title = "Subject Access Request (SAR) Record"22    pdf.cell(0, 15, title, ln=True, align='C')23    pdf.ln(10)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_name', 'N/A')}")30        pdf.multi_cell(0, 10, f"Completed by: {metadata.get('user_name', 'N/A')} ({metadata.get('user_role', 'N/A')})")31        pdf.multi_cell(0, 10, f"Timestamp: {metadata.get('timestamp', 'N/A')}")32        pdf.ln(5)33 34    # Content35    pdf.set_font("Arial", '', 12)36    pdf.set_text_color(0, 0, 0)37    for line in text.strip().split('\n'):38        line = line.strip()39        if line.startswith("## "):40            section = line.replace("## ", "").strip()41            pdf.set_font("Arial", 'B', 13)42            pdf.set_text_color(30, 30, 120)43            pdf.ln(8)44            pdf.cell(0, 10, section, ln=True)45            pdf.set_font("Arial", '', 12)46            pdf.set_text_color(0, 0, 0)47        elif line.startswith("- **"):48            match = re.match(r"- \*\*(.+?)\*\*: (.+)", line)49            if match:50                label, value = match.groups()51                pdf.set_font("Arial", 'B', 12)52                pdf.cell(0, 10, f"{label}:", ln=True)53                pdf.set_font("Arial", '', 12)54                pdf.multi_cell(0, 10, value)55        else:56            pdf.multi_cell(0, 10, line)57 58    pdf.output(output_path)59    return output_path60 61# === Questions ===62QUESTIONS = prepend_metadata_questions([63    ("request_date", "When was the access request received?"),64    ("data_subject_identity", "Who is the data subject (name or ID)?"),65    ("requested_info", "What information did the data subject request?"),66    ("verification_process", "How was the subject's identity verified?"),67    ("response_timeline", "What was the planned timeline for response?"),68    ("info_provided", "What data or response was ultimately provided?"),69    ("notes", "Any additional notes or observations?")70])71 72def get_questions():73    return QUESTIONS74 75# === Run Tool ===76def run_tool():77    state = {"step": 0, "answers": {}}78 79    def step_by_step_agent(user_input, state):80        step = state["step"]81        answers = state["answers"]82        if step > 0:83            key, _ = QUESTIONS[step - 1]84            answers[key] = user_input85 86        if step < len(QUESTIONS):87            next_q = QUESTIONS[step][1]88            state["step"] += 189            return next_q, state, None90 91        # Final formatting92        content = "\n".join([f"- **{label}**: {answers.get(key, '')}" for key, label in QUESTIONS])93        lang = detect(content)94        metadata = {95            "user_name": answers.get("user_name", "N/A"),96            "user_role": answers.get("user_role", "N/A"),97            "organization_name": answers.get("organization_name", "N/A"),98            "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")99        }100 101        pdf_path = export_text_to_pdf(content, metadata=metadata, language=lang)102        return "โœ… SAR record created. Download your PDF below.", {"done": True}, pdf_path103 104    with gr.Blocks(title="SAR Record Tool") as demo:105        chatbot = gr.Chatbot(label="๐Ÿ“ฅ Subject Access Request Assistant", value=[{"role": "assistant", "content": QUESTIONS[0][1]}], type="messages")106        msg = gr.Textbox(label="Your answer")107        state_var = gr.State(state)108        file_output = gr.File(label="Download PDF")109        reset_btn = gr.Button("๐Ÿ” Restart")110 111        def chat_logic(msg_in, state_in):112            reply, updated_state, file = step_by_step_agent(msg_in, state_in)113            messages = [{"role": "user", "content": msg_in}]114            if reply:115                messages.append({"role": "assistant", "content": reply})116            return messages, updated_state, file117 118        def reset():119            return [{"role": "assistant", "content": QUESTIONS[0][1]}], {"step": 0, "answers": {}}, None120 121        msg.submit(chat_logic, [msg, state_var], [chatbot, state_var, file_output])122        reset_btn.click(reset, outputs=[chatbot, state_var, file_output])123 124    demo.launch(show_api=False)125