Path: blob/main/scripts/content_checks/nb_metadata.py
3855 views
import sys1import nbformat2from pathlib import Path3from tools import parse_args456CLEAN_METADATA = {'kernelspec': {'display_name': 'Python 3',7'language': 'python',8'name': 'python3'},9'language_info': {'codemirror_mode': {'name': 'ipython', 'version': 3},10'file_extension': '.py',11'mimetype': 'text/x-python',12'name': 'python',13'nbconvert_exporter': 'python',14'pygments_lexer': 'ipython3',15'version': '3.9'}}161718def check_metadata(filepath, fix=False):19notebook = nbformat.read(filepath, 4)20if notebook.metadata == CLEAN_METADATA:21return True22elif fix:23notebook.metadata = CLEAN_METADATA24nbformat.write(notebook, filepath)25return True26else:27raise ValueError(28f'Bad metadata in {filepath}.\nRun `npm run test:nb:fix` to reset.'29)3031if __name__ == '__main__':32# usage: python nb_metadata.py --fix notebook1.ipynb path/to/notebook2.ipynb33switches, filepaths = parse_args(sys.argv)3435fix = '--fix' in switches3637for path in filepaths:38check_metadata(path, fix)394041