Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import nbformat
from nbconvert import MarkdownExporter
from jinja2 import DictLoader
from traitlets.config import Config
c = Config()
# c.ExtractOutputPreprocessor.extract_output_types = set()
c.ExtractOutputPreprocessor.output_filename_template = 'images/{unique_key}_{cell_index}_{index}{extension}'
c.NbConvertBase.display_data_priority = ['application/javascript', 'text/html', 'text/markdown',
'image/svg+xml', 'text/latex', 'image/png', 'image/jpeg',
'text/plain']
nb = nbformat.read(filename, as_version=4)
dl = DictLoader({'full.tpl': TEMPLATE})
md_exporter = MarkdownExporter(config=c, extra_loaders=[
dl], template_file='full.tpl')
(body, resources) = md_exporter.from_notebook_node(nb)
self.kp_write(body, images={name.split(
'images/')[1]: data for name, data in resources.get('outputs', {}).items()})
# Add cleaned ipynb file
for cell in nb['cells']:
if cell['cell_type'] == 'code':
cell['outputs'] = [] # remove output data
cell['execution_count'] = None # reset to not executed
self.kp.write_src(os.path.basename(filename), nbformat.writes(nb))
for filename in filenames:
if filename.endswith(".ipynb") and os.path.basename(dirpath) != '.ipynb_checkpoints':
parentpath = os.path.relpath(dirpath, notebooks)
nb = nbf.read(
open(os.path.join(dirpath, filename), 'r'), as_version=4)
if rst or all:
# EXPORT RST
exporter = nbc.RSTExporter()
dir = os.path.join(project_root, RST_DIR, parentpath)
logging.info("Converting the "+filename +
" notebook to an RST format.")
_export(nb, exporter, project_root, dir,
parentpath, filename, '.rst')
if markdown or all:
# EXPORT Markdown
exporter = nbc.MarkdownExporter()
dir = os.path.join(project_root, DOCS_DIR, parentpath)
logging.info("Converting the "+filename +
" notebook to an Markdown format.")
_export(nb, exporter, project_root, dir,
parentpath, filename, '.md')
if script or all:
# EXPORT SCRIPT
exporter = nbc.ScriptExporter()
dir = os.path.join(
project_root, SCRIPTS_DIR, parentpath)
logging.info("Converting the "+filename +
" notebook to a python script.")
_export(nb, exporter, project_root, dir,
parentpath, filename, '.py')
elif filename.endswith(".Rmd"):
Returns: hugo-formatted markdown
"""
# first, update the notebook's metadata
update_notebook_metadata(path)
with open(Path(path)) as fp:
notebook = nbformat.read(fp, as_version=4)
assert 'front-matter' in notebook['metadata'], "You must have a front-matter field in the notebook's metadata"
front_matter_dict = dict(notebook['metadata']['front-matter'])
front_matter = json.dumps(front_matter_dict, indent=2)
c = Config()
c.MarkdownExporter.preprocessors = [CustomPreprocessor]
markdown_exporter = MarkdownExporter(config=c)
markdown, _ = markdown_exporter.from_notebook_node(notebook)
doctored_md = doctor(markdown)
# added comment to prevent summary creation
output = '\n'.join(('---', front_matter, '---', '', doctored_md))
return output
def display_run_notebook(filename):
"""the display function for running a notebook"""
import nbconvert
print("\nNotebook output:")
output = nbconvert.exporters.export(nbconvert.MarkdownExporter(), filename)[0]
print(output)