-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreport_generator.py
More file actions
354 lines (304 loc) · 12.1 KB
/
Copy pathreport_generator.py
File metadata and controls
354 lines (304 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
"""
PDF Report Generator for Multiple Disease Prediction System.
"""
from datetime import datetime
from typing import Dict, List, Any, Optional
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter, A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus import (
SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
PageBreak, Image, ListFlowable, ListItem
)
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY
import io
def generate_prediction_report(
disease_type: str,
inputs: Dict[str, float],
prediction: str,
probability: float,
risk_level: str,
risk_color: str,
recommendations: List[str],
feature_importance: Optional[Dict[str, float]] = None
) -> bytes:
"""
Generate a comprehensive PDF report for a prediction.
Returns:
PDF content as bytes
"""
buffer = io.BytesIO()
doc = SimpleDocTemplate(
buffer,
pagesize=A4,
rightMargin=0.75*inch,
leftMargin=0.75*inch,
topMargin=0.75*inch,
bottomMargin=0.75*inch
)
# Container for the 'Flowable' objects
elements = []
# Styles
styles = getSampleStyleSheet()
title_style = ParagraphStyle(
'CustomTitle',
parent=styles['Heading1'],
fontSize=24,
textColor=colors.HexColor('#2c3e50'),
spaceAfter=30,
alignment=TA_CENTER,
fontName='Helvetica-Bold'
)
heading_style = ParagraphStyle(
'CustomHeading',
parent=styles['Heading2'],
fontSize=14,
textColor=colors.HexColor('#667eea'),
spaceAfter=12,
spaceBefore=12,
fontName='Helvetica-Bold'
)
normal_style = ParagraphStyle(
'CustomNormal',
parent=styles['Normal'],
fontSize=10,
textColor=colors.HexColor('#2c3e50'),
spaceAfter=6,
alignment=TA_JUSTIFY
)
# Header
elements.append(Paragraph("🏥 Advanced Health Assistant AI", title_style))
elements.append(Paragraph("Disease Prediction Report", heading_style))
elements.append(Spacer(1, 0.2*inch))
# Report metadata
meta_data = [
['Report Generated:', datetime.now().strftime("%Y-%m-%d %H:%M:%S")],
['Disease Type:', disease_type.title()],
['Prediction ID:', f"PRED-{datetime.now().strftime('%Y%m%d%H%M%S')}"],
]
meta_table = Table(meta_data, colWidths=[2*inch, 4*inch])
meta_table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (0, -1), colors.HexColor('#f8f9fa')),
('TEXTCOLOR', (0, 0), (0, -1), colors.HexColor('#2c3e50')),
('ALIGN', (0, 0), (-1, -1), 'LEFT'),
('FONTNAME', (0, 0), (0, -1), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, -1), 10),
('GRID', (0, 0), (-1, -1), 0.5, colors.HexColor('#dee2e6')),
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
('PADDING', (0, 0), (-1, -1), 8),
]))
elements.append(meta_table)
elements.append(Spacer(1, 0.3*inch))
# Prediction Result Section
elements.append(Paragraph("📊 Prediction Result", heading_style))
# Risk level color mapping
risk_color_map = {
"Low Risk": colors.HexColor('#2ed573'),
"Moderate Risk": colors.HexColor('#ffa502'),
"High Risk": colors.HexColor('#ff4757'),
}
result_color = risk_color_map.get(risk_level, colors.HexColor('#667eea'))
result_data = [
['Prediction Result:', prediction],
['Confidence Level:', f"{probability:.1%}"],
['Risk Assessment:', risk_level],
]
result_table = Table(result_data, colWidths=[2*inch, 4*inch])
result_table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (0, -1), colors.HexColor('#f8f9fa')),
('TEXTCOLOR', (0, 0), (0, -1), colors.HexColor('#2c3e50')),
('ALIGN', (0, 0), (-1, -1), 'LEFT'),
('FONTNAME', (0, 0), (0, -1), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, -1), 11),
('BACKGROUND', (1, 2), (1, 2), result_color),
('TEXTCOLOR', (1, 2), (1, 2), colors.white),
('FONTNAME', (1, 2), (1, 2), 'Helvetica-Bold'),
('GRID', (0, 0), (-1, -1), 0.5, colors.HexColor('#dee2e6')),
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
('PADDING', (0, 0), (-1, -1), 10),
]))
elements.append(result_table)
elements.append(Spacer(1, 0.3*inch))
# Input Parameters Section
elements.append(Paragraph("📋 Input Parameters", heading_style))
input_data = [['Parameter', 'Value']]
for param, value in inputs.items():
input_data.append([param, f"{value:.4f}" if isinstance(value, float) else str(value)])
input_table = Table(input_data, colWidths=[3*inch, 3*inch])
input_table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#667eea')),
('TEXTCOLOR', (0, 0), (-1, 0), colors.white),
('ALIGN', (0, 0), (-1, -1), 'LEFT'),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, 0), 11),
('BACKGROUND', (0, 1), (-1, -1), colors.HexColor('#f8f9fa')),
('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.HexColor('#f8f9fa')]),
('GRID', (0, 0), (-1, -1), 0.5, colors.HexColor('#dee2e6')),
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
('PADDING', (0, 0), (-1, -1), 6),
]))
elements.append(input_table)
elements.append(Spacer(1, 0.3*inch))
# Feature Importance Section (if available)
if feature_importance:
elements.append(Paragraph("🔍 Key Contributing Factors", heading_style))
sorted_features = sorted(feature_importance.items(), key=lambda x: x[1], reverse=True)[:5]
feature_data = [['Factor', 'Importance']]
for feature, importance in sorted_features:
feature_data.append([feature, f"{importance:.1%}"])
feature_table = Table(feature_data, colWidths=[4*inch, 2*inch])
feature_table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#667eea')),
('TEXTCOLOR', (0, 0), (-1, 0), colors.white),
('ALIGN', (0, 0), (0, -1), 'LEFT'),
('ALIGN', (1, 0), (1, -1), 'CENTER'),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, 0), 11),
('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.HexColor('#f8f9fa')]),
('GRID', (0, 0), (-1, -1), 0.5, colors.HexColor('#dee2e6')),
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
('PADDING', (0, 0), (-1, -1), 6),
]))
elements.append(feature_table)
elements.append(Spacer(1, 0.3*inch))
# Recommendations Section
elements.append(Paragraph("💡 Health Recommendations", heading_style))
rec_items = []
for i, rec in enumerate(recommendations, 1):
rec_items.append(ListItem(Paragraph(rec, normal_style), bulletColor=result_color))
rec_list = ListFlowable(rec_items, bulletType='1', start=1)
elements.append(rec_list)
elements.append(Spacer(1, 0.3*inch))
# Disclaimer
elements.append(Spacer(1, 0.2*inch))
disclaimer_style = ParagraphStyle(
'Disclaimer',
parent=styles['Normal'],
fontSize=9,
textColor=colors.HexColor('#7f8c8d'),
alignment=TA_JUSTIFY,
fontName='Helvetica-Oblique'
)
disclaimer_text = """
<b>Disclaimer:</b> This prediction report is generated by an AI-based system for educational
and informational purposes only. It should NOT be considered as a substitute for professional
medical advice, diagnosis, or treatment. Always seek the guidance of qualified healthcare
providers with any questions you may have regarding your health condition. Never disregard
professional medical advice because of information you have received from this system.
"""
elements.append(Paragraph(disclaimer_text, disclaimer_style))
# Build PDF
doc.build(elements)
# Get the value of the BytesIO buffer
pdf = buffer.getvalue()
buffer.close()
return pdf
def generate_batch_report(
disease_type: str,
predictions: List[Dict[str, Any]]
) -> bytes:
"""
Generate a batch prediction report.
Returns:
PDF content as bytes
"""
buffer = io.BytesIO()
doc = SimpleDocTemplate(
buffer,
pagesize=A4,
rightMargin=0.75*inch,
leftMargin=0.75*inch,
topMargin=0.75*inch,
bottomMargin=0.75*inch
)
elements = []
styles = getSampleStyleSheet()
title_style = ParagraphStyle(
'CustomTitle',
parent=styles['Heading1'],
fontSize=20,
textColor=colors.HexColor('#2c3e50'),
spaceAfter=20,
alignment=TA_CENTER,
fontName='Helvetica-Bold'
)
heading_style = ParagraphStyle(
'CustomHeading',
parent=styles['Heading2'],
fontSize=14,
textColor=colors.HexColor('#667eea'),
spaceAfter=12,
spaceBefore=12,
fontName='Helvetica-Bold'
)
# Header
elements.append(Paragraph("🏥 Advanced Health Assistant AI", title_style))
elements.append(Paragraph(f"Batch Prediction Report - {disease_type.title()}", heading_style))
elements.append(Spacer(1, 0.2*inch))
# Summary statistics
total = len(predictions)
positive = sum(1 for p in predictions if p['prediction'] == 'Positive')
negative = total - positive
summary_data = [
['Report Generated:', datetime.now().strftime("%Y-%m-%d %H:%M:%S")],
['Total Predictions:', str(total)],
['Positive Cases:', str(positive)],
['Negative Cases:', str(negative)],
]
summary_table = Table(summary_data, colWidths=[2.5*inch, 3.5*inch])
summary_table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (0, -1), colors.HexColor('#f8f9fa')),
('TEXTCOLOR', (0, 0), (0, -1), colors.HexColor('#2c3e50')),
('ALIGN', (0, 0), (-1, -1), 'LEFT'),
('FONTNAME', (0, 0), (0, -1), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, -1), 10),
('GRID', (0, 0), (-1, -1), 0.5, colors.HexColor('#dee2e6')),
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
('PADDING', (0, 0), (-1, -1), 8),
]))
elements.append(summary_table)
elements.append(Spacer(1, 0.3*inch))
# Predictions table
elements.append(Paragraph("📊 Prediction Results", heading_style))
pred_data = [['#', 'Prediction', 'Confidence', 'Risk Level']]
for i, pred in enumerate(predictions[:50], 1): # Limit to 50 rows
pred_data.append([
str(i),
pred['prediction'],
f"{pred['probability']:.1f}%",
pred['risk_level']
])
pred_table = Table(pred_data, colWidths=[0.5*inch, 1.5*inch, 1.5*inch, 2*inch])
pred_table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#667eea')),
('TEXTCOLOR', (0, 0), (-1, 0), colors.white),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, 0), 10),
('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.HexColor('#f8f9fa')]),
('GRID', (0, 0), (-1, -1), 0.5, colors.HexColor('#dee2e6')),
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
('PADDING', (0, 0), (-1, -1), 5),
]))
elements.append(pred_table)
# Disclaimer
elements.append(Spacer(1, 0.3*inch))
disclaimer_style = ParagraphStyle(
'Disclaimer',
parent=styles['Normal'],
fontSize=9,
textColor=colors.HexColor('#7f8c8d'),
alignment=TA_JUSTIFY,
fontName='Helvetica-Oblique'
)
disclaimer_text = """
<b>Disclaimer:</b> This batch prediction report is generated by an AI-based system for
educational purposes only. Always consult qualified healthcare professionals for medical decisions.
"""
elements.append(Paragraph(disclaimer_text, disclaimer_style))
# Build PDF
doc.build(elements)
pdf = buffer.getvalue()
buffer.close()
return pdf