Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
quantum-kittens
GitHub Repository: quantum-kittens/platypus
Path: blob/main/scripts/content_checks/nb_metadata.py
3855 views
1
import sys
2
import nbformat
3
from pathlib import Path
4
from tools import parse_args
5
6
7
CLEAN_METADATA = {'kernelspec': {'display_name': 'Python 3',
8
'language': 'python',
9
'name': 'python3'},
10
'language_info': {'codemirror_mode': {'name': 'ipython', 'version': 3},
11
'file_extension': '.py',
12
'mimetype': 'text/x-python',
13
'name': 'python',
14
'nbconvert_exporter': 'python',
15
'pygments_lexer': 'ipython3',
16
'version': '3.9'}}
17
18
19
def check_metadata(filepath, fix=False):
20
notebook = nbformat.read(filepath, 4)
21
if notebook.metadata == CLEAN_METADATA:
22
return True
23
elif fix:
24
notebook.metadata = CLEAN_METADATA
25
nbformat.write(notebook, filepath)
26
return True
27
else:
28
raise ValueError(
29
f'Bad metadata in {filepath}.\nRun `npm run test:nb:fix` to reset.'
30
)
31
32
if __name__ == '__main__':
33
# usage: python nb_metadata.py --fix notebook1.ipynb path/to/notebook2.ipynb
34
switches, filepaths = parse_args(sys.argv)
35
36
fix = '--fix' in switches
37
38
for path in filepaths:
39
check_metadata(path, fix)
40
41