88"""
99
1010import base64
11+ import io
1112import re
1213import sys
1314from pathlib import Path
@@ -41,27 +42,23 @@ def load_categories_from_index(index_path: Path) -> dict[str, list[str]]:
4142 dict[str, list[str]]
4243 Mapping from category name to list of notebook names (without .ipynb)
4344 """
44- categories : dict [str , list [str ]] = {}
45- current_category = None
46-
4745 if not index_path .exists ():
48- return categories
46+ return {}
4947
5048 try :
51- with open ( index_path , "r" , encoding = "utf-8" ) as f :
52- for line in f :
53- # Check for category header (## Category Name)
54- if line .startswith ("## " ):
55- current_category = line [3 :].strip ()
56- if current_category and current_category != "Example Gallery" :
57- categories [current_category ] = []
58- # Check for notebook links under current category
59- elif current_category and (match := re . search ( r":link:\s+(\S+)" , line )):
60- categories [ current_category ]. append ( match . group ( 1 ))
49+ categories : dict [ str , list [ str ]] = {}
50+ current_category = None
51+ for line in index_path . read_text ( encoding = "utf-8" ). splitlines ():
52+ if line .startswith ("## " ):
53+ current_category = line [3 :].strip ()
54+ if current_category and current_category != "Example Gallery" :
55+ categories [current_category ] = []
56+ elif current_category and ( match := re . search ( r":link:\s+(\S+)" , line )):
57+ categories [ current_category ]. append (match . group ( 1 ))
58+ return categories
6159 except Exception as e :
6260 print (f"Warning: Could not load categories from { index_path } : { e } " )
63-
64- return categories
61+ return {}
6562
6663
6764def get_notebook_category (filename : str , category_mapping : dict [str , list [str ]]) -> str :
@@ -79,8 +76,7 @@ def get_notebook_category(filename: str, category_mapping: dict[str, list[str]])
7976
8077def extract_metadata (notebook_path : Path ) -> str :
8178 """Extract title from notebook."""
82- with open (notebook_path , "r" , encoding = "utf-8" ) as f :
83- nb = nbformat .read (f , as_version = 4 )
79+ nb = nbformat .reads (notebook_path .read_text (encoding = "utf-8" ), as_version = 4 )
8480
8581 # Look for title in first markdown cell
8682 for cell in nb .cells :
@@ -109,8 +105,7 @@ def extract_first_image(notebook_path: Path, output_dir: Path) -> str | None:
109105 return None
110106
111107 try :
112- with open (notebook_path , "r" , encoding = "utf-8" ) as f :
113- nb = nbformat .read (f , as_version = 4 )
108+ nb = nbformat .reads (notebook_path .read_text (encoding = "utf-8" ), as_version = 4 )
114109
115110 # Try to find images in existing outputs first
116111 if image_data := _find_image_in_notebook (nb ):
@@ -145,15 +140,12 @@ def _save_thumbnail(
145140 thumbnail_name = f"{ notebook_path .stem } .png"
146141 thumbnail_path = output_dir / thumbnail_name
147142
148- # Decode and save image
149- thumbnail_path .write_bytes (base64 .b64decode (image_data ))
150-
151- # Resize to uniform size (400x250) with padding
152- img = Image .open (thumbnail_path )
143+ # Decode and process image in memory
144+ img = Image .open (io .BytesIO (base64 .b64decode (image_data )))
153145 target_size = (400 , 250 )
154146 img .thumbnail (target_size , Image .Resampling .LANCZOS )
155147
156- # Create padded image
148+ # Create padded image and save
157149 new_img = Image .new ("RGB" , target_size , (255 , 255 , 255 ))
158150 new_img .paste (
159151 img ,
@@ -179,9 +171,9 @@ def generate_gallery_markdown(
179171 categories .setdefault (nb_data ["category" ], []).append (nb_data )
180172
181173 # Sort categories maintaining order from index.md
182- sorted_categories = [
183- cat for cat in category_mapping .keys () if cat in categories
184- ] + [ cat for cat in categories . keys () if cat not in category_mapping ]
174+ sorted_categories = list ( category_mapping . keys () & categories . keys ()) + list (
175+ categories . keys () - category_mapping .keys ()
176+ )
185177
186178 # Generate markdown
187179 lines = ["# Example Gallery\n " ]
0 commit comments