本文整理汇总了Python中nbconvert.exporters.HTMLExporter类的典型用法代码示例。如果您正苦于以下问题:Python HTMLExporter类的具体用法?Python HTMLExporter怎么用?Python HTMLExporter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HTMLExporter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_html_from_filepath
def get_html_from_filepath(filepath, start=0, end=None, preprocessors=[], template=None):
"""Return the HTML from a Jupyter Notebook
"""
template_file = 'basic'
extra_loaders = []
if template:
extra_loaders.append(jinja2.FileSystemLoader([os.path.dirname(template)]))
template_file = os.path.basename(template)
config = get_config()
config.update({'CSSHTMLHeaderTransformer': {
'enabled': True,
'highlight_class': '.highlight-ipynb'},
'SubCell': {
'enabled':True,
'start':start,
'end':end}})
exporter = HTMLExporter(config=config,
template_file=template_file,
extra_loaders=extra_loaders,
filters={'highlight2html': custom_highlighter},
preprocessors=[SubCell] + preprocessors)
config.CSSHTMLHeaderPreprocessor.highlight_class = " .highlight pre "
content, info = exporter.from_filename(filepath)
return content, info
示例2: _process
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
示例3: _compile_string
def _compile_string(self, nb_json):
"""Export notebooks as HTML strings."""
if flag is None:
req_missing(['ipython[notebook]>=2.0.0'], 'build this site (compile ipynb)')
c = Config(self.site.config['IPYNB_CONFIG'])
exportHtml = HTMLExporter(config=c)
body, _ = exportHtml.from_notebook_node(nb_json)
return body
示例4: _compile_string
def _compile_string(self, nb_json):
"""Export notebooks as HTML strings."""
self._req_missing_ipynb()
c = Config(self.site.config['IPYNB_CONFIG'])
c.update(get_default_jupyter_config())
exportHtml = HTMLExporter(config=c)
body, _ = exportHtml.from_notebook_node(nb_json)
return body
示例5: render_ipynb
def render_ipynb(full_path):
"""
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')
示例6: get_html_from_filepath
def get_html_from_filepath(filepath,
start=0,
end=None,
template=None):
"""Return the HTML from a Jupyter Notebook
"""
preprocessors_ = [SubCell]
template_file = "basic"
extra_loaders = []
if template:
extra_loaders.append(
jinja2.FileSystemLoader([os.path.dirname(template)]))
template_file = os.path.basename(template)
# Load the user's nbconvert configuration
app = NbConvertApp()
app.load_config_file()
app.config.update({
# This Preprocessor changes the pygments css prefixes
# from .highlight to .highlight-ipynb
"CSSHTMLHeaderPreprocessor": {
"enabled": True,
"highlight_class": ".highlight-ipynb",
},
"SubCell": {
"enabled": True,
"start": start,
"end": end
},
})
# Overwrite Custom jinja filters
# This is broken right now so needs fix from below
# https://github.com/jupyter/nbconvert/pull/877
filters = {
"highlight_code": custom_highlight_code
}
exporter = HTMLExporter(
config=app.config,
template_file=template_file,
extra_loaders=extra_loaders,
filters=filters,
preprocessors=preprocessors_,
)
content, info = exporter.from_filename(filepath)
# Fix for nbconvert bug
# content = content.replace("<pre>", '<pre class="highlight highlight-ipynb">')
# end-fix
# Since we make a Markdown file we need to remove empty lines and strip
content = "\n".join([line.rstrip() for line in content.split("\n") if line.rstrip()])
return content, info
示例7: compile_html_string
def compile_html_string(self, source, is_two_file=True):
"""Export notebooks as HTML strings."""
if flag is None:
req_missing(['ipython[notebook]>=2.0.0'], 'build this site (compile ipynb)')
c = Config(self.site.config['IPYNB_CONFIG'])
exportHtml = HTMLExporter(config=c)
with io.open(source, "r", encoding="utf8") as in_file:
nb_json = nbformat.read(in_file, current_nbformat)
(body, resources) = exportHtml.from_notebook_node(nb_json)
return body
示例8: generate_exercises
def generate_exercises():
p = Path(*EXERCISES_DIR)
exporter = HTMLExporter()
exporter.register_preprocessor(ClearOutputPreprocessor(), enabled=True)
for exercise in p.iterdir():
if exercise.suffix == '.ipynb':
html, _ = exporter.from_file(exercise.open())
with open(exercise.with_suffix('.html').name, 'w') as f:
f.write(html)
示例9: render_notebook
def render_notebook(self, filename, site=None, data=None, lang=None, post=None):
c = Config(self.site.config['IPYNB_CONFIG'])
export_html = HTMLExporter(config=c)
(notebook_raw, _) = export_html.from_filename(filename)
# The raw HTML contains garbage (scripts and styles). Extract only div id=notebook-container and children
notebook_html = lxml.html.fromstring(notebook_raw)
notebook_code = lxml.html.tostring(notebook_html.xpath('//*[@id="notebook-container"]')[0], encoding='unicode')
return notebook_code, [filename]
示例10: _compile_string
def _compile_string(self, nb_json):
"""Export notebooks as HTML strings."""
self._req_missing_ipynb()
c = Config(self.site.config['IPYNB_CONFIG'])
c.update(get_default_jupyter_config())
if 'template_file' not in self.site.config['IPYNB_CONFIG'].get('Exporter', {}):
c['Exporter']['template_file'] = 'basic.tpl' # not a typo
exportHtml = HTMLExporter(config=c)
body, _ = exportHtml.from_notebook_node(nb_json)
return body
示例11: convert_ipynb_to_html
def convert_ipynb_to_html(notebook_file, html_file):
"""
Convert the given `notebook_file` to HTML and
write it to `html_file`.
"""
# set a high timeout for datasets with a large number of features
report_config = Config({'ExecutePreprocessor': {'enabled': True,
'timeout': 600},
'HTMLExporter': {'template_path': [template_path],
'template_file': 'report.tpl'}})
exportHtml = HTMLExporter(config=report_config)
output, resources = exportHtml.from_filename(notebook_file)
open(html_file, mode='w', encoding='utf-8').write(output)
示例12: get_html_from_filepath
def get_html_from_filepath(filepath):
"""Convert ipython notebook to html
Return: html content of the converted notebook
"""
config = Config({"CSSHTMLHeaderTransformer": {"enabled": True, "highlight_class": ".highlight-ipynb"}})
exporter = HTMLExporter(config=config, template_file="basic", filters={"highlight2html": custom_highlighter})
content, info = exporter.from_filename(filepath)
if BeautifulSoup:
soup = BeautifulSoup(content, "html.parser")
for i in soup.findAll("div", {"class": "input"}):
if i.findChildren()[1].find(text="#ignore") is not None:
i.extract()
content = soup.decode(formatter=None)
return content, info
示例13: main
def main(app):
static_dir = os.path.join(app.builder.srcdir, '_static')
target_dir = os.path.join(app.builder.srcdir, 'notebooks')
source_dir = os.path.abspath(os.path.join(app.builder.srcdir,
'..', 'notebooks'))
rendered_dir = os.path.join(target_dir, 'rendered')
if not os.path.exists(static_dir):
os.makedirs(static_dir)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
if not os.path.exists(rendered_dir):
os.makedirs(rendered_dir)
nbroots = []
nbtitles = []
exporter = HTMLExporter(template_file='full')
for nb_src in glob.glob(os.path.join(source_dir, '*.ipynb')):
print("converting notebook {0}".format(nb_src))
basedir, nbname = os.path.split(nb_src)
nb_dest = os.path.join(target_dir, nbname)
shutil.copyfile(nb_src, nb_dest)
with open(nb_dest, 'r') as f:
nb_json = nbformat.reads(f.read(), as_version = 4)
(body, resources) = exporter.from_notebook_node(nb_json)
root, ext = os.path.splitext(nbname)
nb_html_dest = os.path.join(rendered_dir, root + '.html')
with open(nb_html_dest, 'w') as f:
f.write(body)
nbroots.append(root)
nbtitles.append(get_notebook_title(nb_json, root))
for nbroot, nbtitle in zip(nbroots, nbtitles):
with open(os.path.join(target_dir, nbroot + '.rst'), 'w') as f:
f.write(RST_TEMPLATE.render(title=nbtitle, nbroot=nbroot))
with open(os.path.join(target_dir, 'index.rst'), 'w') as f:
f.write(INDEX_TEMPLATE.render(notebooks=nbroots,
sphinx_tag='notebook-examples'))
示例14: render
def render(self):
try:
with open(self.file_path, 'r') as file_pointer:
notebook = nbformat.reads(file_pointer.read(), as_version=4)
except ValueError:
raise exceptions.InvalidFormat('Could not read ipython notebook file.')
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)
示例15: get_html_from_filepath
def get_html_from_filepath(filepath):
"""Convert ipython notebook to html
Return: html content of the converted notebook
"""
config = Config({'CSSHTMLHeaderTransformer': {'enabled': True,
'highlight_class': '.highlight-ipynb'}})
config.HTMLExporter.preprocessors = [HtmlLinksPreprocessor]
config.HtmlLinksPreprocessor['enabled'] = True
path = os.path.dirname(os.path.realpath(__file__))
exporter = HTMLExporter(config=config, template_file='no_code',
template_path=['.', path + '/../../../scripts/'],
filters={'highlight2html': custom_highlighter})
content, info = exporter.from_filename(filepath)
return content, info