|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Notebook to GitHub-Compatible Format Converter |
| 4 | +
|
| 5 | +This script fixes Jupyter notebooks for GitHub rendering by: |
| 6 | +1. Converting XML-format notebooks to standard Jupyter JSON format |
| 7 | +2. Cleaning widget metadata that can cause GitHub rendering issues |
| 8 | +""" |
| 9 | + |
| 10 | +import os |
| 11 | +import json |
| 12 | +import re |
| 13 | +import nbformat |
| 14 | +from nbformat.validator import validate |
| 15 | + |
| 16 | +def process_notebooks(directory="."): |
| 17 | + """Find and process all notebook files in the repository""" |
| 18 | + notebook_files = [] |
| 19 | + print(f"Searching for notebooks in directory: {directory}") |
| 20 | + for root, dirs, files in os.walk(directory): |
| 21 | + # Skip directories that should be excluded |
| 22 | + if '.git' in dirs: |
| 23 | + dirs.remove('.git') # Skip git directory |
| 24 | + if '.github' in dirs: |
| 25 | + dirs.remove('.github') # Skip GitHub directory |
| 26 | + if '.venv' in dirs: |
| 27 | + dirs.remove('.venv') # Skip virtual environments |
| 28 | + |
| 29 | + for file in files: |
| 30 | + if file.endswith('.ipynb'): |
| 31 | + notebook_path = os.path.join(root, file) |
| 32 | + print(f"Found notebook: {notebook_path}") |
| 33 | + notebook_files.append(notebook_path) |
| 34 | + |
| 35 | + print(f"Found {len(notebook_files)} notebooks to process") |
| 36 | + |
| 37 | + success_count = 0 |
| 38 | + for nb_path in notebook_files: |
| 39 | + if convert_notebook(nb_path): |
| 40 | + success_count += 1 |
| 41 | + |
| 42 | + print(f"Successfully rendered {success_count} out of {len(notebook_files)} notebooks") |
| 43 | + return success_count |
| 44 | + |
| 45 | +def convert_notebook(filepath): |
| 46 | + """Convert a notebook to GitHub-compatible format by cleaning widget metadata""" |
| 47 | + print(f"\nProcessing {filepath}") |
| 48 | + |
| 49 | + try: |
| 50 | + # Read the notebook content |
| 51 | + with open(filepath, 'r', encoding='utf-8') as f: |
| 52 | + content = f.read() |
| 53 | + |
| 54 | + # Check if this is a XML notebook |
| 55 | + if '<VSCode.Cell' in content: |
| 56 | + print(f" Converting from XML format...") |
| 57 | + # Extract cells using regex |
| 58 | + cells = [] |
| 59 | + cell_pattern = re.compile(r'<VSCode\.Cell.*?language="(.*?)".*?>(.*?)</VSCode\.Cell>', re.DOTALL) |
| 60 | + |
| 61 | + matches = list(cell_pattern.finditer(content)) |
| 62 | + if not matches: |
| 63 | + print(f" WARNING: No cells found in {filepath}") |
| 64 | + return False |
| 65 | + |
| 66 | + print(f" Found {len(matches)} cells") |
| 67 | + |
| 68 | + for match in matches: |
| 69 | + cell_type, cell_content = match.groups() |
| 70 | + |
| 71 | + if cell_type == "markdown": |
| 72 | + cells.append(nbformat.v4.new_markdown_cell( |
| 73 | + source=cell_content.strip() |
| 74 | + )) |
| 75 | + else: # python, javascript, etc. |
| 76 | + cells.append(nbformat.v4.new_code_cell( |
| 77 | + source=cell_content.strip() |
| 78 | + )) |
| 79 | + |
| 80 | + # Create a new notebook |
| 81 | + nb = nbformat.v4.new_notebook() |
| 82 | + nb.cells = cells |
| 83 | + |
| 84 | + # Add required metadata |
| 85 | + nb.metadata = { |
| 86 | + "kernelspec": { |
| 87 | + "display_name": "Python 3", |
| 88 | + "language": "python", |
| 89 | + "name": "python3" |
| 90 | + }, |
| 91 | + "language_info": { |
| 92 | + "codemirror_mode": { |
| 93 | + "name": "ipython", |
| 94 | + "version": 3 |
| 95 | + }, |
| 96 | + "file_extension": ".py", |
| 97 | + "mimetype": "text/x-python", |
| 98 | + "name": "python", |
| 99 | + "nbconvert_exporter": "python", |
| 100 | + "pygments_lexer": "ipython3", |
| 101 | + "version": "3.8.10" |
| 102 | + }, |
| 103 | + # Add empty widget state to prevent GitHub rendering issues |
| 104 | + "widgets": { |
| 105 | + "application/vnd.jupyter.widget-state+json": { |
| 106 | + "state": {}, |
| 107 | + "version_major": 2, |
| 108 | + "version_minor": 0 |
| 109 | + } |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + # Validate and write the notebook |
| 114 | + validate(nb) |
| 115 | + with open(filepath, 'w', encoding='utf-8') as f: |
| 116 | + nbformat.write(nb, f) |
| 117 | + |
| 118 | + print(f" Successfully rendered {filepath} for GitHub compatibility") |
| 119 | + return True |
| 120 | + |
| 121 | + else: |
| 122 | + # It's already in JSON format, clean widget metadata |
| 123 | + try: |
| 124 | + notebook = json.loads(content) |
| 125 | + print(f" Cleaning widget metadata...") |
| 126 | + |
| 127 | + # Remove potentially problematic widget state but keep proper structure |
| 128 | + if 'metadata' in notebook: |
| 129 | + # Replace with clean widget state |
| 130 | + notebook['metadata']['widgets'] = { |
| 131 | + "application/vnd.jupyter.widget-state+json": { |
| 132 | + "state": {}, |
| 133 | + "version_major": 2, |
| 134 | + "version_minor": 0 |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + # Clean widget metadata from cells as well |
| 139 | + for cell in notebook.get('cells', []): |
| 140 | + if 'metadata' in cell and 'widgets' in cell['metadata']: |
| 141 | + del cell['metadata']['widgets'] |
| 142 | + |
| 143 | + # Write the cleaned notebook |
| 144 | + with open(filepath, 'w', encoding='utf-8') as f: |
| 145 | + json.dump(notebook, f, indent=2) |
| 146 | + |
| 147 | + print(f" Successfully cleaned {filepath} for GitHub compatibility") |
| 148 | + return True |
| 149 | + |
| 150 | + except json.JSONDecodeError: |
| 151 | + print(f" ERROR: {filepath} is not in valid JSON format or XML format") |
| 152 | + return False |
| 153 | + |
| 154 | + except Exception as e: |
| 155 | + print(f" ERROR processing {filepath}: {str(e)}") |
| 156 | + return False |
| 157 | + |
| 158 | +if __name__ == "__main__": |
| 159 | + print("Rendering notebooks for GitHub compatibility...") |
| 160 | + # Get the repository root directory from environment variable if available |
| 161 | + repo_root = os.environ.get('GITHUB_WORKSPACE', '.') |
| 162 | + print(f"Repository root: {repo_root}") |
| 163 | + process_notebooks(repo_root) |
0 commit comments