本文整理汇总了Python中IPython.nbconvert.exporters.HTMLExporter类的典型用法代码示例。如果您正苦于以下问题:Python HTMLExporter类的具体用法?Python HTMLExporter怎么用?Python HTMLExporter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HTMLExporter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: nb_renderer
def nb_renderer(full_path):
directory, base = split(full_path)
cache_file = join(directory, '.%s.html' % base)
if not current_app.config.get('DEBUG'):
try:
if isfile(cache_file) and getmtime(full_path) < getmtime(cache_file):
current_app.logger.debug('Using Cache File %s' % cache_file)
return raw_renderer(cache_file)
except:
current_app.logger.warn('There was an error reading from the cache file %s' % cache_file)
ex = HTMLExporter(extra_loaders=[current_app.jinja_env.loader],
template_file='wakari_notebook.html')
ex.environment.globals.update(current_app.jinja_env.globals)
current_app.update_template_context(ex.environment.globals)
ex.environment.globals.update(dirname=dirname(request.view_args['path']))
output, _ = ex.from_filename(full_path)
try:
with open(cache_file, 'w') as fd:
current_app.logger.debug('Writing Cache File %s' % cache_file)
fd.write(output.encode(errors='replace'))
except (OSError, IOError):
current_app.logger.warn('There was an error writing to the cache file %s' % cache_file)
try:
if isfile(cache_file): os.unlink(cache_file)
except OSError:
current_app.logger.warn('There was an error removing the cache file %s' % cache_file)
pass
return output
示例2: read
def read(self, filepath):
metadata = {}
# Files
filedir = os.path.dirname(filepath)
filename = os.path.basename(filepath)
metadata_filename = filename.split('.')[0] + '.ipynb-meta'
metadata_filepath = os.path.join(filedir, metadata_filename)
# Load metadata
if os.path.exists(metadata_filepath):
# Metadata is on a external file, process using Pelican MD Reader
md_reader = MarkdownReader(self.settings)
_content, metadata = md_reader.read(metadata_filepath)
else:
# Load metadata from ipython notebook file
ipynb_file = open(filepath)
metadata = json.load(ipynb_file)['metadata']
# Fix metadata to pelican standars
for key, value in metadata.items():
del metadata[key]
key = key.lower()
metadata[key] = self.process_metadata(key, value)
metadata['ipython'] = True
# Convert ipython notebook to html
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)
# Process using Pelican HTMLReader
content = '<body>{0}</body>'.format(content) # So Pelican HTMLReader works
parser = MyHTMLParser(self.settings, filename)
parser.feed(content)
parser.close()
body = parser.body
summary = parser.summary
metadata['summary'] = summary
# Remove some CSS styles, so it doesn't break the themes.
def filter_tags(style_text):
style_list = style_text.split('\n')
exclude = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'a', 'ul', 'ol', 'li',
'.rendered_html', '@media', '.navbar', 'nav.navbar', '.navbar-text',
'code', 'pre', 'div.text_cell_render']
style_list = [i for i in style_list if len(list(filter(i.startswith, exclude))) == 0]
ans = '\n'.join(style_list)
return '<style type=\"text/css\">{0}</style>'.format(ans)
css = '\n'.join(filter_tags(css) for css in info['inlining']['css'])
css = css + CUSTOM_CSS
body = css + body
return body, metadata
示例3: 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)')
HTMLExporter.default_template = 'basic'
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
示例4: nb2html
def nb2html(nb):
"""
Cribbed from nbviewer
"""
config = Config()
config.HTMLExporter.template_file = 'basic'
config.NbconvertApp.fileext = "html"
config.CSSHtmlHeaderTransformer.enabled = False
C = HTMLExporter(config=config)
return C.from_notebook_node(nb)[0]
示例5: compile_html
def compile_html(self, source, dest, is_two_file=True):
if flag is None:
req_missing(['ipython[notebook]>=2.0.0'], 'build this site (compile ipynb)')
makedirs(os.path.dirname(dest))
HTMLExporter.default_template = 'basic'
c = Config(self.site.config['IPYNB_CONFIG'])
exportHtml = HTMLExporter(config=c)
with io.open(dest, "w+", encoding="utf8") as out_file:
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)
out_file.write(body)
示例6: compile_html
def compile_html(self, source, dest, is_two_file=True):
if flag is None:
raise Exception('To build this site, you need '
'to install IPython 1.0.')
makedirs(os.path.dirname(dest))
HTMLExporter.default_template = 'basic'
exportHtml = HTMLExporter()
with codecs.open(dest, "w+", "utf8") as out_file:
with codecs.open(source, "r", "utf8") as in_file:
nb = in_file.read()
nb_json = nbformat.reads_json(nb)
(body, resources) = exportHtml.from_notebook_node(nb_json)
out_file.write(body)
示例7: main
def main(ipynb):
print("running %s" % ipynb)
with io.open(ipynb, encoding='utf8') as f:
nb = read(f, NO_CONVERT)
test_notebook(nb)
base, ext = os.path.splitext(ipynb)
exportHtml = HTMLExporter()
(body, resources) = exportHtml.from_notebook_node(nb)
outfile = ipynb + ".html"
open(outfile, 'w').write(encode_utf8(body))
print("wrote %s" % outfile)
示例8: read
def read(self, filepath):
filedir = os.path.dirname(filepath)
filename = os.path.basename(filepath)
_metadata = {}
# See if metadata file exists metadata
metadata_filename = filename.split('.')[0] + '.ipynb-meta'
metadata_filepath = os.path.join(filedir, metadata_filename)
if os.path.exists(metadata_filepath):
with open(metadata_filepath, 'r') as metadata_file:
content = metadata_file.read()
metadata_file = open(metadata_filepath)
md = markdown.Markdown(extensions=['meta'])
md.convert(content)
_metadata = md.Meta
for key, value in _metadata.items():
_metadata[key] = value[0]
else:
# Try to load metadata from inside ipython nb
ipynb_file = open(filepath)
_metadata = json.load(ipynb_file)['metadata']
metadata = {}
for key, value in _metadata.items():
key = key.lower()
metadata[key] = self.process_metadata(key, value)
metadata['ipython'] = True
# Converting ipythonnb to html
config = Config({'CSSHTMLHeaderTransformer':
{'enabled': True,
'highlight_class': '.highlight-ipynb'}})
exporter = HTMLExporter(config=config, template_file='basic',
filters={'highlight2html': custom_highlighter})
body, info = exporter.from_filename(filepath)
def filter_tags(s):
l = s.split('\n')
exclude = ['a', '.rendered_html', '@media']
l = [i for i in l if len(list(filter(i.startswith, exclude))) == 0]
ans = '\n'.join(l)
return STYLE_TAG.format(ans)
STYLE_TAG = '<style type=\"text/css\">{0}</style>'
css = '\n'.join(filter_tags(css) for css in info['inlining']['css'])
css = css + CUSTOM_CSS
#body = css + body
return body, metadata
示例9: 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_json(f.read())
(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'))
示例10: 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)
示例11: nb_to_html
def nb_to_html(nb, template_file = 'basic'):
""" Convert notebook `nb` to html, using template `template_file`
Parameters
----------
nb : notebook object
template_file : str, optional
template to use for notebook conversion
Returns
-------
html : str
html output
resources : ResourcesDict
Resources
"""
config = Config()
config.HTMLExporter.template_file = template_file
config.CSSHTMLHeaderTransformer.enabled = False
exporter = HTMLExporter(config=config)
return exporter.from_notebook_node(nb)
示例12: main
def main():
"""
Render STDIN as a notebook.
"""
exporter = HTMLExporter()
json_as_string = sys.stdin.read().decode("utf-8")
try:
notebook_node = reads_json(json_as_string)
except Exception:
logging.exception("Unable to parse JSON.")
html, _ = exporter.from_notebook_node(notebook_node)
sys.stderr.write("JSON was {:,} byte(s); html is {:,} byte(s).\n".format(
len(json_as_string), len(html)
))
sys.stdout.write(html.encode("utf-8"))
sys.stderr.flush()
sys.stdout.flush()
示例13: read
def read(self, filepath):
filedir = os.path.dirname(filepath)
filename = os.path.basename(filepath)
_metadata = {}
# See if metadata file exists metadata
metadata_filename = filename.split('.')[0] + '.ipynb-meta'
metadata_filepath = os.path.join(filedir, metadata_filename)
if os.path.exists(metadata_filepath):
with open(metadata_filepath, 'r') as metadata_file:
content = metadata_file.read()
metadata_file = open(metadata_filepath)
md = markdown.Markdown(extensions=['meta'])
md.convert(content)
_metadata = md.Meta
for key, value in _metadata.items():
_metadata[key] = value[0]
else:
# Try to load metadata from inside ipython nb
ipynb_file = open(filepath)
_metadata = json.load(ipynb_file)['metadata']
metadata = {}
for key, value in _metadata.items():
key = key.lower()
metadata[key] = self.process_metadata(key, value)
metadata['ipython'] = True
# Converting ipythonnb to html
config = Config({'CSSHTMLHeaderTransformer': {'enabled': True}})
here = os.path.dirname(os.path.realpath(__file__))
loader = FileSystemLoader(here)
exporter = HTMLExporter(config=config, extra_loaders=[loader],
template_file='content.tpl')
body, info = exporter.from_filename(filepath)
return body, metadata
示例14: read
def read(self, filepath):
metadata = {}
# Files
filedir = os.path.dirname(filepath)
filename = os.path.basename(filepath)
metadata_filename = filename.split('.')[0] + '.ipynb-meta'
metadata_filepath = os.path.join(filedir, metadata_filename)
# Load metadata
if os.path.exists(metadata_filepath):
# Metadata is on a external file, process using Pelican MD Reader
md_reader = MarkdownReader(self.settings)
_content, metadata = md_reader.read(metadata_filepath)
else:
# Load metadata from ipython notebook file
ipynb_file = open(filepath)
metadata = json.load(ipynb_file)['metadata']
# Fix metadata to pelican standards
for key, value in metadata.items():
del metadata[key]
key = key.lower()
metadata[key] = self.process_metadata(key, value)
metadata['ipython'] = True
# Convert ipython notebook to html
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)
for i in soup.findAll("div", {"class" : "input"}):
if i.findChildren()[1].find(text='#ignore') is not None:
i.extract()
else:
soup = content
# Process using Pelican HTMLReader
content = '<body>{0}</body>'.format(soup) # So Pelican HTMLReader works
parser = MyHTMLParser(self.settings, filename)
parser.feed(content)
parser.close()
body = parser.body
summary = parser.summary
metadata['summary'] = summary
def filter_css(style_text):
'''
HACK: IPython returns a lot of CSS including its own bootstrap.
Get only the IPython Notebook CSS styles.
'''
index = style_text.find('/*!\n*\n* IPython notebook\n*\n*/')
if index > 0:
style_text = style_text[index:]
index = style_text.find('/*!\n*\n* IPython notebook webapp\n*\n*/')
if index > 0:
style_text = style_text[:index]
style_text = re.sub(r'color\:\#0+(;)?', '', style_text)
style_text = re.sub(r'\.rendered_html[a-z0-9 ]*\{[a-z0-9:;%.#\-\s\n]+\}', '', style_text)
return '<style type=\"text/css\">{0}</style>'.format(style_text)
ipython_css = '\n'.join(filter_css(css_style) for css_style in info['inlining']['css'])
body = ipython_css + body + LATEX_CUSTOM_SCRIPT
return body, metadata
示例15: notebook
def notebook(preprocessor, tag, markup):
match = FORMAT.search(markup)
if match:
argdict = match.groupdict()
src = argdict['src']
start = argdict['start']
end = argdict['end']
else:
raise ValueError("Error processing input, "
"expected syntax: {0}".format(SYNTAX))
if start:
start = int(start)
else:
start = 0
if end:
end = int(end)
else:
end = None
settings = preprocessor.configs.config['settings']
nb_dir = settings.get('NOTEBOOK_DIR', 'notebooks')
nb_path = os.path.join('content', nb_dir, src)
if not os.path.exists(nb_path):
raise ValueError("File {0} could not be found".format(nb_path))
# Create the custom notebook converter
c = Config({'CSSHTMLHeaderTransformer':
{'enabled':True, 'highlight_class':'.highlight-ipynb'},
'SubCell':
{'enabled':True, 'start':start, 'end':end}})
template_file = 'basic'
if LooseVersion(IPython.__version__) >= '2.0':
if os.path.exists('pelicanhtml_2.tpl'):
template_file = 'pelicanhtml_2'
else:
if os.path.exists('pelicanhtml_1.tpl'):
template_file = 'pelicanhtml_1'
if LooseVersion(IPython.__version__) >= '2.0':
subcell_kwarg = dict(preprocessors=[SubCell])
else:
subcell_kwarg = dict(transformers=[SubCell])
exporter = HTMLExporter(config=c,
template_file=template_file,
filters={'highlight2html': custom_highlighter},
**subcell_kwarg)
# read and parse the notebook
with open(nb_path) as f:
nb_text = f.read()
nb_json = nbformat.reads_json(nb_text)
(body, resources) = exporter.from_notebook_node(nb_json)
for h in '123456':
body = body.replace('<h%s' % h, '<h%s class="ipynb"' % h)
body = '<div class="ipynb">\n\n' + body + "\n\n</div>"
# if we haven't already saved the header, save it here.
if not notebook.header_saved:
print ("\n ** Writing styles to _nb_header.html: "
"this should be included in the theme. **\n")
header = '\n'.join(CSS_WRAPPER.format(css_line)
for css_line in resources['inlining']['css'])
header += JS_INCLUDE
# # replace the highlight tags
header = header.replace('highlight', 'highlight-ipynb')
header = header.replace('html, body', '\n'.join(('pre.ipynb {',
' color: black;',
' background: #f7f7f7;',
' border: 0;',
' box-shadow: none;',
' margin-bottom: 0;',
' padding: 0;'
'}\n',
'html, body')))
# # create a special div for notebook
header = header.replace('body {', 'div.ipynb {')
header = header.replace('body{margin:0;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:13px;line-height:20px;color:#000;background-color:#fff}', '')
# # specialize headers
header = header.replace('html, body,',
'\n'.join((('h1.ipynb h2.ipynb h3.ipynb '
'h4.ipynb h5.ipynb h6.ipynb {'),
'h1.ipynb h2.ipynb ... {',
' margin: 0;',
' padding: 0;',
' border: 0;',
' font-size: 100%;',
' font: inherit;',
' vertical-align: baseline;',
'}\n',
#.........这里部分代码省略.........