in src/doc_builder/commands/notebook_to_mdx.py [0:0]
def notebook_to_mdx(notebook, max_len):
content = []
for cell in notebook["cells"]:
if cell["cell_type"] == "code":
code = cell["source"]
outputs = [
o
for o in cell["outputs"]
if ("text" in o and o.get("name", None) == "stdout")
or "text/plain" in o
or ("data" in o and ("image/png" in o["data"] or "image/jpeg" in o["data"]))
]
if len(outputs) > 0:
code_lines = code.split("\n")
# We can add >>> everywhere without worrying as format_code_example will replace them by ...
# when needed.
code_lines = [f">>> {l}" if not len(l) == 0 or l.isspace() else l for l in code_lines]
code = "\n".join(code_lines)
code = format_code_example(code, max_len=max_len)[0]
content.append(f"```python\n{code}\n```")
first_output = outputs[0]
if "text" in first_output:
output = first_output["text"]
output = f"<pre>\n{output.strip()}\n</pre>"
elif "text/plain" in first_output:
output = first_output["text/plain"]
output = f"<pre>\n{output.strip()}\n</pre>"
elif "data" in first_output and "image/png" in first_output["data"]:
jpeg_base64 = png_to_jpeg(first_output["data"]["image/png"])
output = f'<img src="data:image/jpeg;base64,{jpeg_base64}">\n'
elif "data" in first_output and "image/jpeg" in first_output["data"]:
output = f'<img src="data:image/jpeg;base64,{first_output["data"]["image/jpeg"]}">\n'
content.append(output)
else:
code = format_code_example(code, max_len=max_len)[0]
content.append(f"```python\n{code}\n```")
elif cell["cell_type"] == "markdown":
content.append(cell["source"])
else:
content.append(f"```\n{cell['source']}\n```")
mdx_content = "\n\n".join(content)
return mdx_content