CoolFace
Apppublic

Dave67350/First_agent_template

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
dma_data_sharing_record.py125 linesDownload Raw Back to tools
1# tools/dma_data_sharing_record.py2 3import 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"data_sharing_record_{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 = "Data Sharing Record (DMA)" if language == "en" else "Registre de Partage de Données (DMA)"23    pdf.cell(0, 15, title, ln=True, align='C')24    pdf.ln(10)25 26    # Metadata27    if metadata:28        pdf.set_font("Arial", '', 12)29        pdf.set_text_color(90, 90, 90)30        pdf.multi_cell(0, 10, f"Organization: {metadata.get('organization', 'N/A')}")31        pdf.multi_cell(0, 10, f"Completed by: {metadata.get('name', 'N/A')} ({metadata.get('role', 'N/A')})")32        pdf.multi_cell(0, 10, f"Timestamp: {metadata.get('timestamp', 'N/A')}")33        pdf.ln(5)34 35    # Body content36    pdf.set_font("Arial", '', 12)37    pdf.set_text_color(0, 0, 0)38    for line in text.strip().split('\n'):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        elif line == "---":56            pdf.line(10, pdf.get_y(), 200, pdf.get_y())57            pdf.ln(5)58        else:59            pdf.multi_cell(0, 10, line)60 61    pdf.output(output_path)62    return output_path63 64# === Questions ===65QUESTIONS = prepend_metadata_questions([66    ("shared_data_types", "What types of data are shared with third parties?"),67    ("sharing_purpose", "What is the purpose for sharing this data?"),68    ("recipients", "Who are the recipients of the shared data?"),69    ("legal_basis", "What is the legal basis for sharing this data under the DMA?"),70    ("user_consent", "Is user consent obtained for sharing? If so, how?"),71    ("access_controls", "What access controls are in place to protect the shared data?"),72    ("audit_logs", "How are data sharing activities logged and monitored?"),73])74 75def get_questions():76    return QUESTIONS77 78# === Tool Execution ===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        if step < len(QUESTIONS):89            next_question = QUESTIONS[step][1]90            state["step"] += 191            return next_question, state, None92 93        content = "\n".join([f"- **{label}**: {answers.get(key, '')}" for key, label in QUESTIONS])94        lang = detect(content) if len(content.strip()) > 3 else "en"95        metadata = {96            "organization": answers.get("organization_name", "N/A"),97            "name": answers.get("user_name", "N/A"),98            "role": answers.get("user_role", "N/A"),99            "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")100        }101        pdf_path = export_text_to_pdf(content, metadata=metadata, language=lang)102        return "✅ Data Sharing Record completed. Download your PDF below.", {"done": True}, pdf_path103 104    with gr.Blocks(title="DMA Data Sharing Tool") as demo:105        chatbot = gr.Chatbot(label="🔄 DMA Data Sharing 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