Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
quantum-kittens
GitHub Repository: quantum-kittens/platypus
Path: blob/main/scripts/content_checks/nb_svg.py
3855 views
1
import sys
2
import nbformat
3
from scour import scour
4
from tools import parse_args
5
6
7
class ScourOptions:
8
def __init__(self, **entries):
9
self.__dict__.update(entries)
10
11
12
SCOUR_OPTIONS = ScourOptions(
13
**{
14
'simple_colors': False,
15
'style_to_xml': True,
16
'group_collapse': True,
17
'group_create': True,
18
'keep_editor_data': False,
19
'keep_defs': False,
20
'renderer_workaround': True,
21
'strip_xml_prolog': False,
22
'remove_titles': True,
23
'remove_descriptions': True,
24
'remove_metadata': True,
25
'remove_descriptive_elements': True,
26
'strip_comments': True,
27
'enable_viewboxing': True,
28
'indent_type': 'none',
29
'newlines': False,
30
'strip_xml_space_attribute': False,
31
'strip_ids': True,
32
}
33
)
34
35
36
def scour_svgs(filepath, fix=False):
37
"""Search through notebook and find/replace un-minimized SVGs"""
38
notebook = nbformat.read(filepath, 4)
39
needs_write = False
40
for cell in notebook.cells:
41
if cell.cell_type == 'code':
42
for output in cell.outputs:
43
if 'data' in output:
44
if 'image/svg+xml' in output['data']:
45
svg = output['data']['image/svg+xml']
46
if '\n' in svg:
47
if fix:
48
needs_write = True
49
min_svg = scour.scourString(svg, SCOUR_OPTIONS)
50
min_svg = min_svg.replace('\n', '')
51
output['data']['image/svg+xml'] = min_svg
52
else:
53
raise ValueError(f'Error in {filename.strip()}: SVG not minified.\n'
54
'Run `npm run test:nb:fix` to fix.')
55
if fix and needs_write:
56
nbformat.write(notebook, filepath, 4)
57
58
59
if __name__ == '__main__':
60
# usage: python nb_svg.py --fix notebook1.ipynb path/to/notebook2.ipynb
61
switches, filepaths = parse_args(sys.argv)
62
63
fix = '--fix' in switches
64
65
for path in filepaths:
66
scour_svgs(path, fix)
67
68