|
11 | 11 | import plotly.graph_objects as go |
12 | 12 | import sys |
13 | 13 | import traceback |
| 14 | +from PIL import Image |
14 | 15 |
|
15 | 16 |
|
16 | 17 | def main(): |
@@ -83,6 +84,12 @@ def _capture_plotly_show(fig, counter, result, output_dir, stem): |
83 | 84 | result["html_files"].append(html_filename) |
84 | 85 | result.setdefault("html_content", []).append(html_content) |
85 | 86 |
|
| 87 | +def _capture_Image_show(img, counter, result, output_dir, stem): |
| 88 | + """Saves Images instead of displaying them.""" |
| 89 | + png_filename = f"{stem}_image_{counter}.png" |
| 90 | + png_path = output_dir / png_filename |
| 91 | + img.save(png_path, "PNG") |
| 92 | + result["images"].append(png_filename) |
86 | 93 |
|
87 | 94 | def _generate_markdown(args, content, code_blocks, execution_results, output_dir): |
88 | 95 | """Generate the output markdown with embedded results.""" |
@@ -211,6 +218,7 @@ def _run_all_blocks(args, code_blocks, stem=None, block_number=None): |
211 | 218 | "__file__": "<markdown_code>", |
212 | 219 | } |
213 | 220 | figure_counter = 0 |
| 221 | + # img_counter = 0 |
214 | 222 | for i, block in enumerate(code_blocks): |
215 | 223 | if block_number is None: |
216 | 224 | _report(args.verbose > 1, f"- Executing block {i}/{len(code_blocks)}") |
@@ -256,10 +264,18 @@ def patched_show(self, *args, **kwargs): |
256 | 264 | figure_counter += 1 |
257 | 265 | if stem is not None: |
258 | 266 | _capture_plotly_show(self, figure_counter, result, output_dir, stem) |
| 267 | + def patched_img_show(self, *args, **kwargs): |
| 268 | + nonlocal figure_counter |
| 269 | + figure_counter += 1 |
| 270 | + if stem is not None: |
| 271 | + _capture_Image_show(self, figure_counter, result, output_dir, stem) |
259 | 272 | original_show = go.Figure.show |
| 273 | + original_img_show = Image.Image.show |
| 274 | + Image.Image.show = patched_img_show |
260 | 275 | go.Figure.show = patched_show |
261 | 276 | exec(code, exec_globals) |
262 | 277 | go.Figure.show = original_show |
| 278 | + Image.Image.show = original_img_show |
263 | 279 |
|
264 | 280 | except Exception as e: |
265 | 281 | result["error"] = f"Error executing code: {str(e)}\n{traceback.format_exc()}" |
|
0 commit comments