Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def __call__(self, exporter=None, filename=None):
raw_nb = nbconvert.exporters.Exporter().from_filename(self.filename)
raw_nb[0].metadata.setdefault('kernelspec', {})['name'] = 'python'
exec_nb = nbconvert.preprocessors.ExecutePreprocessor(timeout=600).preprocess(*raw_nb)
if exporter is not None:
out_nb = nbconvert.exporters.MarkdownExporter().from_notebook_node(*exec_nb)
if filename is None:
assert self.filename.endswith('.ipynb')
filename = self.filename[:-6] + exporter.file_extension
open(filename, 'w').write(out_nb[0].encode('utf-8'))
def __call__(self, exporter=None, filename=None):
raw_nb = nbconvert.exporters.Exporter().from_filename(self.filename)
raw_nb[0].metadata.setdefault('kernelspec', {})['name'] = 'python'
exec_nb = nbconvert.preprocessors.ExecutePreprocessor().preprocess(*raw_nb)
if exporter is not None:
out_nb = nbconvert.exporters.MarkdownExporter().from_notebook_node(*exec_nb)
if filename is None:
assert self.filename.endswith('.ipynb')
filename = self.filename[:-6] + exporter.file_extension
open(filename, 'w').write(out_nb[0].encode('utf-8'))
def export_notebook(ipath, opath):
"""
Exports the notebook at `ipath` to a python file at `opath`.
"""
import nbconvert
from traitlets.config import Config
# Create nbconvert configuration to ignore text cells
c = Config()
c.TemplateExporter.exclude_markdown = True
# Load notebook, convert to python
e = nbconvert.exporters.PythonExporter(config=c)
code, __ = e.from_filename(ipath)
# Remove "In [1]:" comments
r = re.compile(r'(\s*)# In\[([^]]*)\]:(\s)*')
code = r.sub('\n\n', code)
# Store as executable script file
with open(opath, 'w') as f:
f.write('#!/usr/bin/env python')
f.write(code)
os.chmod(opath, 0o775)
def __call__(self, exporter=None, filename=None):
raw_nb = nbconvert.exporters.Exporter().from_filename(self.filename)
raw_nb[0].metadata.setdefault('kernelspec', {})['name'] = 'python'
exec_nb = nbconvert.preprocessors.ExecutePreprocessor().preprocess(*raw_nb)
if exporter is not None:
out_nb = nbconvert.exporters.MarkdownExporter().from_notebook_node(*exec_nb)
if filename is None:
assert self.filename.endswith('.ipynb')
filename = self.filename[:-6] + exporter.file_extension
open(filename, 'w').write(out_nb[0].encode('utf-8'))
def generate_tutorials():
basepath = os.path.dirname(__file__)
tutorial_path = os.path.join(basepath, '..', '_static', 'notebooks')
tutorials = [i for i in os.listdir(tutorial_path) if i.endswith('.ipynb')]
for k in tutorials:
notebook_path = os.path.join(tutorial_path, k)
html_path = os.path.join(tutorial_path, k.replace('.ipynb', '.html'))
nb = nbformat.read(notebook_path, 4)
html, resource = nbconvert.exporters.export(nbconvert.exporters.get_exporter('html'), nb)
# Remove plotly javascript
start_string = """<div class="output_html rendered_html output_subarea">\n\n</div>"""
end = html.find(end_string)
html_new = html[:start] + html[end + len(end_string):]
# remove call to internal javascript from plotly plots
html_new = html_new.replace('require(["plotly"], function(Plotly) {', '')
html_new = html_new.replace(')});', ');')
# Also get rid of table borders
html_new = html_new.replace('border="1" ', '')
def display_run_notebook(filename):
"""display function for running a notebook"""
import nbconvert
print("\nNotebook output:")
output = nbconvert.exporters.export(nbconvert.MarkdownExporter(), filename)[0]
print(output)
# Process the notebook.
ep = ExecutePreprocessor(timeout=None)
# Sometimes the default startup timeout exceed the default of 60 seconds.
ep.startup_timeout = 180
# Set the title name, does not appear in all exporters
resource_data = {'metadata': {'name': 'YANK Simulation Report: {}'.format(file_base_name)}}
print("Processing notebook now, this may take a while...")
processed_notebook, resources = ep.preprocess(loaded_notebook, resource_data)
# Retrieve exporter
exporter_data = exporters[file_extension.lower()]
# Determine exporter and data output type
exporter = exporter_data['exporter']
write_type = exporter_data['write_type']
with open(output, 'w{}'.format(write_type)) as notebook:
exported_notebook, _ = nbconvert.exporters.export(exporter, processed_notebook, resources=resources)
notebook.write(exported_notebook)
return True
# Read the temp notebook into a notebook_node object nbconvert can work with
with open(tmp_nb_path, 'r') as tmp_notebook:
loaded_notebook = nbformat.read(tmp_notebook, as_version=4)
ep = ExecutePreprocessor(timeout=None)
# Set the title name, does not appear in all exporters
resource_data = {'metadata': {'name': 'YANK Simulation Report: {}'.format(file_base_name)}}
# Process notebook
print("Processing notebook now, this may take a while...")
processed_notebook, resources = ep.preprocess(loaded_notebook, resource_data)
# Retrieve exporter
exporter_data = exporters[file_extension.lower()]
# Determine exporter and data output type
exporter = exporter_data['exporter']
write_type = exporter_data['write_type']
with open(output, 'w{}'.format(write_type)) as notebook:
exported_notebook, _ = nbconvert.exporters.export(exporter, processed_notebook, resources=resources)
notebook.write(exported_notebook)
else:
# No pre-rendering, no need to process anything
with open(output, 'w') as notebook:
notebook.write(notebook_text)
return True