-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpyodide-quarto-html-demo.qmd
219 lines (168 loc) · 5.15 KB
/
pyodide-quarto-html-demo.qmd
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
---
title: "Pyodide with Quarto HTML Standalone Document Proof of Concept"
subtitle: "Experiments with an Interactive Quarto Document using Pyodide v0.23.4"
author: "JJB"
engine: knitr
format:
html:
toc: true
editor: source
---
# Demo
## Background
The purpose of this document is to explore the [pyodide](https://pyodide.org/en/stable/) WebAssembly interface to power interactive Quarto documents.
## Setup
```{=html}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.css">
<style>
.CodeMirror pre {
background-color: unset !important;
}
.btn-pyodide {
background-color: #EEEEEE;
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/mode/python/python.js"></script>
<script src="https://cdn.jsdelivr.net/pyodide/v0.23.4/full/pyodide.js"></script>
<script type="module">
globalThis.pyodide = await loadPyodide();
document.querySelectorAll(".btn-pyodide").forEach((btn) => {
btn.innerText = "Run code";
btn.disabled = false;
});
globalThis.global_pyodide_run_counter = 0;
</script>
```
```{r}
#| results: asis
#| echo: false
pyodide_counter = 0
pyodide_editor = function(code = I(encodeString(code, quote = '`')), width, height) {
pyodide_counter <<- pyodide_counter + 1
output = glue::glue('
<button class="btn btn-default btn-pyodide" disabled type="button" id="pyodide-run-button-{{ pyodide_counter }}">Loading pyodide...</button>
<div id="pyodide-editor-{{ pyodide_counter }}"></div>
<div id="pyodide-code-output-{{ pyodide_counter }}"><pre style="visibility: hidden"></pre></div>
<script type="module">
const runButton = document.getElementById("pyodide-run-button-{{ pyodide_counter }}");
const outputDiv = document.getElementById("pyodide-code-output-{{ pyodide_counter }}");
const editorDiv = document.getElementById("pyodide-editor-{{ pyodide_counter }}");
const editor = CodeMirror((elt) => {
elt.style.border = "1px solid #eee";
elt.style.height = "auto";
editorDiv.append(elt);
},{
value: {{code}},
lineNumbers: true,
mode: "python",
theme: "light default",
viewportMargin: Infinity,
});
function addToOutput(s) {
globalThis.global_pyodide_run_counter += 1;
return "[" + globalThis.global_pyodide_run_counter + "] " + s + "\\n";
}
runButton.onclick = async () => {
runButton.disabled = true;
let pyodide = await globalThis.pyodide;
let python_code = editor.getValue();
// Detect whether any Python package needs to be attached from
// the Python code prior to running it.
await pyodide.loadPackagesFromImports(python_code);
// Setup an output variable
let out;
// Try to execute the code, if it fails... Store the error
try {
let output = pyodide.runPython(python_code);
out = addToOutput(output);
} catch (err) {
out = addToOutput(err);
} finally {
outputDiv.innerHTML = "";
const pre = document.createElement("pre");
if (/\\S/.test(out)) {
const code = document.createElement("code");
code.innerText = out;
pre.appendChild(code);
} else {
pre.style.visibility = "hidden";
}
outputDiv.appendChild(pre);
runButton.disabled = false;
}
};
runButton.innerText = "Run code";
runButton.disabled = false;
</script>
', .open = "{{", .close = "}}")
}
```
```{r}
#| echo: false
knitr::knit_engines$set(pyodide = function(options) {
code = paste(options$code, collapse = "\n")
w = knitr::opts_current$get('fig.width') * 72
h = knitr::opts_current$get('fig.height') * 72
options$results = 'asis'
form = pyodide_editor(code = I(encodeString(code, quote = '`')), width = w, height = h)
form
}
)
```
## Sample Calculations
Let's start off with a quick calculation
```{pyodide}
1 + 1
```
## Strings
Viewing string data
```{pyodide}
greet = 'Hello'
greet
```
## Retrieving prior objects
Checking string length
```{pyodide}
len(greet)
```
Notice, we're able to track the run value of code.
## Define and Call Functions
Functions can be defined in one cell and called.
```{pyodide}
def square(x):
return x**2
square(8)
```
Similarly, they persist to other cells.
```{pyodide}
num_list = [1, 2, 3]
[square(num)for num in num_list]
```
## Load a package
We've enabled _dynamic_ package detection to handle importing packages into the environment. The _dynamic_ part comes from detecting whether a non-core Python package is used, installing, and, then, importing it.
:::{.callout-note}
Importing a package for the first time will require more time. Subsequent import statements will be resolve quicker.
:::
```{pyodide}
import pandas as pd
df = pd.DataFrame({
'Name': ['JJB', 'H', 'Alex', 'Steve'],
'Age': [18, 25, 33, 42]
})
df
```
```{pyodide}
import pandas as pd
df.Age
```
## Graphing
:::{.callout-important}
Graphing is not yet available.
:::
## Free-for-all
Feel free to explore adding your own Python code into this code cell. Note, you may also do the same with earlier cells.
```{pyodide}
```