Dave67350 commited on
Commit
7bcbd43
·
verified ·
1 Parent(s): 8412cb4

Create high_risk_ai_register.py

Browse files
Files changed (1) hide show
  1. tools/high_risk_ai_register.py +151 -0
tools/high_risk_ai_register.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ import csv
4
+ import datetime
5
+ import os
6
+ import re
7
+ from fpdf import FPDF
8
+ import gradio as gr
9
+ from langdetect import detect
10
+
11
+ # === PDF Export Function ===
12
+ def export_text_to_pdf(text, output_path=None, language="en"):
13
+ if output_path is None:
14
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
15
+ output_path = f"high_risk_ai_summary_{timestamp}.pdf"
16
+
17
+ pdf = FPDF()
18
+ pdf.add_page()
19
+ pdf.set_auto_page_break(auto=True, margin=15)
20
+
21
+ # Title
22
+ pdf.set_font("Arial", 'B', 16)
23
+ pdf.set_text_color(0, 51, 102)
24
+ title = "High-Risk AI System Documentation" if language == "en" else "Documentation des Systèmes IA à Haut Risque"
25
+ pdf.cell(0, 15, title, ln=True, align='C')
26
+ pdf.ln(10)
27
+
28
+ # Subtitle
29
+ pdf.set_font("Arial", 'I', 12)
30
+ pdf.set_text_color(90, 90, 90)
31
+ subtitle = f"Generated on {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
32
+ pdf.cell(0, 10, subtitle, ln=True, align='C')
33
+ pdf.ln(5)
34
+
35
+ # Content formatting
36
+ pdf.set_font("Arial", '', 12)
37
+ pdf.set_text_color(0, 0, 0)
38
+
39
+ for line in text.strip().split('\n'):
40
+ line = line.strip()
41
+ if line.startswith("## "):
42
+ section_title = line.replace("## ", "").strip()
43
+ pdf.set_font("Arial", 'B', 13)
44
+ pdf.set_text_color(30, 30, 120)
45
+ pdf.ln(8)
46
+ pdf.cell(0, 10, section_title, ln=True)
47
+ pdf.set_font("Arial", '', 12)
48
+ pdf.set_text_color(0, 0, 0)
49
+ elif line.startswith("- **"):
50
+ match = re.match(r"- \*\*(.+?)\*\*: (.+)", line)
51
+ if match:
52
+ label, answer = match.groups()
53
+ pdf.set_font("Arial", 'B', 12)
54
+ pdf.cell(0, 10, f"{label}:", ln=True)
55
+ pdf.set_font("Arial", '', 12)
56
+ pdf.multi_cell(0, 10, f"{answer}")
57
+ elif line == "---":
58
+ pdf.line(10, pdf.get_y(), 200, pdf.get_y())
59
+ pdf.ln(5)
60
+ else:
61
+ pdf.multi_cell(0, 10, line)
62
+ pdf.output(output_path)
63
+ return output_path
64
+
65
+ # === Questions for AI System Documentation ===
66
+ QUESTIONS = [
67
+ ("system_name", "What is the name of your AI system?"),
68
+ ("system_purpose", "What is its intended purpose?"),
69
+ ("category", "Which Annex III category does it fall under?"),
70
+ ("developer", "Who developed it?"),
71
+ ("users", "Who will use it?"),
72
+ ("input_types", "What types of input data does it use?"),
73
+ ("output", "What actions does it perform?"),
74
+ ("dependencies", "List any critical dependencies (e.g., APIs, models)."),
75
+ ("context", "What is the intended deployment environment?"),
76
+ ("justification", "Why is it high-risk under the AI Act?"),
77
+ ]
78
+
79
+ # === Conversation Logic ===
80
+ def step_by_step(user_input, state):
81
+ if state is None:
82
+ state = {"step": 0, "answers": {}}
83
+
84
+ step = state["step"]
85
+ answers = state["answers"]
86
+
87
+ if step > 0:
88
+ key, _ = QUESTIONS[step - 1]
89
+ answers[key] = user_input
90
+
91
+ if step < len(QUESTIONS):
92
+ next_q = QUESTIONS[step][1]
93
+ state["step"] += 1
94
+ return next_q, state, None
95
+
96
+ # === Format document ===
97
+ content = f"""
98
+ # High-Risk AI System Summary
99
+ ## General Info
100
+ - **System Name**: {answers.get('system_name', '')}
101
+ - **Purpose**: {answers.get('system_purpose', '')}
102
+ - **Annex III Category**: {answers.get('category', '')}
103
+ - **Developer**: {answers.get('developer', '')}
104
+ - **Intended Users**: {answers.get('users', '')}
105
+ - **Deployment Context**: {answers.get('context', '')}
106
+
107
+ ## Technical Info
108
+ - **Input Types**: {answers.get('input_types', '')}
109
+ - **System Output**: {answers.get('output', '')}
110
+ - **Dependencies**: {answers.get('dependencies', '')}
111
+
112
+ ## Risk Classification
113
+ - **Justification for High-Risk**: {answers.get('justification', '')}
114
+ ---
115
+ Generated by AI Act Assistant.
116
+ """
117
+
118
+ lang = detect(content)
119
+ pdf_path = export_text_to_pdf(content, language=lang)
120
+
121
+ return f"✅ All data collected!\n📝 Your summary is ready. Click below to download your PDF.", {"done": True}, pdf_path
122
+
123
+ # === Gradio UI ===
124
+ def launch_ui():
125
+ with gr.Blocks(title="High-Risk AI Summary Tool") as demo:
126
+ chatbot = gr.Chatbot(label="🛡️ High-Risk AI Summary Assistant")
127
+ user_input = gr.Textbox(placeholder="Your answer...", label="Answer")
128
+ state = gr.State()
129
+ file_output = gr.File(label="Download PDF", visible=True)
130
+ reset_btn = gr.Button("🔁 Start Over")
131
+
132
+ first_q = QUESTIONS[0][1]
133
+ chatbot.value = [gr.ChatMessage(role="assistant", content=first_q)]
134
+
135
+ def run_chat(msg, state):
136
+ reply, state, pdf = step_by_step(msg, state)
137
+ messages = [gr.ChatMessage(role="user", content=msg)]
138
+ if reply:
139
+ messages.append(gr.ChatMessage(role="assistant", content=reply))
140
+ return messages, state, pdf
141
+
142
+ def reset_all():
143
+ return [gr.ChatMessage(role="assistant", content=QUESTIONS[0][1])], {"step": 0, "answers": {}}, None
144
+
145
+ user_input.submit(run_chat, [user_input, state], [chatbot, state, file_output])
146
+ reset_btn.click(reset_all, outputs=[chatbot, state, file_output])
147
+
148
+ demo.launch()
149
+
150
+ if __name__ == "__main__":
151
+ launch_ui()