Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def nb_to_html(nb_path):
"""convert notebook to html"""
exporter = HTMLExporter(template_file='full')
output, resources = exporter.from_filename(nb_path)
header = output.split('', 1)[1].split('',1)[0]
body = output.split('', 1)[1].split('',1)[0]
# http://imgur.com/eR9bMRH
header = header.replace('', re.MULTILINE)
header = comp.sub('', header)
# Filter out styles that conflict with the sphinx theme.
filter_strings = [
'navbar',
def _process(self):
config = Config()
config.HTMLExporter.preprocessors = [CppHighlighter]
config.HTMLExporter.template_file = 'basic'
with self.attachment.file.open() as f:
notebook = nbformat.read(f, as_version=4)
html_exporter = HTMLExporter(config=config)
body, resources = html_exporter.from_notebook_node(notebook)
css_code = '\n'.join(resources['inlining'].get('css', []))
nonce = str(uuid4())
html = render_template('previewer_jupyter:ipynb_preview.html', attachment=self.attachment,
html_code=body, css_code=css_code, nonce=nonce)
response = current_app.response_class(html)
# Use CSP to restrict access to possibly malicious scripts or inline JS
csp_header = "script-src cdn.mathjax.org 'nonce-{}';".format(nonce)
response.headers['Content-Security-Policy'] = csp_header
response.headers['X-Webkit-CSP'] = csp_header
# IE10 doesn't have proper CSP support, so we need to be more strict
response.headers['X-Content-Security-Policy'] = "sandbox allow-same-origin;"
return response
def nbhtml(input_name: str,
input_path: str = './',
output_name: Optional[str] = None,
output_path: str = './') -> None:
if not input_path.endswith('/'):
input_path += '/'
se = HTMLExporter()
base, ext = splitext(input_path+input_name)
script, resources = se.from_filename(input_path+input_name)
if output_name is None:
script_fname = base + resources.get('output_extension', '.txt')
with open(output_path+script_fname, 'wt') as f:
f.write(script)
else:
if not output_path.endswith('/'):
output_path += '/'
with open(output_path+output_name, 'wt') as f:
f.write(script)
def _exporter_class_default(self):
return HTMLExporter
if not requires_prerendering:
# No pre-rendering, no need to process anything
with open(output, 'w') as notebook:
notebook.write(notebook_text)
else:
# Cast to static output
print("Rendering notebook as a {} file...".format(file_extension))
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
import nbconvert.exporters
# Categorize exporters based on extension, requires exporter object and data type output
# 'b' = byte types output, e.g. PDF
# 't' = text based output, e.g. HTML or even raw notebook, human-readable-like
exporters = {
".pdf": {'exporter': nbconvert.exporters.PDFExporter, 'write_type': 'b'},
".html": {'exporter': nbconvert.exporters.HTMLExporter, 'write_type': 't'},
".ipynb": {'exporter': nbconvert.exporters.NotebookExporter, 'write_type': 't'}
}
# Load the notebook through Jupyter.
loaded_notebook = nbformat.read(io.StringIO(notebook_text), as_version=4)
# 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()]
def render(self):
try:
with open(self.file_path, 'r') as file_pointer:
notebook = nbformat.reads(file_pointer.read(), as_version=4)
except ValueError as err:
raise exceptions.InvalidFormatError(
'Could not read ipython notebook file. {}'.format(str(err)),
extension=self.metadata.ext,
download_url=str(self.metadata.download_url),
original_exception=err,
)
exporter = HTMLExporter(config=Config({
'HTMLExporter': {
'template_file': 'basic',
},
'CSSHtmlHeaderTransformer': {
'enabled': False,
},
}))
(body, _) = exporter.from_notebook_node(notebook)
return self.TEMPLATE.render(base=self.assets_url, body=body)
def render_ipynb(full_path, format):
"""
Render a given ipynb file
"""
exporter = HTMLExporter()
with open(full_path, encoding='utf-8') as file_handle:
html, res = exporter.from_file(file_handle)
return Response(html, mimetype='text/html')
html_file : str
Path to output HTML file.
Note
----
This function is also exposed as the
:ref:`render_notebook ` command-line utility.
"""
# set a high timeout for datasets with a large number of features
report_config = Config({'ExecutePreprocessor': {'enabled': True,
'timeout': 3600},
'HTMLExporter': {'template_path': [template_path],
'template_file': 'report.tpl'}})
exportHtml = HTMLExporter(config=report_config)
output, _ = exportHtml.from_filename(notebook_file)
open(html_file, mode='w', encoding='utf-8').write(output)