From 9a48bd9a21d6836cc0b26363fd69a73c57e3dcd1 Mon Sep 17 00:00:00 2001 From: Sanjiv Das Date: Wed, 18 Dec 2024 10:16:46 -0800 Subject: [PATCH] Update to ensure no hanging code cells in generated notebooks --- packages/jupyter-ai/jupyter_ai/chat_handlers/generate.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/packages/jupyter-ai/jupyter_ai/chat_handlers/generate.py b/packages/jupyter-ai/jupyter_ai/chat_handlers/generate.py index a69b5ed28..409ce578e 100644 --- a/packages/jupyter-ai/jupyter_ai/chat_handlers/generate.py +++ b/packages/jupyter-ai/jupyter_ai/chat_handlers/generate.py @@ -212,6 +212,15 @@ def create_notebook(outline): nb["cells"].append(nbf.new_markdown_cell("## " + section["title"])) for code_block in section["code"].split("\n\n"): nb["cells"].append(nbf.new_code_cell(code_block)) + + # Post process notebook for hanging cells: merge hanging cell with the previous cell + nb_cells = list() + for cell in nb["cells"]: + if (cell["cell_type"] == 'code') and (cell["source"][0] == ' '): + nb_cells[-1]["source"] = nb_cells[-1]["source"] + '\n\n' + cell["source"] + else: + nb_cells.append(cell) + nb["cells"] = nb_cells return nb