Skip to content

Commit f36c1a0

Browse files
author
Red Giuliano
committed
fixed failing ipynb conversion
1 parent 12bf066 commit f36c1a0

File tree

2 files changed

+35
-48
lines changed

2 files changed

+35
-48
lines changed

zt_backend/tests/test_convert.py

Lines changed: 22 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,36 @@
11
from zt_backend.models.state.notebook_state import NotebookState
2-
from zt_backend.models import notebook
3-
import rtoml
42
import subprocess
53
from pathlib import Path
64
import os
5+
import importlib.util
76

8-
notebook_state = NotebookState()
7+
IPYNB_PATH = Path("test_file.ipynb").resolve()
8+
OUTPUT_PATH = Path("notebook.py").resolve()
9+
NOTEBOOK_PATH = Path("test_notebook.py").resolve()
910

10-
IPYNB_PATH = Path("zt_backend/tests/test_file.ipynb").resolve()
11-
OUTPUT_PATH = Path("zt_backend/tests/notebook.py").resolve()
12-
NOTEBOOK_PATH = Path("zt_backend/tests/test_notebook.py").resolve()
11+
def dynamic_import(module_path):
12+
spec = importlib.util.spec_from_file_location("notebook_module", module_path)
13+
module = importlib.util.module_from_spec(spec)
14+
spec.loader.exec_module(module)
15+
return module
1316

1417
def test_ipynb_to_ztnb():
1518

19+
# Step 1: Convert the IPYNB file to a Python file
1620
convert = subprocess.Popen(
1721
["zero-true", "jupyter-convert", IPYNB_PATH, OUTPUT_PATH]
1822
)
1923
convert.wait()
2024

21-
with open(NOTEBOOK_PATH, "r", encoding="utf-8") as file:
22-
expected_data = rtoml.loads(file.read().replace("\\", "\\\\"))
23-
24-
expected_notebook_data = {
25-
"notebookId": "test_id",
26-
"notebookName": expected_data.get("notebookName", "Zero True"),
27-
"userId": "",
28-
"cells": {
29-
f"{index}": notebook.CodeCell(id=f"{index}", **cell_data, output="")
30-
for index, (cell_id, cell_data) in enumerate(expected_data["cells"].items())
31-
},
32-
}
33-
expected_notebook = notebook.Notebook(**expected_notebook_data)
34-
35-
with open(OUTPUT_PATH, "r", encoding="utf-8") as file:
36-
output_data = rtoml.loads(file.read().replace("\\", "\\\\"))
37-
38-
output_notebook_data = {
39-
"notebookId": "test_id",
40-
"notebookName": output_data.get("notebookName", "Zero True"),
41-
"userId": "",
42-
"cells": {
43-
f"{index}": notebook.CodeCell(id=f"{index}", **cell_data, output="")
44-
for index, (cell_id, cell_data) in enumerate(output_data["cells"].items())
45-
},
46-
}
47-
output_notebook = notebook.Notebook(**output_notebook_data)
48-
49-
assert expected_notebook == output_notebook
50-
51-
os.remove(OUTPUT_PATH)
25+
# Step 2: Import the expected notebook from test_notebook.py
26+
from test_notebook import notebook as expected_notebook
27+
output_module = dynamic_import(OUTPUT_PATH)
28+
output_notebook = output_module.notebook
29+
# Step 3: Import the generated notebook from notebook.py
30+
expected_notebook.notebookId='0'
31+
output_notebook.notebookId='0'
32+
# Step 4: Assert that the generated notebook matches the expected notebook
33+
assert output_notebook == expected_notebook
34+
35+
# Step 5: Clean up the generated file
36+
os.remove(OUTPUT_PATH)

zt_cli/cli.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ def jupyter_convert(
243243

244244
try:
245245
with open(ipynb_path, "r", encoding="utf-8") as f:
246-
notebook = json.loads(f.read())
246+
notebook = json.load(f)
247247
except Exception as e:
248248
typer.echo(f"Error occured: {e}")
249249
return
@@ -257,8 +257,7 @@ def jupyter_convert(
257257
typer.echo(f"Successfully converted {ipynb_path} to {nb_path}")
258258
return
259259

260-
def jupyter_convert_func(ipynb_string):
261-
notebook = json.loads(ipynb_string)
260+
def jupyter_convert_func(notebook):
262261
output_lines = []
263262

264263
# Add notebook metadata
@@ -267,31 +266,34 @@ def jupyter_convert_func(ipynb_string):
267266
output_lines.append("")
268267

269268
# Generate Python functions for each cell
270-
for index, cell in enumerate(notebook["cells"], start=1):
269+
for index, cell in enumerate(notebook["cells"], start=0):
271270
cell_id = f"cell_{index}"
272271
if cell["cell_type"] == "code":
273272
output_lines.append(f"def {cell_id}():")
274-
for line in cell["source"]:
275-
output_lines.append(f" {line.strip()}")
276-
output_lines.append("")
273+
# Join the source lines with proper indentation
274+
source_code = "".join(cell["source"])
275+
for line in source_code.splitlines():
276+
output_lines.append(f" {line}")
277+
output_lines.append("") # Add an empty line after the function
277278

278279
elif cell["cell_type"] == "markdown":
279280
markdown_content = "".join(cell["source"]).strip().replace('"""', "'''")
280281
output_lines.append(f"def {cell_id}():")
281282
output_lines.append(f" zt.markdown(\"\"\"{markdown_content}\"\"\")")
282-
output_lines.append("")
283+
output_lines.append("") # Add an empty line after the function
283284

284285
# Add notebook definition
285286
output_lines.append(f"notebook = zt.notebook(")
286287
output_lines.append(f" id='{notebook_id}',")
287288
output_lines.append(f" name='Zero True',")
288289
output_lines.append(f" cells=[")
289-
for index in range(1, len(notebook["cells"]) + 1):
290-
output_lines.append(f" zt.cell(cell_{index}, type='{'markdown' if notebook['cells'][index-1]['cell_type'] == 'markdown' else 'code'}'),")
290+
for index in range(0, len(notebook["cells"])):
291+
output_lines.append(f" zt.cell(cell_{index}, type='{'markdown' if notebook['cells'][index]['cell_type'] == 'markdown' else 'code'}'),")
291292
output_lines.append(f" ]")
292293
output_lines.append(f")")
293294

294-
return "\n".join(output_lines)
295+
return output_lines # Return the list of output lines directly
296+
295297

296298

297299

0 commit comments

Comments
 (0)