Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
/* indent single paragraph */
div.admonition {
text-indent: 20px;
}
/* don't indent multiple paragraphs */
div.admonition > p {
text-indent: 0;
}
/* remove excessive padding */
div.admonition.inline-title p.admonition-title {
padding-left: .2em;
}
"""
class Exporter(nbconvert.RSTExporter):
"""Convert Jupyter notebooks to reStructuredText.
Uses nbconvert to convert Jupyter notebooks to a reStructuredText
string with custom reST directives for input and output cells.
Notebooks without output cells are automatically executed before
conversion.
"""
def __init__(self, execute='auto', kernel_name='', execute_arguments=[],
allow_errors=False, timeout=30, codecell_lexer='none'):
"""Initialize the Exporter."""
# NB: The following stateful Jinja filters are a hack until
# template-based processing is dropped
def run(self):
import nbconvert
from os.path import join
exporter = nbconvert.RSTExporter()
writer = nbconvert.writers.FilesWriter()
files = [
join("examples", "01_simple_usage.ipynb"),
join("examples", "02_advanced_usage.ipynb"),
join("examples", "03_preserving_global_structure.ipynb"),
join("examples", "04_large_data_sets.ipynb"),
]
target_dir = join("docs", "source", "examples")
for fname in files:
self.announce(f"Converting {fname}...")
directory, nb_name = fname.split("/")
nb_name, _ = nb_name.split(".")
body, resources = exporter.from_file(fname)
writer.build_directory = join(target_dir, nb_name)
def create_rst(self, nb, in_dir, odir):
"""Create the rst file from the notebook node"""
exporter = nbconvert.RSTExporter()
raw_rst, resources = exporter.from_notebook_node(nb)
# remove ipython magics
rst_content = ''
i0 = 0
m = None
# HACK: we insert the bokeh style sheets here as well, since for some
# themes (e.g. the sphinx_rtd_theme) it is not sufficient to include
# the style sheets only via app.add_stylesheet
bokeh_str = ''
if 'bokeh' in raw_rst and self.insert_bokeh:
bokeh_str += self.BOKEH_TEMPLATE.format(
version=self.insert_bokeh)
if 'bokeh' in raw_rst and self.insert_bokeh_widgets:
bokeh_str += self.BOKEH_WIDGETS_TEMPLATE.format(
version=self.insert_bokeh_widgets)
for m in code_blocks.finditer(raw_rst):
def convert(nbfile):
basename, _ = os.path.splitext(nbfile)
meta = {'metadata': {'path': '.'}}
with open(nbfile, 'r', encoding='utf-8') as nbf:
nbdata = nbformat.read(nbf, as_version=4, encoding='utf-8')
runner = ExecutePreprocessor(timeout=600, kernel_name='probscale')
runner.preprocess(nbdata, meta)
img_folder = basename + '_files'
body_raw, images = RSTExporter().from_notebook_node(nbdata)
body_final = body_raw.replace('.. image:: ', '.. image:: {}/'.format(img_folder))
with open(basename + '.rst', 'w', encoding='utf-8') as rst_out:
rst_out.write(body_final)
for img_name, img_data in images['outputs'].items():
img_path = os.path.join(img_folder, img_name)
with open(img_path, 'wb') as img:
img.write(img_data)
def convert_notebook(nb: notebooknode.NotebookNode, resources: Dict[str, str]):
nb = _process_nb(nb)
writer = nbconvert.RSTExporter()
body, resources = writer.from_notebook_node(nb, resources)
body = _process_rst(body)
return body, resources
"""
Convert notebook object `ntbk` to rst document at `rpth`, in
directory `rdir`. Parameter `cr` is a CrossReferenceLookup
object.
"""
# Parent directory of file rpth
rdir = os.path.dirname(rpth)
# File basename
rb = os.path.basename(os.path.splitext(rpth)[0])
# Pre-process notebook prior to conversion to rst
if cr is not None:
preprocess_notebook(ntbk, cr)
# Convert notebook to rst
rex = RSTExporter()
rsttxt, rstres = rex.from_notebook_node(ntbk)
# Replace `` with ` in sphinx cross-references
rsttxt = re.sub(r':([^:]+):``(.*?)``', r':\1:`\2`', rsttxt)
# Insert a cross-reference target at top of file
reflbl = '.. _examples_' + os.path.basename(rdir) + '_' + \
rb.replace('-', '_') + ':\n\n'
rsttxt = reflbl + rsttxt
# Write the converted rst to disk
write_notebook_rst(rsttxt, rstres, rb, rdir)