Spaces:
Running
Running
| const PYODIDE_URL = "https://cdn.jsdelivr.net/pyodide/v0.26.1/full/pyodide.mjs"; | |
| // @ts-ignore | |
| import managerCode from "../../../backend/src/optimization_manager.py?raw"; | |
| import logicCode from "../../../backend/src/optimization_logic.py?raw"; | |
| import type { WorkerMessage } from "./types"; | |
| let pyodide: any = null; | |
| let manager: any = null; | |
| async function init() { | |
| const { loadPyodide } = await import(/* @vite-ignore */ PYODIDE_URL); | |
| pyodide = await loadPyodide({ | |
| indexURL: "https://cdn.jsdelivr.net/pyodide/v0.26.1/full/" | |
| }); | |
| await pyodide.loadPackage(["numpy", "sympy"]); | |
| pyodide.FS.writeFile("optimization_logic.py", logicCode); | |
| pyodide.FS.writeFile("optimization_manager.py", managerCode); | |
| pyodide.runPython(`from optimization_manager import OptimizationManager; manager = OptimizationManager();`); | |
| manager = pyodide.globals.get("manager"); | |
| if (!manager) { | |
| console.error("Failed to initialize optimization manager"); | |
| } | |
| self.postMessage({ type: "READY" }); | |
| } | |
| function handlePythonResult(result: any) { | |
| if (!result) { | |
| return null; | |
| } | |
| try { | |
| const data = result.toJs({ dict_converter: Object.fromEntries }); | |
| if (result.destroy) { | |
| result.destroy(); | |
| } | |
| self.postMessage({ type: "RESULT", data: data }); | |
| } catch (error) { | |
| console.error("Error handling Python result:", error); | |
| } | |
| } | |
| self.onmessage = async (event) => { | |
| const message = event.data as WorkerMessage; | |
| if (!manager) { | |
| console.warn("Pyodide is not ready yet"); | |
| return; | |
| } | |
| switch (message.type) { | |
| case "INIT": | |
| const pythonSettings = pyodide.toPy(message.settings); | |
| handlePythonResult(manager.handle_update_settings(pythonSettings)); | |
| break; | |
| case "NEXT_STEP": | |
| handlePythonResult(manager.handle_next_step()); | |
| break; | |
| case "PREV_STEP": | |
| handlePythonResult(manager.handle_prev_step()); | |
| break; | |
| case "RESET": | |
| handlePythonResult(manager.handle_reset()); | |
| break; | |
| default: | |
| console.error("Unknown message type:", message); | |
| break; | |
| } | |
| } | |
| // Start of execution | |
| init(); | |