Dave67350 commited on
Commit
0c4ab12
·
verified ·
1 Parent(s): b38b02c

Create post_market_monitoring.py

Browse files
Files changed (1) hide show
  1. tools/post_market_monitoring.py +129 -0
tools/post_market_monitoring.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # tools/post_market_monitoring.py
2
+ import datetime
3
+ import re
4
+ from fpdf import FPDF
5
+ from langdetect import detect
6
+ import gradio as gr
7
+
8
+ # === PDF Export ===
9
+ def export_text_to_pdf(text, output_path=None, language="en"):
10
+ if output_path is None:
11
+ timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
12
+ output_path = f"post_market_monitoring_{timestamp}.pdf"
13
+
14
+ pdf = FPDF()
15
+ pdf.add_page()
16
+ pdf.set_auto_page_break(auto=True, margin=15)
17
+
18
+ pdf.set_font("Arial", 'B', 16)
19
+ pdf.set_text_color(0, 51, 102)
20
+ title = "Post-Market Monitoring Plan (AI Act - Art. 61)" if language == "en" else "Plan de surveillance post-marché (AI Act)"
21
+ pdf.cell(0, 15, title, ln=True, align='C')
22
+ pdf.ln(10)
23
+
24
+ pdf.set_font("Arial", '', 12)
25
+ pdf.set_text_color(0, 0, 0)
26
+ for line in text.strip().split('\n'):
27
+ line = line.strip()
28
+ if line.startswith("## "):
29
+ section = line.replace("## ", "").strip()
30
+ pdf.set_font("Arial", 'B', 13)
31
+ pdf.set_text_color(30, 30, 120)
32
+ pdf.ln(8)
33
+ pdf.cell(0, 10, section, ln=True)
34
+ pdf.set_font("Arial", '', 12)
35
+ pdf.set_text_color(0, 0, 0)
36
+ elif line.startswith("- **"):
37
+ match = re.match(r"- \*\*(.+?)\*\*: (.+)", line)
38
+ if match:
39
+ label, value = match.groups()
40
+ pdf.set_font("Arial", 'B', 12)
41
+ pdf.cell(0, 10, f"{label}:", ln=True)
42
+ pdf.set_font("Arial", '', 12)
43
+ pdf.multi_cell(0, 10, value)
44
+ elif line == "---":
45
+ pdf.line(10, pdf.get_y(), 200, pdf.get_y())
46
+ pdf.ln(5)
47
+ else:
48
+ pdf.multi_cell(0, 10, line)
49
+ pdf.output(output_path)
50
+ return output_path
51
+
52
+ # === Questions ===
53
+ QUESTIONS = [
54
+ ("system_name", "What is the name of the AI system being monitored?"),
55
+ ("monitoring_objectives", "What are the main objectives of post-market monitoring?"),
56
+ ("monitoring_process", "Describe the process for collecting post-market data."),
57
+ ("responsible_roles", "Who is responsible for carrying out the monitoring?"),
58
+ ("data_sources", "What data sources will be used (logs, feedback, etc.)?"),
59
+ ("trigger_events", "What events will trigger a review or investigation?"),
60
+ ("frequency", "How frequently will monitoring activities take place?"),
61
+ ("corrective_actions", "How will issues identified be addressed or escalated?"),
62
+ ("documentation", "How will monitoring activities be documented and stored?"),
63
+ ("update_strategy", "How will monitoring findings be used to update the system?")
64
+ ]
65
+
66
+ def get_questions():
67
+ return QUESTIONS
68
+
69
+ # === Run tool for integration ===
70
+ def run_tool():
71
+ state = {"step": 0, "answers": {}}
72
+
73
+ def step_by_step_agent(user_input, state):
74
+ step = state["step"]
75
+ answers = state["answers"]
76
+
77
+ if step > 0:
78
+ key, _ = QUESTIONS[step - 1]
79
+ answers[key] = user_input
80
+
81
+ if step < len(QUESTIONS):
82
+ next_question = QUESTIONS[step][1]
83
+ state["step"] += 1
84
+ return next_question, state, None
85
+
86
+ # Final format
87
+ content = f"""
88
+ # Post-Market Monitoring Plan
89
+ ## System Overview
90
+ - **System Name**: {answers.get('system_name', '')}
91
+ ## Monitoring Strategy
92
+ - **Objectives**: {answers.get('monitoring_objectives', '')}
93
+ - **Process**: {answers.get('monitoring_process', '')}
94
+ - **Responsible Roles**: {answers.get('responsible_roles', '')}
95
+ - **Data Sources**: {answers.get('data_sources', '')}
96
+ - **Trigger Events**: {answers.get('trigger_events', '')}
97
+ - **Frequency**: {answers.get('frequency', '')}
98
+ ## Response & Documentation
99
+ - **Corrective Actions**: {answers.get('corrective_actions', '')}
100
+ - **Documentation Approach**: {answers.get('documentation', '')}
101
+ - **Update Strategy**: {answers.get('update_strategy', '')}
102
+ ---
103
+ Generated by AI Act Assistant.
104
+ """
105
+ lang = detect(content)
106
+ pdf_path = export_text_to_pdf(content, language=lang)
107
+ return "✅ Plan completed. Download your PDF below.", {"done": True}, pdf_path
108
+
109
+ with gr.Blocks(title="Post-Market Monitoring Tool") as demo:
110
+ chatbot = gr.Chatbot(label="📡 Monitoring Assistant", value=[{"role": "assistant", "content": QUESTIONS[0][1]}], type="messages")
111
+ msg = gr.Textbox(label="Your answer")
112
+ state_var = gr.State(state)
113
+ file_output = gr.File(label="Download PDF")
114
+ reset_btn = gr.Button("🔁 Restart")
115
+
116
+ def chat_logic(msg_in, state_in):
117
+ reply, updated_state, file = step_by_step_agent(msg_in, state_in)
118
+ messages = [{"role": "user", "content": msg_in}]
119
+ if reply:
120
+ messages.append({"role": "assistant", "content": reply})
121
+ return messages, updated_state, file
122
+
123
+ def reset():
124
+ return [{"role": "assistant", "content": QUESTIONS[0][1]}], {"step": 0, "answers": {}}, None
125
+
126
+ msg.submit(chat_logic, [msg, state_var], [chatbot, state_var, file_output])
127
+ reset_btn.click(reset, outputs=[chatbot, state_var, file_output])
128
+
129
+ demo.launch()