CoolFace
Apppublic

Dave67350/First_agent_template

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
ai_act_generator.py180 linesDownload Raw Back to tools
1#!/usr/bin/env python2# coding=utf-83import csv4import datetime5import os6import re7from fpdf import FPDF8from langdetect import detect9 10import gradio as gr11from tools.common import prepend_metadata_questions12 13# === PDF Export Function with Language Option ===14def export_text_to_pdf(text, answers, output_path=None, language="fr"):15    if output_path is None:16        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")17        output_path = f"ai_act_register_{timestamp}.pdf"18 19    pdf = FPDF()20    pdf.add_page()21    pdf.set_auto_page_break(auto=True, margin=15)22 23    # Title24    pdf.set_font("Arial", 'B', 16)25    pdf.set_text_color(0, 51, 102)26    title = "Documentation Record for High-Risk AI Systems" if language == "en" else "Registre de Conformité AI Act"27    pdf.cell(0, 15, title, ln=True, align='C')28    pdf.ln(5)29 30    # Metadata below title31    pdf.set_font("Arial", 'I', 11)32    pdf.set_text_color(80, 80, 80)33    name = answers.get("user_name", "N/A")34    role = answers.get("user_role", "N/A")35    org = answers.get("organization_name", "N/A")36    timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')37    pdf.multi_cell(0, 10, f"Completed by {name} ({role}) at {org} on {timestamp}", align="C")38    pdf.ln(5)39 40    # Content41    pdf.set_font("Arial", '', 12)42    pdf.set_text_color(0, 0, 0)43    for line in text.strip().split('\n'):44        line = line.strip()45        if line.startswith("## "):46            section_title = line.replace("## ", "").strip()47            pdf.set_font("Arial", 'B', 13)48            pdf.set_text_color(30, 30, 120)49            pdf.ln(8)50            pdf.cell(0, 10, section_title, ln=True)51            pdf.set_font("Arial", '', 12)52            pdf.set_text_color(0, 0, 0)53        elif line.startswith("- **"):54            match = re.match(r"- \*\*(.+?)\*\*: (.+)", line)55            if match:56                label, value = match.groups()57                pdf.set_font("Arial", 'B', 12)58                pdf.cell(0, 10, f"{label}:", ln=True)59                pdf.set_font("Arial", '', 12)60                pdf.multi_cell(0, 10, value)61                pdf.ln(2)62        elif line == "---":63            pdf.line(10, pdf.get_y(), 200, pdf.get_y())64            pdf.ln(5)65        else:66            pdf.multi_cell(0, 10, line)67            pdf.ln(2)68 69    pdf.output(output_path)70    return output_path71 72# === Sequential Questions ===73QUESTIONS = prepend_metadata_questions([74    ("responsible_person", "Who is responsible for this AI system?"),75    ("deployment_date", "When is the AI system scheduled to be deployed?"),76    ("ai_type", "What type of AI system is it?"),77    ("ai_description", "Please briefly describe what the system does."),78    ("risk_level", "What is the risk level of this system (e.g., high, medium)?"),79    ("risk_justification", "Why do you consider it this risk level?"),80    ("data_evaluation", "How have you evaluated the training data?"),81    ("technical_docs", "What technical documentation is available?"),82    ("human_oversight", "What kind of human oversight is planned?"),83    ("transparency_measures", "What transparency mechanisms are in place?"),84    ("audit_frequency", "How often will the system be audited?"),85    ("compliance_contact", "Who is the contact person for compliance (email or name)?")86])87 88# === Interactive Collection Flow ===89def step_by_step_agent(user_input, state):90    if state is None:91        state = {"step": 0, "answers": {}}92 93    step = state["step"]94    answers = state["answers"]95 96    if step > 0:97        key, _ = QUESTIONS[step - 1]98        answers[key] = user_input99 100    if step < len(QUESTIONS):101        next_q = QUESTIONS[step][1]102        state["step"] += 1103        return next_q, state, None104 105    # Build filled template106    filled = f"""107# AI Act Compliance Register108 109## General Information110- **Responsible Person**: {answers['responsible_person']}111- **Deployment Date**: {answers['deployment_date']}112- **System Description**: {answers['ai_description']}113 114## Risk Category115- **Type**: {answers['ai_type']}116- **Risk Level**: {answers['risk_level']}117- **Justification**: {answers['risk_justification']}118 119## Compliance Measures120- **Data Evaluation**: {answers['data_evaluation']}121- **Technical Docs**: {answers['technical_docs']}122- **Human Oversight**: {answers['human_oversight']}123- **Transparency Measures**: {answers['transparency_measures']}124 125## Audit & Follow-up126- **Audit Frequency**: {answers['audit_frequency']}127- **Compliance Contact**: {answers['compliance_contact']}128 129---130Generated by AI Act Assistant.131"""132 133    detected_lang = detect(filled) if filled.strip() else "en"134 135    csv_file = "ai_act_registers.csv"136    fieldnames = [key for key, _ in QUESTIONS] + ["timestamp"]137    row_data = {**answers, "timestamp": datetime.datetime.now().isoformat()}138    file_exists = os.path.isfile(csv_file)139 140    with open(csv_file, mode="a", newline="", encoding="utf-8") as f:141        writer = csv.DictWriter(f, fieldnames=fieldnames)142        if not file_exists:143            writer.writeheader()144        writer.writerow(row_data)145 146    pdf_path = export_text_to_pdf(filled, answers, language=detected_lang)147    return f"✅ Your PDF is ready for download.", {"done": True, "pdf": pdf_path}, pdf_path148 149# === Gradio Interface ===150def launch_step_by_step_ui():151    with gr.Blocks(title="AI Act Assistant", css="""footer, a[href*="gradio.app"], a[href*="huggingface.co"] { display: none !important; }""") as demo:152        gr.Markdown("### 🔒 GDPR Notice\nThis assistant does not store personal data. Use responsibly.")153        chatbot = gr.Chatbot(type="messages", value=[])154        msg = gr.Textbox(label="Your answer")155        state = gr.State()156        file_output = gr.File(label="Download PDF", visible=True)157        restart = gr.Button("🔁 Restart")158 159        def chat_logic(user_msg, state):160            reply, updated_state, file_path = step_by_step_agent(user_msg, state)161            messages = [gr.ChatMessage(role="user", content=user_msg)]162            if isinstance(reply, str):163                messages.append(gr.ChatMessage(role="assistant", content=reply))164            return messages, updated_state, file_path if file_path else None165 166        def reset():167            first_q = QUESTIONS[0][1]168            return [gr.ChatMessage(role="assistant", content=f"👋 Let's get started.\n\n{first_q}")], {"step": 0, "answers": {}}, None169 170        msg.submit(chat_logic, [msg, state], [chatbot, state, file_output])171        restart.click(reset, outputs=[chatbot, state, file_output])172 173    demo.launch(show_api=False)174 175def get_questions():176    return QUESTIONS177 178def run_tool():179    return launch_step_by_step_ui()180