def convert_to_rst(nb, basedir, fpath, fstem): # Convert to .rst formats exp = RSTExporter() c = Config() c.TagRemovePreprocessor.remove_cell_tags = {"hide"} c.TagRemovePreprocessor.remove_input_tags = {"hide-input"} c.TagRemovePreprocessor.remove_all_outputs_tags = {"hide-output"} c.ExtractOutputPreprocessor.output_filename_template = ( f"{fstem}_files/{fstem}_" + "{cell_index}_{index}{extension}" ) exp.register_preprocessor(TagRemovePreprocessor(config=c), True) exp.register_preprocessor(ExtractOutputPreprocessor(config=c), True) body, resources = exp.from_notebook_node(nb) # Clean the output on the notebook and save a .ipynb back to disk print(f"Writing clean {fpath} ... ", end=" ", flush=True) nb = strip_output(nb) with open(fpath, "wt") as f: nbformat.write(nb, f) # Write the .rst file rst_path = os.path.join(basedir, f"{fstem}.rst") print(f"Writing {rst_path}") with open(rst_path, "w") as f: f.write(body) print(resources["outputs"]) # Write the individual image outputs imdir = os.path.join(basedir, f"{fstem}_files") if not os.path.exists(imdir): os.mkdir(imdir) for imname, imdata in resources["outputs"].items(): if imname.startswith(fstem): impath = os.path.join(basedir, f"{imname}") with open(impath, "wb") as f: f.write(imdata) f.write(imdata)
if key == "text/plain": field["data"].pop(key) if not field["data"]: fields.remove(field) # Convert to .rst formats exp = RSTExporter() c = Config() c.TagRemovePreprocessor.remove_cell_tags = {"hide"} c.TagRemovePreprocessor.remove_input_tags = {"hide-input"} c.TagRemovePreprocessor.remove_all_outputs_tags = {"hide-output"} c.ExtractOutputPreprocessor.output_filename_template = \ f"{fstem}_files/{fstem}_" + "{cell_index}_{index}{extension}" exp.register_preprocessor(TagRemovePreprocessor(config=c), True) exp.register_preprocessor(ExtractOutputPreprocessor(config=c), True) body, resources = exp.from_notebook_node(nb) # Clean the output on the notebook and save a .ipynb back to disk print(f"Writing clean {fpath} ... ", end=" ", flush=True) nb = strip_output(nb) with open(fpath, "wt") as f: nbformat.write(nb, f) # Write the .rst file rst_path = os.path.join(basedir, f"{fstem}.rst") print(f"Writing {rst_path}") with open(rst_path, "w") as f: f.write(body)