-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
usePython.ts
262 lines (235 loc) · 6.22 KB
/
usePython.ts
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
import {
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState
} from 'react'
import { PythonContext, suppressedMessages } from '../providers/PythonProvider'
import { proxy, Remote, wrap } from 'comlink'
import useFilesystem from './useFilesystem'
import { Packages } from '../types/Packages'
import { PythonRunner } from '../types/Runner'
interface UsePythonProps {
packages?: Packages
}
export default function usePython(props?: UsePythonProps) {
const { packages = {} } = props ?? {}
const [runnerId, setRunnerId] = useState<string>()
const [isLoading, setIsLoading] = useState(false)
const [isRunning, setIsRunning] = useState(false)
const [output, setOutput] = useState<string[]>([])
const [stdout, setStdout] = useState('')
const [stderr, setStderr] = useState('')
const [pendingCode, setPendingCode] = useState<string | undefined>()
const [hasRun, setHasRun] = useState(false)
const {
packages: globalPackages,
timeout,
lazy,
terminateOnCompletion,
autoImportPackages,
sendInput,
workerAwaitingInputIds,
getPrompt
} = useContext(PythonContext)
const workerRef = useRef<Worker>()
const runnerRef = useRef<Remote<PythonRunner>>()
const {
readFile,
writeFile,
mkdir,
rmdir,
watchModules,
unwatchModules,
watchedModules
} = useFilesystem({ runner: runnerRef?.current })
const createWorker = () => {
const worker = new Worker(
new URL('../workers/python-worker', import.meta.url)
)
workerRef.current = worker
}
useEffect(() => {
if (!lazy) {
// Spawn worker on mount
createWorker()
}
// Cleanup worker on unmount
return () => {
cleanup()
}
}, [])
const allPackages = useMemo(() => {
const official = [
...new Set([
...(globalPackages.official ?? []),
...(packages.official ?? [])
])
]
const micropip = [
...new Set([
...(globalPackages.micropip ?? []),
...(packages.micropip ?? [])
])
]
return [official, micropip]
}, [globalPackages, packages])
const isReady = !isLoading && !!runnerId
useEffect(() => {
if (workerRef.current && !isReady) {
const init = async () => {
try {
setIsLoading(true)
const runner: Remote<PythonRunner> = wrap(workerRef.current as Worker)
runnerRef.current = runner
await runner.init(
proxy((msg: string) => {
// Suppress messages that are not useful for the user
if (suppressedMessages.includes(msg)) {
return
}
setOutput((prev) => [...prev, msg])
}),
proxy(({ id, version }) => {
setRunnerId(id)
console.debug('Loaded pyodide version:', version)
}),
'standard',
allPackages
)
} catch (error) {
console.error('Error loading Pyodide:', error)
} finally {
setIsLoading(false)
}
}
init()
}
}, [workerRef.current])
// Immediately set stdout upon receiving new input
useEffect(() => {
if (output.length > 0) {
setStdout(output.join('\n'))
}
}, [output])
// React to ready state and run delayed code if pending
useEffect(() => {
if (pendingCode && isReady) {
const delayedRun = async () => {
await runPython(pendingCode)
setPendingCode(undefined)
}
delayedRun()
}
}, [pendingCode, isReady])
// React to run completion and run cleanup if worker should terminate on completion
useEffect(() => {
if (terminateOnCompletion && hasRun && !isRunning) {
cleanup()
setIsRunning(false)
setRunnerId(undefined)
}
}, [terminateOnCompletion, hasRun, isRunning])
// prettier-ignore
const moduleReloadCode = (modules: Set<string>) => `
import importlib
import sys
${Array.from(modules).map((name) => `
if """${name}""" in sys.modules:
importlib.reload(sys.modules["""${name}"""])
`).join('')}
del importlib
del sys
`
const runPython = useCallback(
async (code: string) => {
// Clear stdout and stderr
setStdout('')
setStderr('')
if (lazy && !isReady) {
// Spawn worker and set pending code
createWorker()
setPendingCode(code)
return
}
if (!isReady) {
throw new Error('Pyodide is not loaded yet')
}
let timeoutTimer
try {
setIsRunning(true)
setHasRun(true)
// Clear output
setOutput([])
if (!isReady || !runnerRef.current) {
throw new Error('Pyodide is not loaded yet')
}
if (timeout > 0) {
timeoutTimer = setTimeout(() => {
setStdout('')
setStderr(`Execution timed out. Reached limit of ${timeout} ms.`)
interruptExecution()
}, timeout)
}
if (watchedModules.size > 0) {
await runnerRef.current.run(
moduleReloadCode(watchedModules),
autoImportPackages
)
}
await runnerRef.current.run(code, autoImportPackages)
// eslint-disable-next-line
} catch (error: any) {
setStderr('Traceback (most recent call last):\n' + error.message)
} finally {
setIsRunning(false)
clearTimeout(timeoutTimer)
}
},
[lazy, isReady, timeout, watchedModules]
)
const interruptExecution = () => {
cleanup()
setIsRunning(false)
setRunnerId(undefined)
setOutput([])
// Spawn new worker
createWorker()
}
const cleanup = () => {
if (!workerRef.current) {
return
}
console.debug('Terminating worker')
workerRef.current.terminate()
}
const isAwaitingInput =
!!runnerId && workerAwaitingInputIds.includes(runnerId)
const sendUserInput = (value: string) => {
if (!runnerId) {
console.error('No runner id')
return
}
sendInput(runnerId, value)
}
return {
runPython,
stdout,
stderr,
isLoading,
isReady,
isRunning,
interruptExecution,
readFile,
writeFile,
mkdir,
rmdir,
watchModules,
unwatchModules,
isAwaitingInput,
sendInput: sendUserInput,
prompt: runnerId ? getPrompt(runnerId) : ''
}
}