Skip to content
Snippets Groups Projects
Commit deca584a authored by Maciej Topyla's avatar Maciej Topyla
Browse files

Deleted extra_markdown.tpl, nbconvert_fix.py, execute.py, theme/main.html,...

Deleted extra_markdown.tpl, nbconvert_fix.py, execute.py, theme/main.html, src/scripts/thebelab-custom.js, src/scripts/thebelabhelper.js
parent afa23f49
No related branches found
No related tags found
3 merge requests!34Draft: Configure and optimise mathjax for SVG and speed,!33Draft: Merging a new minimal version of the website from branch:enablingsearch,!26Fixing search function
Pipeline #121057 canceled
from pathlib import Path
import shutil
import mimetypes
import nbconvert
import notedown
from traitlets.config import Config
from nbconvert_fix import ExtractOutputPreprocessor
reader = notedown.MarkdownReader(code_regex='fenced')
mimetypes.add_type('application/vnd.plotly.v1+json', '.json')
src = Path('src')
target = Path('docs')
shutil.rmtree(target, ignore_errors=True)
target.mkdir(exist_ok=True)
shutil.copytree(src / 'figures', target / 'figures')
shutil.copytree(src / 'scripts', target / 'scripts')
shutil.copytree(src / 'styles', target / 'styles')
output_extractor = ExtractOutputPreprocessor()
output_extractor.extract_output_types = (
output_extractor.extract_output_types
| {'application/vnd.plotly.v1+json'}
)
exporter = nbconvert.MarkdownExporter(
config=Config(dict(
MarkdownExporter=dict(
preprocessors=[
nbconvert.preprocessors.ExecutePreprocessor,
output_extractor,
],
exclude_input=False,
template_file='extra_markdown.tpl',
),
NbConvertBase=dict(
display_data_priority=[
'text/html',
'text/markdown',
'image/svg+xml',
'text/latex',
'image/png',
'application/vnd.plotly.v1+json',
'image/jpeg',
'text/plain'
]
),
))
)
writer = nbconvert.writers.FilesWriter(build_directory=str(target))
for source_file in src.glob('*.md'):
fname = source_file.name[:-len('.md')]
notebook = reader.reads(source_file.read_text())
output, resources = exporter.from_notebook_node(
notebook,
resources={
'unique_key': fname,
'output_files_dir': 'figures',
'metadata': {'path': 'src/code'}
}
)
writer.write(output, resources, fname)
{% extends 'markdown.tpl' %}
{% block input %}
{% if cell.metadata.attributes and cell.metadata.attributes.initialize %}
<div class="thebelab-init-code">
<pre class="thebelab-code" data-executable="true" data-language="python">
{{cell.source}}
</pre>
</div>
{% endif %}
{% endblock %}
{% block display_data %}
{% if cell.metadata.attributes and cell.metadata.attributes.editable == 'false' and not cell.metadata.attributes.initialize %}
{{ super() }}
{% elif cell.metadata.attributes and cell.metadata.attributes.initialize %}
{% if output.data['text/html'] %}
<div>
{{ output.data['text/html'] }}
</div>
{% endif %}
{% else %}
<pre class="thebelab-code" data-executable="true" data-language="python">{{cell.source}}</pre>
<div class="thebelab-output" data-output="true" markdown="1">
{% if output.data['text/html'] %}
{{ output.data['text/html'] }}
{% else %}
{{ super() }}
{% endif %}
</div>
{% endif %}
{% endblock %}
{% block error %}
{% endblock error %}
{% block stream %}
{%- if output.name == 'stdout' -%}
{{ output.text | indent }}
{%- endif -%}
{% endblock stream %}
import sys
import os
import json
from mimetypes import guess_extension
from binascii import a2b_base64
from nbformat.notebooknode import NotebookNode
import nbconvert
from nbconvert.preprocessors.extractoutput import guess_extension_without_jpe
class ExtractOutputPreprocessor(nbconvert.preprocessors.ExtractOutputPreprocessor):
# Patches against gh-846 following
# https://github.com/jupyter/nbconvert/pull/847
def preprocess_cell(self, cell, resources, cell_index):
"""
Apply a transformation on each cell,
Parameters
----------
cell : NotebookNode cell
Notebook cell being processed
resources : dictionary
Additional resources used in the conversion process. Allows
preprocessors to pass variables into the Jinja engine.
cell_index : int
Index of the cell being processed (see base.py)
"""
#Get the unique key from the resource dict if it exists. If it does not
#exist, use 'output' as the default. Also, get files directory if it
#has been specified
unique_key = resources.get('unique_key', 'output')
output_files_dir = resources.get('output_files_dir', None)
#Make sure outputs key exists
if not isinstance(resources['outputs'], dict):
resources['outputs'] = {}
#Loop through all of the outputs in the cell
for index, out in enumerate(cell.get('outputs', [])):
if out.output_type not in {'display_data', 'execute_result'}:
continue
#Get the output in data formats that the template needs extracted
for mime_type in self.extract_output_types:
if mime_type in out.data:
data = out.data[mime_type]
# If data was JSON, it will become a NotebookNode at this point.
if isinstance(data, NotebookNode):
data = json.dumps(data)
#Binary files are base64-encoded, SVG is already XML
if mime_type in {'image/png', 'image/jpeg', 'application/pdf'}:
# data is b64-encoded as text (str, unicode),
# we want the original bytes
data = a2b_base64(data)
elif sys.platform == 'win32':
data = data.replace('\n', '\r\n').encode("UTF-8")
else:
data = data.encode("UTF-8")
ext = guess_extension_without_jpe(mime_type)
if ext is None:
ext = '.' + mime_type.rsplit('/')[-1]
if out.metadata.get('filename', ''):
filename = out.metadata['filename']
if not filename.endswith(ext):
filename+=ext
else:
filename = self.output_filename_template.format(
unique_key=unique_key,
cell_index=cell_index,
index=index,
extension=ext)
# On the cell, make the figure available via
# cell.outputs[i].metadata.filenames['mime/type']
# where
# cell.outputs[i].data['mime/type'] contains the data
if output_files_dir is not None:
filename = os.path.join(output_files_dir, filename)
out.metadata.setdefault('filenames', {})
out.metadata['filenames'][mime_type] = filename
if filename in resources['outputs']:
raise ValueError(
"Your outputs have filename metadata associated "
"with them. Nbconvert saves these outputs to "
"external files using this filename metadata. "
"Filenames need to be unique across the notebook, "
"or images will be overwritten. The filename {} is "
"associated with more than one output. The second "
"output associated with this filename is in cell "
"{}.".format(filename, cell_index)
)
#In the resources, make the figure available via
# resources['outputs']['filename'] = data
resources['outputs'][filename] = data
return cell, resources
This diff is collapsed.
function initThebelab() {
let activateButton = document.getElementById("thebelab-activate-button");
if (activateButton.classList.contains('thebelab-active')) {
return;
}
thebelab.bootstrap();
// Run all thebelab cells marked as initialization code
setTimeout(function() {
let initDivs = document.getElementsByClassName("thebelab-init-code");
for(var i = 0; i < initDivs.length; i++) {
// div.thebelab-init-code > div.thebelab-cell > button.thebelab-run-button
let runButton = initDivs[i].firstElementChild.childNodes[1]
runButton.click();
}
}, 500)
activateButton.classList.add('thebelab-active')
}
\ No newline at end of file
{% extends "base.html" %}
{% block scripts %}
<!-- ThebeLab config -->
<!-- IMPORTANT: Everytime a python file is changed, ref needs to be updated to the latest commit! -->
<script type="text/x-thebe-config">
{
predefinedOutput: true,
binderOptions: {
repoProvider: "git",
repo: "{{repo_url}}",
ref: "master",
},
requestKernel: true,
kernelOptions: {
name: "python3",
path: "src"
},
}
</script>
<!-- End ThebeLab config -->
{{ super() }}
{% endblock %}
{% block libs %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js" type="text/javascript"></script>
{{ super() }}
{% endblock %}
{% block content %}
{% if 'thebelab-code' in super() %}
<a title="Make live" id="thebelab-activate-button" class="md-icon md-content__icon" onclick="initThebelab()">
<i class="fas fa-magic"></i>
</a>
{{ super() }}
{% else %}
{{ super() }}
{% endif %}
{% endblock %}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment