/
html_report.py
294 lines (233 loc) · 8.69 KB
/
html_report.py
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
"""Generate HTML reports."""
import copy
import os
import warnings
from pathlib import Path
from string import Template
from nilearn.externals import tempita
from nilearn.plotting.html_document import HTMLDocument
from nilearn.reporting.utils import figure_to_svg_base64
ESTIMATOR_TEMPLATES = {
'NiftiLabelsMasker': 'report_body_template_niftilabelsmasker.html',
'NiftiMapsMasker': 'report_body_template_niftimapsmasker.html',
'default': 'report_body_template.html'}
def _get_estimator_template(estimator):
"""Return the HTML template to use for a given estimator \
if a specific template was defined in ESTIMATOR_TEMPLATES, \
otherwise return the default template.
Parameters
----------
estimator : object instance of BaseEstimator
The object we wish to retrieve template of.
Returns
-------
template : str
Name of the template file to use.
"""
if estimator.__class__.__name__ in ESTIMATOR_TEMPLATES:
return ESTIMATOR_TEMPLATES[estimator.__class__.__name__]
else:
return ESTIMATOR_TEMPLATES['default']
def _embed_img(display):
"""Embed an image or just return its instance if already embedded.
Parameters
----------
display : obj
A Nilearn plotting object to display.
Returns
-------
embed : str
Binary image string.
"""
if display is None: # no image to display
return None
# If already embedded, simply return as is
if isinstance(display, str):
return display
return figure_to_svg_base64(display.frame_axes.figure)
def _str_params(params):
"""Convert NoneType values to the string 'None' for display.
Parameters
----------
params : dict
A dictionary of input values to a function.
"""
params_str = copy.deepcopy(params)
for k, v in params_str.items():
if v is None:
params_str[k] = 'None'
return params_str
def _update_template(title, docstring, content, overlay,
parameters, data, template_name=None):
"""Populate a report with content.
Parameters
----------
title : str
The title for the report.
docstring : str
The introductory docstring for the reported object.
content : img
The content to display.
overlay : img
Overlaid content, to appear on hover.
parameters : dict
A dictionary of object parameters and their values.
data : dict
A dictionary holding the data to be added to the report.
The keys must match exactly the ones used in the template.
The default template accepts the following:
- description (str) : Description of the content.
- warning_message (str) : An optional warning
message to be displayed in red. This is used
for example when no image was provided to the
estimator when fitting.
The NiftiLabelsMasker template accepts the additional
fields:
- summary (dict) : A summary description of the
region labels and sizes. This will be displayed
as an expandable table in the report.
template_name : str, optional
The name of the template to use. If not provided, the
default template `report_body_template.html` will be
used.
Returns
-------
report : HTMLReport
An instance of a populated HTML report.
"""
resource_path = Path(__file__).resolve().parent.joinpath('data', 'html')
if template_name is None:
body_template_name = 'report_body_template.html'
else:
body_template_name = template_name
body_template_path = resource_path.joinpath(body_template_name)
if not os.path.exists(str(body_template_path)):
raise FileNotFoundError(f"No template {body_template_name}")
tpl = tempita.HTMLTemplate.from_filename(str(body_template_path),
encoding='utf-8')
body = tpl.substitute(title=title, content=content,
overlay=overlay,
docstring=docstring,
parameters=parameters,
**data)
head_template_name = 'report_head_template.html'
head_template_path = resource_path.joinpath(head_template_name)
with open(str(head_template_path), 'r') as head_file:
head_tpl = Template(head_file.read())
return HTMLReport(body=body, head_tpl=head_tpl)
def _define_overlay(estimator):
"""Determine whether an overlay was provided and \
update the report text as appropriate."""
displays = estimator._reporting()
if len(displays) == 1: # set overlay to None
overlay, image = None, displays[0]
elif len(displays) == 2:
overlay, image = displays[0], displays[1]
else:
overlay, image = None, displays
return overlay, image
def generate_report(estimator):
"""Generate a report for Nilearn objects.
Reports are useful to visualize steps in a processing pipeline.
Example use case: visualize the overlap of a mask and reference image
in NiftiMasker.
Parameters
----------
estimator : Object instance of BaseEstimator.
Object for which the report should be generated.
Returns
-------
report : HTMLReport
"""
if hasattr(estimator, '_report_content'):
data = estimator._report_content
else:
data = {}
if not hasattr(estimator, '_reporting_data'):
warnings.warn('This object has not been fitted yet ! '
'Make sure to run `fit` before inspecting reports.')
return _update_template(
title='Empty Report',
docstring=(
"This report was not generated. Please `fit` the object."
),
content=_embed_img(None),
overlay=None,
parameters={},
data=data,
)
elif estimator._reporting_data is None:
warnings.warn('Report generation not enabled ! '
'No visual outputs will be created.')
return _update_template(
title='Empty Report',
docstring=(
'This report was not '
'generated. Please check '
'that reporting is enabled.'
),
content=_embed_img(None),
overlay=None,
parameters={},
data=data,
)
return _create_report(estimator, data)
def _create_report(estimator, data):
html_template = _get_estimator_template(estimator)
overlay, image = _define_overlay(estimator)
embeded_images = (
[_embed_img(i) for i in image]
if isinstance(image, list)
else _embed_img(image)
)
parameters = _str_params(estimator.get_params())
docstring = estimator.__doc__
snippet = docstring.partition('Parameters\n ----------\n')[0]
return _update_template(
title=estimator.__class__.__name__,
docstring=snippet,
content=embeded_images,
overlay=_embed_img(overlay),
parameters=parameters,
data=data,
template_name=html_template,
)
class HTMLReport(HTMLDocument):
"""A report written as HTML.
Methods such as ``save_as_html``, or ``open_in_browser``
are inherited from class ``nilearn.plotting.html_document.HTMLDocument``.
"""
def __init__(self, head_tpl, body, head_values={}):
"""Construct the ``HTMLReport`` class.
Parameters
----------
head_tpl : Template
This is meant for display as a full page, eg writing on disk.
This is the Template object used to generate the HTML head
section of the report. The template should be filled with:
- title: The title of the HTML page.
- body: The full body of the HTML page. Provided through
the ``body`` input.
body : :obj:`str`
This parameter is used for embedding in the provided
``head_tpl`` template. It contains the full body of the
HTML page.
head_values : :obj:`dict`, optional
Additional substitutions in ``head_tpl``.
Default={}.
.. note::
This can be used to provide additional values
with custom templates.
"""
html = head_tpl.safe_substitute(body=body, **head_values)
super(HTMLReport, self).__init__(html)
self.head_tpl = head_tpl
self.body = body
def _repr_html_(self):
"""Return body of the report.
Method used by the Jupyter notebook.
Users normally won't call this method explicitly.
"""
return self.body
def __str__(self):
return self.body