1+ import nbformat
2+ import sys
3+ from pathlib import Path
4+
5+ def clean_notebook_metadata (path : str ):
6+ """
7+ Remove problematic metadata that breaks GitHub rendering,
8+ while keeping all cell outputs intact.
9+ """
10+ path = Path (path )
11+ if not path .exists ():
12+ print (f"File not found: { path } " )
13+ return
14+
15+ # Read notebook
16+ nb = nbformat .read (str (path ), as_version = 4 )
17+
18+ # Keys in top-level metadata that trigger GitHub widget errors
19+ for key in ["widgets" , "varInspector" , "latex_envs" ]:
20+ if key in nb ['metadata' ]:
21+ nb ['metadata' ].pop (key , None )
22+ print (f"Removed top-level metadata: { key } " )
23+
24+ # Optional: Remove widgets metadata from individual cells if present
25+ for i , cell in enumerate (nb ['cells' ]):
26+ if 'metadata' in cell and 'widgets' in cell ['metadata' ]:
27+ cell ['metadata' ].pop ('widgets' , None )
28+ print (f"Removed widgets metadata from cell { i } " )
29+
30+ # Write the cleaned notebook back
31+ nbformat .write (nb , str (path ))
32+ print (f"Notebook cleaned and saved: { path } " )
33+
34+ if __name__ == "__main__" :
35+ if len (sys .argv ) < 2 :
36+ print ("Usage: python clean_notebook.py <notebook.ipynb>" )
37+ sys .exit (1 )
38+
39+ notebook_path = sys .argv [1 ]
40+ clean_notebook_metadata (notebook_path )
0 commit comments