本文整理汇总了Python中nbconvert.HTMLExporter.template_file方法的典型用法代码示例。如果您正苦于以下问题:Python HTMLExporter.template_file方法的具体用法?Python HTMLExporter.template_file怎么用?Python HTMLExporter.template_file使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nbconvert.HTMLExporter
的用法示例。
在下文中一共展示了HTMLExporter.template_file方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: execute
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.HTMLExporter import template_file [as 别名]
def execute(self):
print("Cleaning lowfat/reports/html ...")
old_reports = os.listdir("lowfat/reports/html")
for old_report in old_reports:
print("- Removing lowfat/reports/html/{}".format(old_report))
os.remove("lowfat/reports/html/{}".format(old_report))
print("Cleaning of lowfat/reports/html is complete.")
notebook_filenames = os.listdir("lowfat/reports")
for notebook_filename in notebook_filenames:
if not notebook_filename.endswith(".ipynb"):
continue
print("Processing lowfat/reports/{}".format(notebook_filename))
# Based on Executing notebooks, nbconvert Documentation by Jupyter Development Team.
# https://nbconvert.readthedocs.io/en/latest/execute_api.html
with open("lowfat/reports/{}".format(notebook_filename)) as file_:
notebook = nbformat.read(file_, as_version=4)
# Kernel is provided by https://github.com/django-extensions/django-extensions/
execute_preprocessor = ExecutePreprocessor(timeout=600, kernel_name='django_extensions')
execute_preprocessor.preprocess(notebook, {'metadata': {'path': '.'}})
html_exporter = HTMLExporter()
html_exporter.template_file = 'basic'
(body, dummy_resources) = html_exporter.from_notebook_node(notebook)
with open('lowfat/reports/html/{}.html'.format(notebook_filename), 'wt') as file_:
file_.write(body)
示例2: nb_to_html
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.HTMLExporter import template_file [as 别名]
def nb_to_html(root, template='basic', version=4, timeout=600, kernel='python3'):
'''
This functions executes a Jupyter notebook and creates the related
HTML file.
Args:
root (str): name of the file without the .ipynb extension
template (str): name of the template (to be in the current folder as template.tpl)
version (int): version of the notebook
timeout (float): maximum time spent per cell
kernel (str)
Returns:
None
The function executes root.ipynb into root_exe.ipynb and creates the file root.html.
'''
with open(root + '.ipynb') as f:
nb = nbformat.read(f, as_version=version)
ep = ExecutePreprocessor(timeout=timeout, kernel_name=kernel)
ep.preprocess(nb, {'metadata': {'path': '.'}})
with open(root + '_exe.ipynb', 'wt') as f:
nbformat.write(nb, f)
html_exporter = HTMLExporter()
html_exporter.template_file = template
with open(root + '_exe.ipynb', mode='r') as f:
notebook = nbformat.reads(''.join(f.readlines()), as_version=version)
(body, _) = html_exporter.from_notebook_node(notebook)
codecs.open(root + '.html', 'w', encoding='utf-8').write(body)
示例3: bundle_notebook
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.HTMLExporter import template_file [as 别名]
def bundle_notebook(vid, fileid):
"""Return a file from the bundle"""
from ambry.orm.file import File
import nbformat
from traitlets.config import Config
from nbconvert import HTMLExporter
b = aac.library.bundle(vid)
nbfile = b.build_source_files.file_by_id(fileid)
notebook = nbformat.reads(nbfile.unpacked_contents, as_version=4)
html_exporter = HTMLExporter()
html_exporter.template_file = 'basic'
(body, resources) = html_exporter.from_notebook_node(notebook)
cxt = dict(
vid=vid,
b=b,
fileid=fileid,
nbfile=nbfile,
notebooks=b.build_source_files.list_records(File.BSFILE.NOTEBOOK),
notebook=notebook,
notebook_html=body,
**aac.cc
)
return aac.render('bundle/notebook.html', **cxt)
示例4: write_html
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.HTMLExporter import template_file [as 别名]
def write_html(self):
print("writing", self.html)
html_exporter = HTMLExporter()
html_exporter.template_file = 'full'
# do a deeo copy to any chance of overwriting the original notebooks
content = copy.deepcopy(self.content)
content.cells = content.cells[2:-1]
content.cells[0].source = "# " + self.numbered_title
(body, resources) = html_exporter.from_notebook_node(content)
with open(self.html, 'w') as f:
f.write(body)
示例5: render
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.HTMLExporter import template_file [as 别名]
def render(file):
"""Generate the result HTML."""
fp = file.open()
content = fp.read()
fp.close()
notebook = nbformat.reads(content.decode('utf-8'), as_version=4)
html_exporter = HTMLExporter()
html_exporter.template_file = 'basic'
(body, resources) = html_exporter.from_notebook_node(notebook)
return body, resources
示例6: _nbconvert_to_html
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.HTMLExporter import template_file [as 别名]
def _nbconvert_to_html(cls, doc):
'''Use nbconvert to render a notebook as HTML.
Strip the headings from the first markdown cell to avoid showing the
page title twice on the blog.
'''
if doc.cells and doc.cells[0].cell_type == 'markdown':
source = doc.cells[0].source
doc.cells[0].source = re.sub('^# .*\n', '', source)
e = HTMLExporter()
e.template_file = 'basic'
return e.from_notebook_node(doc)[0]
示例7: post
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.HTMLExporter import template_file [as 别名]
def post(self):
id=self.get_argument("path")
print id
db=create_engine('postgresql://postgres:[email protected]/ishtar')
fileContent=reads_base64(pgquery.get_file(db, "share", id, include_content=True)['content'])
#notebook= nbformat.reads(fileContent, as_version=4)
notebook=fileContent
db.dispose()
html_exporter = HTMLExporter()
html_exporter.template_file = 'basic'
(body, resources) = html_exporter.from_notebook_node(notebook)
self.write(body)
示例8: nb2html
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.HTMLExporter import template_file [as 别名]
def nb2html(nb_filepath):
"""
Convert notebook to html string.
Args:
nb_filepath (str): Path of notbook file
Returns:
(str): HMTL of converted notebook.
"""
# Save notebook
exporter = HTMLExporter()
exporter.template_file = 'basic'
output, resources = exporter.from_filename(nb_filepath)
return output
示例9: notebook2html
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.HTMLExporter import template_file [as 别名]
def notebook2html(index: dict, in_dir: str, templates: dict, host: str,
out_dir: str, content_dirname: str):
"""
Convert jupyter notebook to html. See relevant docs here:
https://nbconvert.readthedocs.io/en/latest/nbconvert_library.html#Quick-overview
Possible enhancements:
- extract images from notebook
- render from url
"""
new_index = []
for item in index:
if item.get('format') == 'ipynb':
# Render notebook as html
in_fp = f'{in_dir}/{item["in_pth"]}'
notebook = nbformat.read(in_fp, as_version=4)
html_exporter = HTMLExporter()
html_exporter.template_file = 'basic'
nb_html, resources = html_exporter.from_notebook_node(notebook)
# Render navbar
navbar = templates['navbar'].render()
# Render comments section
filename = ntpath.basename(in_fp)[:-len('.ipynb')]
page = {'url': f'{host}/{content_dirname}/{filename}.html',
'identifier': filename}
comments = templates['comments'].render(page=page)
# Render entire page
html = {'navbar': navbar, 'notebook': nb_html, 'comments': comments}
body = templates['notebook'].render(html=html)
# Write html to file
out_fp = f'{out_dir}/{filename}.html'
data2file(body, out_fp)
# Add html path to index
out_pth = f'./{content_dirname}/{filename}.html'
item_new = add2dict('out_pth', out_pth, item)
else:
item_new = item
new_index.append(item_new)
return new_index
示例10: export_notebook
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.HTMLExporter import template_file [as 别名]
def export_notebook(nb, cid):
nb = nbformat.from_dict(nb)
html_exporter = HTMLExporter()
html_exporter.template_file = 'basic'
body = html_exporter.from_notebook_node(nb)[0]
soup = BeautifulSoup(body, 'html.parser')
# mark cells with special name for toggling, and
# TODO make element id's unique by appending cid
for div in soup.find_all('div', 'output_wrapper'):
tag = div.find('h2')
div['name'] = tag.text.split()[0]
# name divs for toggling code_cells
for div in soup.find_all('div', 'input'):
div['name'] = 'Input'
# separate script
script = []
for s in soup.find_all('script'):
script.append(s.text)
s.extract() # remove javascript
return soup.prettify(), '\n'.join(script)
示例11: convert_notebooks
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.HTMLExporter import template_file [as 别名]
def convert_notebooks(in_directory, html_directory, static_directory):
dl = DictLoader({
'post.tpl':
"""
{%- extends 'basic.tpl' -%}
{% block body %}---
title: {{nb.metadata['title']}}
notebook: {{resources['metadata']['path']}}/{{resources['metadata']['name']}}.ipynb
date: {{nb.metadata['date']}}
---
{{ super() }}
{% endblock body %}
"""
})
c = Config()
c.HTMLExporter.preprocessors = [
'nbconvert.preprocessors.ExtractOutputPreprocessor'
]
html_exporter = HTMLExporter(config=c, extra_loaders=[dl])
html_exporter.template_file = 'post.tpl'
writer = FilesWriter(build_directory=html_directory)
for notebook_file in glob(path.join(in_directory, '*.ipynb')):
out_name, _ = path.splitext(path.basename(notebook_file))
out_name = out_name.lower().replace(' ', '-')
print('Converting {}'.format(notebook_file))
(body, resources) = html_exporter.from_filename(
notebook_file,
resources={'output_files_dir': out_name})
writer.write(body, resources, notebook_name=out_name)
shutil.rmtree(path.join(static_directory, out_name), True)
rename(path.join(html_directory, out_name),
path.join(static_directory, out_name))
示例12: notebook_to_html
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.HTMLExporter import template_file [as 别名]
def notebook_to_html(text, record=None):
# construct full path to the notebook (in same dir)
directory,contents_lr = os.path.split(record.source_filename)
notebook_path = os.path.join(directory,text)
# verify that the named notebook is among the attachments
for att in record.attachments:
if att.attachment_filename == notebook_path:
break
else:
raise RuntimeError("Couldn't find notebook file")
# render it
with open(notebook_path) as fl:
nb = nbformat.read(fl, as_version=4)
exporter = HTMLExporter()
exporter.template_file = 'basic'
body,resources = exporter.from_notebook_node(nb)
return body,resources
示例13: HTMLExporter
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.HTMLExporter import template_file [as 别名]
import os.path, re, nbformat, jupyter_contrib_nbextensions
from nbconvert.preprocessors import Preprocessor
from nbconvert import HTMLExporter
from traitlets.config import Config
from pathlib import Path
__all__ = ['read_nb', 'convert_nb', 'convert_all']
exporter = HTMLExporter(Config())
exporter.exclude_input_prompt=True
exporter.exclude_output_prompt=True
#Loads the template to deal with hidden cells.
exporter.template_file = 'jekyll.tpl'
path = Path(__file__).parent
exporter.template_path.append(str(path))
def read_nb(fname):
"Read the notebook in `fname`."
with open(fname,'r') as f: return nbformat.reads(f.read(), as_version=4)
def convert_nb(fname, dest_path='.'):
"Convert a notebook `fname` to html file in `dest_path`."
from .gen_notebooks import remove_undoc_cells, remove_code_cell_jupyter_widget_state_elem
nb = read_nb(fname)
nb['cells'] = remove_undoc_cells(nb['cells'])
nb['cells'] = remove_code_cell_jupyter_widget_state_elem(nb['cells'])
fname = Path(fname).absolute()
dest_name = fname.with_suffix('.html').name
meta = nb['metadata']
meta_jekyll = meta['jekyll'] if 'jekyll' in meta else {'title': fname.with_suffix('').name}
meta_jekyll['nb_path'] = f'{fname.parent.name}/{fname.name}'
示例14: ExecutePreprocessor
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.HTMLExporter import template_file [as 别名]
# coding = UTF-8
import nbformat
from nbconvert import HTMLExporter, LatexExporter, MarkdownExporter
from nbconvert.preprocessors import ExecutePreprocessor
import matplotlib.pyplot as plt
notebook_filename = r'E:\github\workrobot\workrobot\application\notebook\try_two.ipynb'
ep = ExecutePreprocessor(timeout=600, kernel_name='python3')
with open(notebook_filename) as f:
nb = nbformat.read(f, as_version=4)
print(nb)
ep.preprocess(nb, {'metadata': {'path': r'E:\github\workrobot\workrobot\application\notebook'}})
print(nb)
html_exporter = HTMLExporter()
html_exporter.template_file = 'basic'
# 3. Process the notebook we loaded earlier
(body, resources) = MarkdownExporter().from_notebook_node(nb)
print(body)
print(resources['outputs']['output_0_0.png'])
with open('executed_notebook.ipynb', 'wt') as f:
nbformat.write(nb, f)
示例15: get_html_export
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.HTMLExporter import template_file [as 别名]
def get_html_export(self, nb):
exporter = HTMLExporter()
exporter.template_file = 'basic'
return exporter.from_notebook_node(nb)