-
Notifications
You must be signed in to change notification settings - Fork 15
/
__init__.py
222 lines (176 loc) · 6.38 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
"""A sphinx extension to enable interactive computations using thebe."""
import json
import os
from pathlib import Path
from docutils.parsers.rst import Directive, directives
from docutils import nodes
from sphinx.util import logging
__version__ = "0.0.8"
logger = logging.getLogger(__name__)
def st_static_path(app):
static_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "_static"))
app.config.html_static_path.append(static_path)
def init_thebe_default_config(app, env, docnames):
thebe_config = app.config.thebe_config
defaults = {
"selector": ".thebe",
"selector_input": "pre",
"selector_output": ".output",
}
for key, val in defaults.items():
if key not in thebe_config:
thebe_config[key] = val
def init_thebe_core(app, env):
config_thebe = app.config["thebe_config"]
if not config_thebe:
logger.warning("Didn't find `thebe_config` in conf.py, add to use thebe")
return
# Add core libraries
opts = {"async": "async"}
app.add_js_file(filename="https://unpkg.com/thebelab@latest/lib/index.js", **opts)
# Add configuration variables
thebe_config = f"""
const thebe_selector = "{ app.config.thebe_config['selector'] }"
const thebe_selector_input = "{ app.config.thebe_config['selector_input'] }"
const thebe_selector_output = "{ app.config.thebe_config['selector_output'] }"
"""
app.add_js_file(None, body=thebe_config)
app.add_js_file(filename="sphinx-thebe.js", **opts)
def update_thebe_context(app, doctree, docname):
"""Add thebe config nodes to this doctree."""
config_thebe = app.config["thebe_config"]
if not config_thebe:
return
# Thebe configuration
if config_thebe is True:
config_thebe = {}
if not isinstance(config_thebe, dict):
raise ValueError(
"thebe configuration must be `True` or a dictionary for configuration."
)
codemirror_theme = config_thebe.get("codemirror-theme", "abcdef")
# Thebe configuration
# Choose the kernel we'll use
meta = app.env.metadata.get(docname, {})
kernel_name = meta.get("thebe-kernel")
if kernel_name is None:
if meta.get("kernelspec"):
kernel_name = json.loads(meta["kernelspec"]).get("name")
else:
kernel_name = "python3"
# Codemirror syntax
cm_language = kernel_name
if "python" in cm_language:
cm_language = "python"
elif cm_language == "ir":
cm_language = "r"
# Create the URL for the kernel request
repo_url = config_thebe.get(
"repository_url",
"https://github.com/binder-examples/jupyter-stacks-datascience",
)
branch = config_thebe.get("repository_branch", "master")
path_to_docs = config_thebe.get("path_to_docs", ".").strip("/") + "/"
org, repo = _split_repo_url(repo_url)
# Update the doctree with some nodes for the thebe configuration
thebe_html_config = f"""
<script type="text/x-thebe-config">
{{
requestKernel: true,
binderOptions: {{
repo: "{org}/{repo}",
ref: "{branch}",
}},
codeMirrorConfig: {{
theme: "{codemirror_theme}",
mode: "{cm_language}"
}},
kernelOptions: {{
kernelName: "{kernel_name}",
path: "{path_to_docs}{str(Path(docname).parent)}"
}},
predefinedOutput: true
}}
</script>
"""
doctree.append(nodes.raw(text=thebe_html_config, format="html"))
doctree.append(
nodes.raw(text=f"<script>kernelName = '{kernel_name}'</script>", format="html")
)
def _split_repo_url(url):
"""Split a repository URL into an org / repo combination."""
if "github.com/" in url:
end = url.split("github.com/")[-1]
org, repo = end.split("/")[:2]
else:
logger.warning(f"Currently Thebe repositories must be on GitHub, got {url}")
org = repo = None
return org, repo
class ThebeButtonNode(nodes.Element):
"""Appended to the doctree by the ThebeButton directive
Renders as a button to enable thebe on the page.
If no ThebeButton directive is found in the document but thebe
is enabled, the node is added at the bottom of the document.
"""
def __init__(self, rawsource="", *children, text="Run code", **attributes):
super().__init__("", text=text)
def html(self):
text = self["text"]
return (
'<button title="{text}" class="thebelab-button thebe-launch-button"'
'onclick="initThebe()">{text}</button>'.format(text=text)
)
class ThebeButton(Directive):
"""Specify a button to activate thebe on the page
Arguments
---------
text : str (optional)
If provided, the button text to display
Content
-------
None
"""
optional_arguments = 1
final_argument_whitespace = True
has_content = False
def run(self):
kwargs = {"text": self.arguments[0]} if self.arguments else {}
return [ThebeButtonNode(**kwargs)]
# Used to render an element node as HTML
def visit_element_html(self, node):
self.body.append(node.html())
raise nodes.SkipNode
# Used for nodes that do not need to be rendered
def skip(self, node):
raise nodes.SkipNode
def setup(app):
logger.verbose("Adding copy buttons to code blocks...")
# Add our static path
app.connect("builder-inited", st_static_path)
# Set default values for the configuration
app.connect("env-before-read-docs", init_thebe_default_config)
# Include Thebe core docs
app.connect("doctree-resolved", update_thebe_context)
app.connect("env-updated", init_thebe_core)
# configuration for this tool
app.add_config_value("thebe_config", {}, "html")
# override=True in case Jupyter Sphinx has already been loaded
app.add_directive("thebe-button", ThebeButton, override=True)
# Add relevant code to headers
app.add_css_file("sphinx-thebe.css")
# ThebeButtonNode is the button that activates thebe
# and is only rendered for the HTML builder
app.add_node(
ThebeButtonNode,
html=(visit_element_html, None),
latex=(skip, None),
textinfo=(skip, None),
text=(skip, None),
man=(skip, None),
override=True,
)
return {
"version": __version__,
"parallel_read_safe": True,
"parallel_write_safe": True,
}