CoolFace
Apppublic

Dave67350/First_agent_template

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
gdpr_consent_log.py124 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"consent_management_log_{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 = "Consent Management Log"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    ("data_subject", "Who gave consent (name or ID)?"),64    ("consent_purpose", "What is the purpose for which consent was collected?"),65    ("collection_method", "How was consent collected (e.g. checkbox, form)?"),66    ("timestamp_collected", "When was consent obtained?"),67    ("withdrawal_process", "Is there a way to withdraw consent? How?"),68    ("storage", "How is the consent record stored and secured?"),69    ("review_notes", "Any review notes or special considerations?")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        content = "\n".join([f"- **{label}**: {answers.get(key, '')}" for key, label in QUESTIONS])92        lang = detect(content)93        metadata = {94            "user_name": answers.get("user_name", "N/A"),95            "user_role": answers.get("user_role", "N/A"),96            "organization_name": answers.get("organization_name", "N/A"),97            "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")98        }99 100        pdf_path = export_text_to_pdf(content, metadata=metadata, language=lang)101        return "✅ Consent record completed. Download your PDF below.", {"done": True}, pdf_path102 103    with gr.Blocks(title="Consent Management Tool") as demo:104        chatbot = gr.Chatbot(label="✅ Consent Management Assistant", value=[{"role": "assistant", "content": QUESTIONS[0][1]}], type="messages")105        msg = gr.Textbox(label="Your answer")106        state_var = gr.State(state)107        file_output = gr.File(label="Download PDF")108        reset_btn = gr.Button("🔁 Restart")109 110        def chat_logic(msg_in, state_in):111            reply, updated_state, file = step_by_step_agent(msg_in, state_in)112            messages = [{"role": "user", "content": msg_in}]113            if reply:114                messages.append({"role": "assistant", "content": reply})115            return messages, updated_state, file116 117        def reset():118            return [{"role": "assistant", "content": QUESTIONS[0][1]}], {"step": 0, "answers": {}}, None119 120        msg.submit(chat_logic, [msg, state_var], [chatbot, state_var, file_output])121        reset_btn.click(reset, outputs=[chatbot, state_var, file_output])122 123    demo.launch(show_api=False)124