Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
quarto-dev
GitHub Repository: quarto-dev/quarto-cli
Path: blob/main/src/resources/jupyter/lang/python/setup.py
12923 views
1
2
# imports
3
import os
4
import sys
5
import types
6
import json
7
import base64
8
9
# figure size/format
10
fig_width = {fig_width}
11
fig_height = {fig_height}
12
fig_format = '{fig_format}'
13
fig_dpi = {fig_dpi}
14
interactivity = '{interactivity}'
15
is_shiny = {is_shiny}
16
is_dashboard = {is_dashboard}
17
plotly_connected = {plotly_connected}
18
19
# matplotlib defaults / format
20
try:
21
import matplotlib.pyplot as plt
22
plt.rcParams['figure.figsize'] = (fig_width, fig_height)
23
plt.rcParams['figure.dpi'] = fig_dpi
24
plt.rcParams['savefig.dpi'] = "figure"
25
26
# IPython 7.14 deprecated set_matplotlib_formats from IPython
27
try:
28
from matplotlib_inline.backend_inline import set_matplotlib_formats
29
except ImportError:
30
# Fall back to deprecated location for older IPython versions
31
from IPython.display import set_matplotlib_formats
32
33
set_matplotlib_formats(fig_format)
34
except Exception:
35
pass
36
37
# plotly use connected mode
38
try:
39
import plotly.io as pio
40
if plotly_connected:
41
pio.renderers.default = "notebook_connected"
42
else:
43
pio.renderers.default = "notebook"
44
for template in pio.templates.keys():
45
pio.templates[template].layout.margin = dict(t=30,r=0,b=0,l=0)
46
except Exception:
47
pass
48
49
# disable itables paging for dashboards
50
if is_dashboard:
51
try:
52
from itables import options
53
options.dom = 'fiBrtlp'
54
options.maxBytes = 1024 * 1024
55
options.language = dict(info = "Showing _TOTAL_ entries")
56
options.classes = "display nowrap compact"
57
options.paging = False
58
options.searching = True
59
options.ordering = True
60
options.info = True
61
options.lengthChange = False
62
options.autoWidth = False
63
options.responsive = True
64
options.keys = True
65
options.buttons = []
66
except Exception:
67
pass
68
69
try:
70
import altair as alt
71
# By default, dashboards will have container sized
72
# vega visualizations which allows them to flow reasonably
73
theme_sentinel = '_quarto-dashboard-internal'
74
def make_theme(name):
75
nonTheme = alt.themes._plugins[name]
76
def patch_theme(*args, **kwargs):
77
existingTheme = nonTheme()
78
if 'height' not in existingTheme:
79
existingTheme['height'] = 'container'
80
if 'width' not in existingTheme:
81
existingTheme['width'] = 'container'
82
83
if 'config' not in existingTheme:
84
existingTheme['config'] = dict()
85
86
# Configure the default font sizes
87
title_font_size = 15
88
header_font_size = 13
89
axis_font_size = 12
90
legend_font_size = 12
91
mark_font_size = 12
92
tooltip = False
93
94
config = existingTheme['config']
95
96
# The Axis
97
if 'axis' not in config:
98
config['axis'] = dict()
99
axis = config['axis']
100
if 'labelFontSize' not in axis:
101
axis['labelFontSize'] = axis_font_size
102
if 'titleFontSize' not in axis:
103
axis['titleFontSize'] = axis_font_size
104
105
# The legend
106
if 'legend' not in config:
107
config['legend'] = dict()
108
legend = config['legend']
109
if 'labelFontSize' not in legend:
110
legend['labelFontSize'] = legend_font_size
111
if 'titleFontSize' not in legend:
112
legend['titleFontSize'] = legend_font_size
113
114
# The header
115
if 'header' not in config:
116
config['header'] = dict()
117
header = config['header']
118
if 'labelFontSize' not in header:
119
header['labelFontSize'] = header_font_size
120
if 'titleFontSize' not in header:
121
header['titleFontSize'] = header_font_size
122
123
# Title
124
if 'title' not in config:
125
config['title'] = dict()
126
title = config['title']
127
if 'fontSize' not in title:
128
title['fontSize'] = title_font_size
129
130
# Marks
131
if 'mark' not in config:
132
config['mark'] = dict()
133
mark = config['mark']
134
if 'fontSize' not in mark:
135
mark['fontSize'] = mark_font_size
136
137
# Mark tooltips
138
if tooltip and 'tooltip' not in mark:
139
mark['tooltip'] = dict(content="encoding")
140
141
return existingTheme
142
143
return patch_theme
144
145
# We can only do this once per session
146
if theme_sentinel not in alt.themes.names():
147
for name in alt.themes.names():
148
alt.themes.register(name, make_theme(name))
149
150
# register a sentinel theme so we only do this once
151
alt.themes.register(theme_sentinel, make_theme('default'))
152
alt.themes.enable('default')
153
154
except Exception:
155
pass
156
157
# enable pandas latex repr when targeting pdfs
158
try:
159
import pandas as pd
160
if fig_format == 'pdf':
161
pd.set_option('display.latex.repr', True)
162
except Exception:
163
pass
164
165
# interactivity
166
if interactivity:
167
from IPython.core.interactiveshell import InteractiveShell
168
InteractiveShell.ast_node_interactivity = interactivity
169
170
# NOTE: the kernel_deps code is repeated in the cleanup.py file
171
# (we can't easily share this code b/c of the way it is run).
172
# If you edit this code also edit the same code in cleanup.py!
173
174
# output kernel dependencies
175
kernel_deps = dict()
176
for module in list(sys.modules.values()):
177
# Some modules play games with sys.modules (e.g. email/__init__.py
178
# in the standard library), and occasionally this can cause strange
179
# failures in getattr. Just ignore anything that's not an ordinary
180
# module.
181
if not isinstance(module, types.ModuleType):
182
continue
183
path = getattr(module, "__file__", None)
184
if not path:
185
continue
186
if path.endswith(".pyc") or path.endswith(".pyo"):
187
path = path[:-1]
188
if not os.path.exists(path):
189
continue
190
kernel_deps[path] = os.stat(path).st_mtime
191
print(json.dumps(kernel_deps))
192
193
# set run_path if requested
194
run_path = '{run_path}'
195
if run_path:
196
# hex-decode the path
197
run_path = base64.b64decode(run_path.encode("utf-8")).decode("utf-8")
198
os.chdir(run_path)
199
200
# reset state
201
%reset
202
203
# shiny
204
# Checking for shiny by using {is_shiny} directly because we're after the %reset. We don't want
205
# to set a variable that stays in global scope.
206
if {is_shiny}:
207
try:
208
import htmltools as _htmltools
209
import ast as _ast
210
211
_htmltools.html_dependency_render_mode = "json"
212
213
# This decorator will be added to all function definitions
214
def _display_if_has_repr_html(x):
215
try:
216
# IPython 7.14 preferred import
217
from IPython.display import display, HTML
218
except:
219
from IPython.core.display import display, HTML
220
221
if hasattr(x, '_repr_html_'):
222
display(HTML(x._repr_html_()))
223
return x
224
225
# ideally we would undo the call to ast_transformers.append
226
# at the end of this block whenver an error occurs, we do
227
# this for now as it will only be a problem if the user
228
# switches from shiny to not-shiny mode (and even then likely
229
# won't matter)
230
import builtins
231
builtins._display_if_has_repr_html = _display_if_has_repr_html
232
233
class _FunctionDefReprHtml(_ast.NodeTransformer):
234
def visit_FunctionDef(self, node):
235
node.decorator_list.insert(
236
0,
237
_ast.Name(id="_display_if_has_repr_html", ctx=_ast.Load())
238
)
239
return node
240
241
def visit_AsyncFunctionDef(self, node):
242
node.decorator_list.insert(
243
0,
244
_ast.Name(id="_display_if_has_repr_html", ctx=_ast.Load())
245
)
246
return node
247
248
ip = get_ipython()
249
ip.ast_transformers.append(_FunctionDefReprHtml())
250
251
except:
252
pass
253
254
def ojs_define(**kwargs):
255
import json
256
try:
257
# IPython 7.14 preferred import
258
from IPython.display import display, HTML
259
except:
260
from IPython.core.display import display, HTML
261
262
# do some minor magic for convenience when handling pandas
263
# dataframes
264
def convert(v):
265
try:
266
import pandas as pd
267
except ModuleNotFoundError: # don't do the magic when pandas is not available
268
return v
269
if type(v) == pd.Series:
270
v = pd.DataFrame(v)
271
if type(v) == pd.DataFrame:
272
j = json.loads(v.T.to_json(orient='split'))
273
return dict((k,v) for (k,v) in zip(j["index"], j["data"]))
274
else:
275
return v
276
277
v = dict(contents=list(dict(name=key, value=convert(value)) for (key, value) in kwargs.items()))
278
display(HTML('<script type="ojs-define">' + json.dumps(v) + '</script>'), metadata=dict(ojs_define = True))
279
globals()["ojs_define"] = ojs_define
280
globals()["__spec__"] = None
281