| 8 | * Initialize Pyodide with required packages |
| 9 | */ |
| 10 | export async function initializePyodide(): Promise<PyodideInterface> { |
| 11 | if (pyodideInstance) { |
| 12 | return pyodideInstance; |
| 13 | } |
| 14 | |
| 15 | if (initPromise) { |
| 16 | return initPromise; |
| 17 | } |
| 18 | |
| 19 | initPromise = (async () => { |
| 20 | console.log("[Python] Initializing Pyodide..."); |
| 21 | |
| 22 | let pyodide; |
| 23 | try { |
| 24 | pyodide = await loadPyodide({ |
| 25 | indexURL: "https://cdn.jsdelivr.net/pyodide/v0.28.0/full/", |
| 26 | stdout: (text: string) => { |
| 27 | console.log("[Python stdout]", text); |
| 28 | }, |
| 29 | stderr: (text: string) => { |
| 30 | console.error("[Python stderr]", text); |
| 31 | }, |
| 32 | }); |
| 33 | console.log("[Python] Pyodide core loaded successfully"); |
| 34 | } catch (error) { |
| 35 | console.error("[Python] Failed to load Pyodide core:", error); |
| 36 | throw new Error(`Failed to load Pyodide: ${error instanceof Error ? error.message : String(error)}`); |
| 37 | } |
| 38 | |
| 39 | // Install essential packages one by one with yield points |
| 40 | console.log("[Python] Installing core packages..."); |
| 41 | const corePackages = ["numpy", "pandas", "matplotlib", "micropip"]; |
| 42 | |
| 43 | for (const pkg of corePackages) { |
| 44 | try { |
| 45 | console.log(`[Python] Loading ${pkg}...`); |
| 46 | await pyodide.loadPackage([pkg]); |
| 47 | // Yield to browser to prevent freezing |
| 48 | await new Promise(resolve => setTimeout(resolve, 0)); |
| 49 | } catch (error) { |
| 50 | console.error(`[Python] Failed to load ${pkg}:`, error); |
| 51 | throw new Error(`Failed to load ${pkg}: ${error instanceof Error ? error.message : String(error)}`); |
| 52 | } |
| 53 | } |
| 54 | console.log("[Python] Core packages loaded successfully"); |
| 55 | |
| 56 | try { |
| 57 | console.log("[Python] Installing additional data science packages..."); |
| 58 | |
| 59 | await pyodide.runPythonAsync(` |
| 60 | import micropip |
| 61 | |
| 62 | async def install_data_science_packages(): |
| 63 | """Install packages that are commonly available in Pyodide and useful for data analysis""" |
| 64 | try: |
| 65 | # Essential data science and visualization packages |
| 66 | packages_to_install = [ |
| 67 | 'plotly', # Interactive visualizations |