Skip to content

Instantly share code, notes, and snippets.

@derrickturk
Created May 25, 2023 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save derrickturk/6ac2ea5f9b2204c2cfa49153cd355eb2 to your computer and use it in GitHub Desktop.
Save derrickturk/6ac2ea5f9b2204c2cfa49153cd355eb2 to your computer and use it in GitHub Desktop.
Pyodide + NumPy in the browser demo
"use strict";
const input = [1.0, 2.0, 3.0, 4.0, 5.0];
const code = document.getElementById('code');
const output = document.getElementById('output');
let timeoutId;
async function init() {
let pyodide = await loadPyodide();
await pyodide.loadPackage('numpy');
return pyodide;
}
let pyodideP = init();
function showResult(result) {
output.className = 'good';
output.innerText = 'output = ' + result.toString();
}
function showError(error) {
output.className = 'bad';
output.innerText = 'Error: ' + error.toString();
}
async function evaluate() {
let pyodide = await pyodideP;
pyodide.globals.set('input', input);
try {
pyodide.runPython(code.value);
let result = pyodide.globals.get('output').toJs();
showResult(result);
} catch (e) {
showError(e);
}
}
function onCodeChange() {
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
timeoutId = undefined;
}
timeoutId = setTimeout(() => {
evaluate();
}, 750);
}
evaluate();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pyodide Evaluation Demo</title>
<script src="https://cdn.jsdelivr.net/pyodide/v0.23.2/full/pyodide.js">
</script>
<style>
#output {
font-family: monospace;
}
#output.good {
color: green;
}
#output.bad {
color: red;
}
</style>
</head>
<body>
<h1>Pyodide Evaluation Demo</h1>
<p>The data is <code>input = [1.0, 2.0, 3.0, 4.0, 5.0]</code>.
<p><label for="code">Write your Python processing code below,
storing the result in <code>output</code>.</label>
<p><textarea id="code" name="code" rows="20" cols="80"
oninput="onCodeChange()">import numpy as np
output = np.array(list(input)) + 1.0</textarea>
<p><div id="output"></div>
<script src="evaluator.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment