|
| 1 | +import json |
| 2 | +import uuid |
| 3 | +import os |
| 4 | + |
| 5 | +target_files = [ |
| 6 | + "values.ipynb", |
| 7 | + "logical.ipynb", |
| 8 | + "expressions_dataTypes.ipynb", |
| 9 | + "inputs.ipynb", |
| 10 | + "starting.ipynb" |
| 11 | +] |
| 12 | + |
| 13 | +# Set to track all IDs across all processed files to ensure global uniqueness |
| 14 | +seen_ids = set() |
| 15 | + |
| 16 | +def clean_notebook_ids(filepath): |
| 17 | + print(f"Cleaning {filepath}...") |
| 18 | + try: |
| 19 | + with open(filepath, 'r', encoding='utf-8') as f: |
| 20 | + data = json.load(f) |
| 21 | + except Exception as e: |
| 22 | + print(f" Error reading {filepath}: {e}") |
| 23 | + return |
| 24 | + |
| 25 | + changed = False |
| 26 | + if 'cells' in data: |
| 27 | + for cell in data['cells']: |
| 28 | + # 1. Remove 'id' from metadata if present (conflicts with top-level id and causes warnings) |
| 29 | + if 'metadata' in cell and 'id' in cell['metadata']: |
| 30 | + print(f" Removing metadata.id: {cell['metadata']['id']}") |
| 31 | + del cell['metadata']['id'] |
| 32 | + changed = True |
| 33 | + |
| 34 | + # 2. Ensure top-level 'id' exists and is unique across ALL files |
| 35 | + if 'id' not in cell: |
| 36 | + new_id = str(uuid.uuid4())[:8] |
| 37 | + while new_id in seen_ids: |
| 38 | + new_id = str(uuid.uuid4())[:8] |
| 39 | + cell['id'] = new_id |
| 40 | + seen_ids.add(new_id) |
| 41 | + changed = True |
| 42 | + else: |
| 43 | + current_id = cell['id'] |
| 44 | + if current_id in seen_ids: |
| 45 | + # Duplicate found - regenerate |
| 46 | + new_id = str(uuid.uuid4())[:8] |
| 47 | + while new_id in seen_ids: |
| 48 | + new_id = str(uuid.uuid4())[:8] |
| 49 | + print(f" Duplicate top-level ID found: {current_id} -> Replaced with {new_id}") |
| 50 | + cell['id'] = new_id |
| 51 | + seen_ids.add(new_id) |
| 52 | + changed = True |
| 53 | + else: |
| 54 | + seen_ids.add(current_id) |
| 55 | + |
| 56 | + if changed: |
| 57 | + with open(filepath, 'w', encoding='utf-8') as f: |
| 58 | + json.dump(data, f, indent=1, ensure_ascii=False) |
| 59 | + # Ensure single newline at end of file |
| 60 | + f.write('\n') |
| 61 | + print(f" --> Updated {filepath}") |
| 62 | + else: |
| 63 | + print(f" --> No changes needed for {filepath}") |
| 64 | + |
| 65 | +def main(): |
| 66 | + root_dir = "/home/gslee/wGitHub/code-workout-python" |
| 67 | + for fname in target_files: |
| 68 | + fpath = os.path.join(root_dir, fname) |
| 69 | + if os.path.exists(fpath): |
| 70 | + clean_notebook_ids(fpath) |
| 71 | + else: |
| 72 | + print(f"File not found: {fpath}") |
| 73 | + |
| 74 | +if __name__ == "__main__": |
| 75 | + main() |
0 commit comments