Dave67350 commited on
Commit
63a54f3
·
verified ·
1 Parent(s): 8e9edf1

Update tools/ai_act_generator.py

Browse files
Files changed (1) hide show
  1. tools/ai_act_generator.py +129 -76
tools/ai_act_generator.py CHANGED
@@ -1,82 +1,135 @@
1
  # NEW TOOL: Generate AI Act Compliance Register
2
  from smolagents import tool
3
 
4
- @tool
5
- def generate_ai_act_register(
6
- organization_name: str,
7
- responsible_person: str,
8
- deployment_date: str,
9
- ai_type: str,
10
- ai_description: str,
11
- risk_level: str,
12
- risk_justification: str,
13
- data_evaluation: str,
14
- technical_docs: str,
15
- human_oversight: str,
16
- transparency_measures: str,
17
- audit_frequency: str,
18
- compliance_contact: str
19
- ) -> str:
20
- """
21
- Génère un registre de conformité AI Act à partir des champs fournis.
22
-
23
- Args:
24
- organization_name: Le nom de l'organisation responsable du système IA.
25
- responsible_person: Le nom de la personne référente.
26
- deployment_date: La date de mise en service du système IA.
27
- ai_type: Le type de système IA (ex: reconnaissance faciale, scoring).
28
- ai_description: Une brève description du système IA.
29
- risk_level: Le niveau de risque (ex: élevé, modéré).
30
- risk_justification: La justification du niveau de risque déclaré.
31
- data_evaluation: Les méthodes utilisées pour évaluer la qualité des données.
32
- technical_docs: La documentation technique disponible.
33
- human_oversight: Le niveau de supervision humaine prévu.
34
- transparency_measures: Les mesures de transparence mises en œuvre.
35
- audit_frequency: La fréquence prévue des audits du système.
36
- compliance_contact: L'email ou contact de la personne en charge de la conformité.
37
-
38
- Returns:
39
- Un texte complet représentant le registre de conformité prêt à être exporté.
40
- """
41
- return f"""
42
- # Registre de Conformité Système d’IA à Haut Risque
43
-
44
- ## Informations générales
45
-
46
- - **Nom de l'organisation** : {organization_name}
47
- - **Responsable du système IA** : {responsible_person}
48
- - **Date de mise en service** : {deployment_date}
49
- - **Description du système IA** :
50
- {ai_description}
51
-
52
- ## Catégorie de risque
53
-
54
- - **Type de système IA** : {ai_type}
55
- - **Risque identifié** : {risk_level}
56
- - **Justification de la classification** :
57
- {risk_justification}
58
-
59
- ## Mesures de conformité appliquées
60
-
61
- - Évaluation des données utilisées :
62
- {data_evaluation}
63
-
64
- - Documentation technique produite :
65
- {technical_docs}
66
-
67
- - Contrôle humain prévu :
68
- {human_oversight}
69
-
70
- - Mécanismes de transparence intégrés :
71
- {transparency_measures}
72
-
73
- ## Audit & révision
74
-
75
- - Fréquence de révision : {audit_frequency}
76
- - Responsable du suivi : {compliance_contact}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
  ---
 
 
79
 
80
- > Document généré automatiquement selon le Règlement AI Act (UE).
81
- > Ce modèle est à valider par un professionnel du droit selon le contexte d’usage.
82
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # NEW TOOL: Generate AI Act Compliance Register
2
  from smolagents import tool
3
 
4
+ #!/usr/bin/env python
5
+ # coding=utf-8
6
+ import mimetypes
7
+ import os
8
+ import re
9
+ import shutil
10
+ from typing import Optional
11
+
12
+ from smolagents.agent_types import AgentAudio, AgentImage, AgentText, handle_agent_output_types
13
+ from smolagents.agents import ActionStep, MultiStepAgent
14
+ from smolagents.memory import MemoryStep
15
+ from smolagents.utils import _is_package_available
16
+
17
+ import gradio as gr
18
+ from fpdf import FPDF
19
+ from langdetect import detect
20
+
21
+ # === PDF Export Function with Language Option ===
22
+ def export_text_to_pdf(text, output_path="ai_act_register.pdf", language="fr"):
23
+ pdf = FPDF()
24
+ pdf.add_page()
25
+ pdf.set_auto_page_break(auto=True, margin=15)
26
+ pdf.set_font("Arial", size=12)
27
+
28
+ title = "AI Act Compliance Register" if language == "en" else "Registre de Conformité AI Act"
29
+ pdf.set_font("Arial", 'B', 14)
30
+ pdf.cell(0, 10, title, ln=True)
31
+ pdf.ln(10)
32
+ pdf.set_font("Arial", size=12)
33
+
34
+ for line in text.split('\n'):
35
+ pdf.multi_cell(0, 10, line)
36
+
37
+ pdf.output(output_path)
38
+ return output_path
39
+
40
+ # === Sequential Questions ===
41
+ QUESTIONS = [
42
+ ("organization_name", "What is the name of your organization?"),
43
+ ("responsible_person", "Who is responsible for this AI system?"),
44
+ ("deployment_date", "When is the AI system scheduled to be deployed?"),
45
+ ("ai_type", "What type of AI system is it?"),
46
+ ("ai_description", "Please briefly describe what the system does."),
47
+ ("risk_level", "What is the risk level of this system (e.g., high, medium)?"),
48
+ ("risk_justification", "Why do you consider it this risk level?"),
49
+ ("data_evaluation", "How have you evaluated the training data?"),
50
+ ("technical_docs", "What technical documentation is available?"),
51
+ ("human_oversight", "What kind of human oversight is planned?"),
52
+ ("transparency_measures", "What transparency mechanisms are in place?"),
53
+ ("audit_frequency", "How often will the system be audited?"),
54
+ ("compliance_contact", "Who is the contact person for compliance (email or name)?")
55
+ ]
56
+
57
+ RESPONSES = {}
58
+
59
+ # === Interactive Collection Flow ===
60
+ def step_by_step_agent(user_input, state):
61
+ if state is None:
62
+ state = {"step": 0, "answers": {}}
63
+
64
+ step = state["step"]
65
+ answers = state["answers"]
66
+
67
+ # Save answer from previous step
68
+ if step > 0:
69
+ key, _ = QUESTIONS[step - 1]
70
+ answers[key] = user_input
71
+
72
+ # If more questions to ask
73
+ if step < len(QUESTIONS):
74
+ next_question = QUESTIONS[step][1]
75
+ state["step"] += 1
76
+ return next_question, state
77
+
78
+ # All questions answered, generate document
79
+ filled_template = f"""
80
+ # AI Act Compliance Register
81
+
82
+ ## General Information
83
+ - **Organization**: {answers['organization_name']}
84
+ - **Responsible Person**: {answers['responsible_person']}
85
+ - **Deployment Date**: {answers['deployment_date']}
86
+ - **System Description**: {answers['ai_description']}
87
+
88
+ ## Risk Category
89
+ - **Type**: {answers['ai_type']}
90
+ - **Risk Level**: {answers['risk_level']}
91
+ - **Justification**: {answers['risk_justification']}
92
+
93
+ ## Compliance Measures
94
+ - **Data Evaluation**: {answers['data_evaluation']}
95
+ - **Technical Docs**: {answers['technical_docs']}
96
+ - **Human Oversight**: {answers['human_oversight']}
97
+ - **Transparency Measures**: {answers['transparency_measures']}
98
+
99
+ ## Audit & Follow-up
100
+ - **Audit Frequency**: {answers['audit_frequency']}
101
+ - **Compliance Contact**: {answers['compliance_contact']}
102
 
