forked from danielfrg/pelican-jupyter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
executable file
·79 lines (62 loc) · 2.33 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import os
from pelican import signals
try:
from pelican.readers import BaseReader # new Pelican API
except ImportError:
from pelican.readers import Reader as BaseReader
try:
from pelican.readers import EXTENSIONS # old Pelican API
except ImportError:
EXTENSIONS = None
try:
import json
import markdown
from IPython.config import Config
from IPython.nbconvert.exporters import HTMLExporter
from jinja2 import FileSystemLoader
except Exception as e:
IPython = False
raise e
class iPythonNB(BaseReader):
enabled = True
file_extensions = ['ipynb']
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
def add_reader(arg):
if EXTENSIONS is None: # new pelican API:
arg.settings['READERS']['ipynb'] = iPythonNB
else:
EXTENSIONS['ipynb'] = iPythonNB
def register():
signals.initialized.connect(add_reader)