|
| 1 | +import argparse |
| 2 | +import json |
| 3 | +import base64 |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +def convert_notebook_attachments(notebook_path: str, output_path: str): |
| 7 | + """Convert notebook attachments to embedded base64 images.""" |
| 8 | + with open(notebook_path, 'r', encoding='utf-8') as f: |
| 9 | + nb = json.load(f) |
| 10 | + |
| 11 | + for cell in nb.get('cells', []): |
| 12 | + if cell.get('cell_type') == 'markdown' and 'attachments' in cell: |
| 13 | + attachments = cell['attachments'] |
| 14 | + source = cell['source'] |
| 15 | + |
| 16 | + # Convert source to list if it's a string |
| 17 | + if isinstance(source, str): |
| 18 | + source = [source] |
| 19 | + |
| 20 | + new_source = [] |
| 21 | + for line in source: |
| 22 | + # Replace attachment references with data URIs |
| 23 | + for att_name, att_data in attachments.items(): |
| 24 | + if f'attachment:{att_name}' in line: |
| 25 | + # Get the first available image format |
| 26 | + mime_type = list(att_data.keys())[0] |
| 27 | + data = att_data[mime_type] |
| 28 | + data_uri = f'data:{mime_type};base64,{data}' |
| 29 | + line = line.replace(f'attachment:{att_name}', data_uri) |
| 30 | + new_source.append(line) |
| 31 | + |
| 32 | + cell['source'] = new_source |
| 33 | + # Remove attachments after conversion |
| 34 | + del cell['attachments'] |
| 35 | + |
| 36 | + # Save the modified notebook |
| 37 | + with open(output_path, 'w', encoding='utf-8') as f: |
| 38 | + json.dump(nb, f, indent=1) |
| 39 | + |
| 40 | + print(f"Converted notebook saved to: {output_path}") |
| 41 | + |
| 42 | +# ---------------------------------------------------------------------- |
| 43 | +def main() -> None: |
| 44 | + parser = argparse.ArgumentParser() |
| 45 | + parser.add_argument( |
| 46 | + "notebook_path", |
| 47 | + ) |
| 48 | + parser.add_argument( |
| 49 | + "output_path", |
| 50 | + ) |
| 51 | + args = parser.parse_args() |
| 52 | + |
| 53 | + convert_notebook_attachments(args.notebook_path, args.output_path) |
| 54 | + |
| 55 | +if __name__ == "__main__": |
| 56 | + main() |
0 commit comments