103
  ---
104
+ Generated by AI Act Assistant.
105
+ """
106
 
107
+ pdf_path = export_text_to_pdf(filled_template, language="en")
108
+ return f"✅ All answers received. Download your AI Act compliance PDF below.", {"done": True, "pdf": pdf_path}
109
+
110
+ # === UI for Step-by-Step Form ===
111
+ def launch_step_by_step_ui():
112
+ with gr.Blocks(fill_height=True) as demo:
113
+ chatbot = gr.Chatbot()
114
+ msg = gr.Textbox(label="Your answer")
115
+ state = gr.State()
116
+ file_output = gr.File(visible=False)
117
+
118
+ def chat_logic(user_msg, state):
119
+ reply, state = step_by_step_agent(user_msg, state)
120
+ messages = [gr.ChatMessage(role="user", content=user_msg)]
121
+
122
+ if isinstance(reply, str):
123
+ messages.append(gr.ChatMessage(role="assistant", content=reply))
124
+
125
+ outputs = {"chatbot": messages, "state": state}
126
+ if isinstance(state, dict) and state.get("done"):
127
+ outputs["file_output"] = state["pdf"]
128
+ return outputs
129
+
130
+ msg.submit(chat_logic, [msg, state], [chatbot, state, file_output])
131
+
132
+ demo.launch()
133
+
134
+ if __name__ == "__main__":
135
+ launch_step_by_step_ui()