forked from eyra/feldspar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
py_worker.js
executable file
·106 lines (93 loc) · 2.59 KB
/
py_worker.js
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
let pyScript
onmessage = (event) => {
const { eventType } = event.data
switch (eventType) {
case 'initialise':
initialise().then(() => {
self.postMessage({ eventType: 'initialiseDone' })
})
break
case 'firstRunCycle':
pyScript = self.pyodide.runPython(`port.start(${event.data.sessionId})`)
runCycle(null)
break
case 'nextRunCycle':
const { response } = event.data
unwrap(response).then((userInput) => {
runCycle(userInput)
})
break
default:
console.log('[ProcessingWorker] Received unsupported event: ', eventType)
}
}
function runCycle(payload) {
console.log('[ProcessingWorker] runCycle ' + JSON.stringify(payload))
scriptEvent = pyScript.send(payload)
self.postMessage({
eventType: 'runCycleDone',
scriptEvent: scriptEvent.toJs({
create_proxies: false,
dict_converter: Object.fromEntries
})
})
}
function unwrap(response) {
console.log('[ProcessingWorker] unwrap response: ' + JSON.stringify(response.payload))
return new Promise((resolve) => {
switch (response.payload.__type__) {
case 'PayloadFile':
copyFileToPyFS(response.payload.value, resolve)
break
default:
resolve(response.payload)
}
})
}
function copyFileToPyFS(file, resolve) {
directoryName = `/file-input`
pathStats = self.pyodide.FS.analyzePath(directoryName)
if (!pathStats.exists) {
self.pyodide.FS.mkdir(directoryName)
} else {
self.pyodide.FS.unmount(directoryName)
}
self.pyodide.FS.mount(
self.pyodide.FS.filesystems.WORKERFS,
{
files: [file]
},
directoryName
)
resolve({ __type__: 'PayloadString', value: directoryName + '/' + file.name })
}
function initialise() {
console.log('[ProcessingWorker] initialise')
return startPyodide()
.then((pyodide) => {
self.pyodide = pyodide
return loadPackages()
})
.then(() => {
return installPortPackage()
})
}
function startPyodide() {
importScripts('https://cdn.jsdelivr.net/pyodide/v0.24.0/full/pyodide.js')
console.log('[ProcessingWorker] loading Pyodide')
return loadPyodide({
indexURL: 'https://cdn.jsdelivr.net/pyodide/v0.24.0/full/'
})
}
function loadPackages() {
console.log('[ProcessingWorker] loading packages')
return self.pyodide.loadPackage(['micropip', 'numpy', 'pandas'])
}
function installPortPackage() {
console.log('[ProcessingWorker] load port package')
return self.pyodide.runPythonAsync(`
import micropip
await micropip.install("../../port-0.0.0-py3-none-any.whl", deps=False)
import port
`);
}