Path: blob/main/scripts/content_checks/nb_svg.py
3855 views
import sys1import nbformat2from scour import scour3from tools import parse_args456class ScourOptions:7def __init__(self, **entries):8self.__dict__.update(entries)91011SCOUR_OPTIONS = ScourOptions(12**{13'simple_colors': False,14'style_to_xml': True,15'group_collapse': True,16'group_create': True,17'keep_editor_data': False,18'keep_defs': False,19'renderer_workaround': True,20'strip_xml_prolog': False,21'remove_titles': True,22'remove_descriptions': True,23'remove_metadata': True,24'remove_descriptive_elements': True,25'strip_comments': True,26'enable_viewboxing': True,27'indent_type': 'none',28'newlines': False,29'strip_xml_space_attribute': False,30'strip_ids': True,31}32)333435def scour_svgs(filepath, fix=False):36"""Search through notebook and find/replace un-minimized SVGs"""37notebook = nbformat.read(filepath, 4)38needs_write = False39for cell in notebook.cells:40if cell.cell_type == 'code':41for output in cell.outputs:42if 'data' in output:43if 'image/svg+xml' in output['data']:44svg = output['data']['image/svg+xml']45if '\n' in svg:46if fix:47needs_write = True48min_svg = scour.scourString(svg, SCOUR_OPTIONS)49min_svg = min_svg.replace('\n', '')50output['data']['image/svg+xml'] = min_svg51else:52raise ValueError(f'Error in {filename.strip()}: SVG not minified.\n'53'Run `npm run test:nb:fix` to fix.')54if fix and needs_write:55nbformat.write(notebook, filepath, 4)565758if __name__ == '__main__':59# usage: python nb_svg.py --fix notebook1.ipynb path/to/notebook2.ipynb60switches, filepaths = parse_args(sys.argv)6162fix = '--fix' in switches6364for path in filepaths:65scour_svgs(path, fix)666768