-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpy.ts
More file actions
201 lines (190 loc) · 5.47 KB
/
py.ts
File metadata and controls
201 lines (190 loc) · 5.47 KB
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
import worker from 'web-worker:./webworker.js';
import { pyLog, pyExecState, pyInstallLog, isPyExecuting, isPyReadyState, isPyReady } from "./store";
/** The main composable */
const usePython = () => {
const _pyodideWorker = new worker();
//const _pyodideWorker = new Worker(new URL('./webworker.js', import.meta.url), { type: 'classic' })
let _callback: (value: {
results: any;
error: any;
} | PromiseLike<{
results: any;
error: any;
}>) => void = (v) => null;
function _dispatchEvent(id: string, data: Record<string, any>) {
switch (data.type) {
case "end":
_callback({ results: data.res, error: null })
_callback = (v) => null
pyExecState.set(0);
break;
case "err":
_callback({ results: null, error: data.msg })
_callback = (v) => null
pyExecState.set(0);
pyLog.setKey("exception", data.msg)
break;
case "installlog":
pyInstallLog.setKey("stage", data.msg.stage);
pyInstallLog.setKey("msg", data.msg.msg);
break;
case "stderr":
//console.log("STDERR:", data.msg)
pyLog.get().stdErr.push(data.msg);
//pyLog.notify();
break;
case "stdout":
//console.log("STDOUT:", data.msg)
pyLog.get().stdOut.push(data.msg);
//pyLog.notify();
//pyLog.setKey("stdOut", [...pyLog.get().stdOut, data.msg])
break;
default:
pyExecState.set(0);
throw new Error(`Unknown event type ${data.type}`)
}
}
_pyodideWorker.onmessage = (event) => {
const { id, ...data } = event.data;
//console.log("=> msg in:", id, ":", data);
_dispatchEvent(id ?? "", data)
};
function _processTransformCode(code: string): string {
if (code.startsWith('\n')) {
code.replace('\n', '')
}
const li = code.split("\n");
const buf = new Array<string>();
li.forEach((el) => {
buf.push(' ' + el)
});
return buf.join("\n")
}
/** Load the Python runtime
* @param pyoPackages the list of Pyodide packages to install
* @param packages the list of Pip packages to install
* @param initCode the code to run before runtime initialization
* @param transformCode the code to run after every script
*/
async function load(
pyoPackages: Array<string> = [], packages: Array<string> = [], initCode = "", transformCode = ""
): Promise<{ results: any, error: any }> {
let res: { results: any; error: any };
try {
res = await run("", undefined, "_pyinstaller", {
pyoPackages: pyoPackages,
packages: packages,
initCode: initCode,
transformCode: _processTransformCode(transformCode)
});
} catch (e) {
throw new Error(
// @ts-ignore
`Error in pyodideWorker at ${e.filename}, Line: ${e.lineno}, ${e.message}`
);
}
isPyReadyState.set(1);
return res
}
async function _run(
script: string,
isAsync: boolean,
namespace?: string,
id?: string,
context: Record<string, any> = {}
): Promise<{ results: any, error: any }> {
if (pyExecState.get() === 1) {
throw new Error("Only one python script can run at the time")
}
pyExecState.set(1);
// reset logger
const _id = id ?? (+ new Date()).toString();
pyLog.set({
id: _id,
stdOut: [],
stdErr: [],
exception: "",
});
// exec
return new Promise((onSuccess) => {
_callback = onSuccess;
_pyodideWorker.postMessage({
id: _id,
namespace: namespace,
python: script,
isAsync: isAsync,
...context,
});
});
}
/** Run a Python script
* @param script the Python code to run
* @param namespace the namemespace where the code will run
* @param id the script id
* @param context some context data to pass to the runtime
*/
async function run(
script: string,
namespace?: string,
id?: string,
context: Record<string, any> = {}
): Promise<{ results: any, error: any }> {
return await _run(script, false, namespace, id, context)
}
/** Run an async Python script
* @param script the Python code to run
* @param namespace the namemespace where the code will run
* @param id the script id
* @param context some context data to pass to the runtime
*/
async function runAsync(
script: string,
namespace?: string,
id?: string,
context: Record<string, any> = {}
): Promise<{ results: any, error: any }> {
return await _run(script, true, namespace, id, context)
}
/** Clear the python memory and logs for a namespace
* @param namespace the namespace to cleanup
*/
async function clear(namespace: string): Promise<{ results: any, error: any }> {
return new Promise((onSuccess) => {
const _cb: (value: {
results: any;
error: any;
} | PromiseLike<{
results: any;
error: any;
}>) => void = (v) => {
pyLog.set({
id: "_flushns",
stdOut: [],
stdErr: [],
exception: "",
});
onSuccess(v)
};
_callback = _cb;
_pyodideWorker.postMessage({
id: "_flushns",
namespace: namespace,
});
});
}
return {
load,
run,
runAsync,
clear,
/** The install log store */
installLog: pyInstallLog,
/** The runtime log store */
log: pyLog,
/** The execution state atom */
isExecuting: isPyExecuting,
/** The ready state atom */
isReady: isPyReady,
}
}
export { usePython }