Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Automatizing the conversion of jupyter examples to rst #105

Merged
merged 4 commits into from
Dec 4, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/docs-requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,5 @@ sphinx-pdj-theme # TODO to comment
sphinx-copybutton
sphinxjp.themes.sphinxjp
sphinxjp.themes.basicstrap
nbformat
nbconvert
54 changes: 54 additions & 0 deletions docs/notebooks_convert.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from nbconvert import RSTExporter
from nbconvert.writers import FilesWriter
import nbformat
import os

path = os.path.abspath(os.path.join(os.path.dirname(__file__),))


def convert_notebook_to_rst(input_file, output_dir, file_name):
# Load the notebook
with open(input_file, "r", encoding="utf-8") as f:
notebook_content = nbformat.read(f, as_version=4)

# Create an RST exporter
rst_exporter = RSTExporter()

# Generate RST content
rst_content, resources = rst_exporter.from_notebook_node(notebook_content)

if not os.path.exists(output_dir):
os.mkdir(output_dir)

output_file = f"{output_dir}/{file_name}.rst"
mohammadamint marked this conversation as resolved.
Show resolved Hide resolved

# Write RST content to the output file
with open(output_file, "w", encoding="utf-8") as f:
f.write(rst_content)

print(f"Conversion successful. RST file saved to: {output_file}")

# Copy images to the output folder
image_dir = output_dir
for image_filename, image_data in resources["outputs"].items():
image_path = f"{output_dir}/{image_filename}"
mohammadamint marked this conversation as resolved.
Show resolved Hide resolved
with open(image_path, "wb") as img_file:
img_file.write(image_data)


def get_all_ipynb_files(examples_path="notebooks"):

all_files = os.listdir(examples_path)
return [
(f"{path}/{examples_path}/{file}", file.split(".ipynb")[0])
mohammadamint marked this conversation as resolved.
Show resolved Hide resolved
for file in all_files
if file.endswith("ipynb")
]


if __name__ == "__main__":

files = get_all_ipynb_files()

for file, folder in files:
convert_notebook_to_rst(file, f"{path}/source/examples/{folder}", folder)
mohammadamint marked this conversation as resolved.
Show resolved Hide resolved
Loading