Python nbconvert.RSTExporter() Examples

The following are 7 code examples of nbconvert.RSTExporter(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module nbconvert , or try the search function .
Example #1
Source File: make.py    From mpl-probscale with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #2
Source File: setup.py    From openTSNE with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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)
            writer.write(body, resources, nb_name) 
Example #3
Source File: docntbk.py    From alphacsc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def parse_notebook_index(ntbkpth):
    """
    Parse the top-level notebook index file at `ntbkpth`. Returns a list of
    subdirectories in order of appearance in the index file, and a dict
    mapping subdirectory name to a description.
    """

    # Convert notebook to RST text in string
    rex = RSTExporter()
    rsttxt = rex.from_filename(ntbkpth)[0]
    # Clean up trailing whitespace
    rsttxt = re.sub(r'\n  ', r'', rsttxt, re.M | re.S)
    pthidx = {}
    pthlst = []
    lines = rsttxt.split('\n')
    for l in lines:
        m = re.match(r'^-\s+`([^<]+)\s+<([^>]+).ipynb>`__', l)
        if m:
            # List of subdirectories in order of appearance in index.rst
            pthlst.append(m.group(2))
            # Dict mapping subdirectory name to description
            pthidx[m.group(2)] = m.group(1)
    return pthlst, pthidx 
Example #4
Source File: docntbk.py    From alphacsc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def notebook_object_to_rst(ntbk, rpth, rdir, cr=None):
    """
    Convert notebook object `ntbk` to rst document at `rpth`, in directory
    `rdir`. Parameter `cr` is a CrossReferenceLookup object.
    """

    # 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 = '.. _example_' + os.path.basename(rdir) + '_' + \
            rpth.replace('-', '_') + ':\n'
    rsttxt = reflbl + rsttxt
    # Write the converted rst to disk
    write_notebook_rst(rsttxt, rstres, rpth, rdir) 
Example #5
Source File: docntbk.py    From sporco with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def parse_notebook_index(ntbkpth):
    """
    Parse the top-level notebook index file at `ntbkpth`.  Returns a
    list of subdirectories in order of appearance in the index file,
    and a dict mapping subdirectory name to a description.
    """

    # Convert notebook to RST text in string
    rex = RSTExporter()
    rsttxt = rex.from_filename(ntbkpth)[0]
    # Clean up trailing whitespace
    rsttxt = re.sub(r'\n  ', r'', rsttxt, re.M | re.S)
    pthidx = {}
    pthlst = []
    lines = rsttxt.split('\n')
    for l in lines:
        m = re.match(r'^-\s+`([^<]+)\s+<([^>]+).ipynb>`__', l)
        if m:
            # List of subdirectories in order of appearance in index.rst
            pthlst.append(m.group(2))
            # Dict mapping subdirectory name to description
            pthidx[m.group(2)] = m.group(1)
    return pthlst, pthidx 
Example #6
Source File: docntbk.py    From sporco with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def notebook_object_to_rst(ntbk, rpth, cr=None):
    """
    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) 
Example #7
Source File: rst.py    From d2l-book with Apache License 2.0 5 votes vote down vote up
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