# Build portable Python + environment package (python-env-.zip) # ============================================================================ # Purpose: give the packaged Electron client a self-contained Python runtime so # plugins and platform-login no longer depend on an external Python install. # - Portable interpreter: python.org embeddable (self-contained) [default] # - Dependencies: pinned to the versions validated in the project .venv # - Runtime subset: webhost/backend/{plugins,core,shared} (minimal for # plugin_runner protocol + platform login) # - Output: dist-env/python-env-.zip + .sha256; by default also # installs into electron-shell/python-env/ for local dev (client probes it). # Usage (ASCII-safe, works on Windows PowerShell 5.1 with GBK codepage): # powershell -NoProfile -ExecutionPolicy Bypass -File scripts\build-python-env.ps1 [-EnvVersion 1.0.0] [-FromVenv] [-SkipLocal] # -FromVenv : 直接把本地 .venv 全量打包(基础解释器 python.exe/DLL/标准库 + # .venv\Lib\site-packages 全部依赖 + webhost 运行时子集)。不联网、 # 复用已验证依赖版本,推荐日常构建;embeddable+pip 路径保留作备用。 # Needs (embeddable mode only): access to python.org / pypi.org (or an internal # mirror via $PipIndex). FromVenv mode only needs the local .venv. # ============================================================================ [CmdletBinding()] param( [string]$EnvVersion = "1.0.0", [switch]$FromVenv, # 从本地 .venv 全量打包(推荐,不联网) [switch]$SkipLocal, # do NOT install into electron-shell/python-env/ [switch]$Force # re-download embeddable / get-pip ) $ErrorActionPreference = "Stop" $Shell = Resolve-Path (Join-Path $PSScriptRoot "..") $Repo = Resolve-Path (Join-Path $Shell "..\..") $Build = Join-Path $Shell "build\python-env" $Dist = Join-Path $Shell "dist-env" $DownloadDir = Join-Path $Build "downloads" $PyDir = Join-Path $Build "py" # temp root: interpreter + deps + runtime subset $PythonVersion = "3.11.9" $EmbedUrl = "https://www.python.org/ftp/python/$PythonVersion/python-$PythonVersion-embed-amd64.zip" $EmbedZip = Join-Path $DownloadDir "python-$PythonVersion-embed-amd64.zip" $GetPip = Join-Path $DownloadDir "get-pip.py" $PipIndex = $null # e.g. "https://pypi.tuna.tsinghua.edu.cn/simple" # All dependencies (top-level + key transitive), pinned to .venv-validated versions $Pinned = @( "requests==2.34.2", "python-dotenv==1.2.2", "cryptography==50.0.1", "pandas==3.0.5", "numpy==2.3.5", "openpyxl==3.1.5", "python-dateutil==2.9.0.post0", "tzdata==2026.3", "et-xmlfile", "websocket-client==1.9.0", "DrissionPage==4.1.1.4", "DrissionGet==1.2.1", "DrissionRecord==2.0.1", "lxml==6.1.1", "psutil==7.2.2", "tldextract==5.3.2", "cssselect==1.5.0", "click==8.4.2", "ddddocr==1.6.1", "onnxruntime==1.28.0", "Pillow==12.3.0", "opencv-python-headless==5.0.0.93", "flatbuffers==25.12.19", "protobuf==7.35.1", "pywin32==312", "urllib3==2.7.0", "certifi==2026.7.22", "idna==3.18", "charset-normalizer==3.4.9", "six==1.17.0", "packaging==26.3" ) function Download-File([string]$Url, [string]$Dest) { if (-not $Force -and (Test-Path $Dest) -and (Get-Item $Dest).Length -gt 0) { Write-Host " cache hit: $Dest" return } Write-Host " downloading: $Url" curl.exe -sL --retry 3 -o $Dest $Url if (-not (Test-Path $Dest) -or (Get-Item $Dest).Length -eq 0) { throw "download failed: $Url" } } Write-Host "=== 37du portable python env build v$EnvVersion ===" -ForegroundColor Cyan # ---------- 1. portable interpreter ---------- New-Item -ItemType Directory -Force -Path $Build, $Dist, $DownloadDir | Out-Null if (Test-Path $PyDir) { Remove-Item -Recurse -Force $PyDir } New-Item -ItemType Directory -Force -Path $PyDir | Out-Null if ($FromVenv) { # ---------- 1a. 从本地 .venv 全量打包(不联网):基础解释器 + venv site-packages ---------- $Venv = Join-Path $Repo ".venv" $PyvenvCfg = Join-Path $Venv "pyvenv.cfg" $BasePy = "" if (Test-Path $PyvenvCfg) { $BasePy = (Get-Content $PyvenvCfg | Where-Object { $_ -match '^home\s*=' } | ForEach-Object { ($_ -split '=', 2)[1].Trim() } | Select-Object -First 1) } if (-not $BasePy -or -not (Test-Path (Join-Path $BasePy "python.exe")) -or -not (Test-Path (Join-Path $Venv "Lib\site-packages"))) { throw "venv 打包所需目录缺失:基础解释器($BasePy) 或 .venv\Lib\site-packages" } Write-Host "base interpreter: $BasePy" # 解释器 + 运行时 DLL + 标准库 + 扩展模块目录(DLLs/) foreach ($f in @("python.exe", "python311.dll", "python3.dll", "vcruntime140.dll", "vcruntime140_1.dll", "Lib", "DLLs")) { $s = Join-Path $BasePy $f if (Test-Path $s) { Copy-Item $s -Destination $PyDir -Recurse -Force } } # 精简标准库:剔除重/无关目录(base site-packages 随后由 .venv 全量覆盖) foreach ($drop in @("test", "tkinter", "idlelib", "ensurepip", "turtledemo", "site-packages")) { $p = Join-Path (Join-Path $PyDir "Lib") $drop if (Test-Path $p) { Remove-Item -Recurse -Force $p } } # .venv 的 site-packages 全量拷贝(已验证可用的插件/平台登录依赖,含 pip/setuptools) Write-Host "copying venv site-packages: $Venv\Lib\site-packages (全量)" Copy-Item (Join-Path $Venv "Lib\site-packages") -Destination (Join-Path $PyDir "Lib\site-packages") -Recurse -Force } else { # ---------- 1b. embeddable 便携解释器 + pip 依赖(需联网) ---------- Download-File $EmbedUrl $EmbedZip Write-Host "extracting embeddable python ..." Expand-Archive -Path $EmbedZip -DestinationPath $PyDir -Force # enable site-packages (pip / pywin32 .pth depend on 'import site') $Tag = ($PythonVersion.Split('.')[0..1] -join '') $Pth = Join-Path $PyDir "python$Tag._pth" Write-Host "enabling site + site-packages: $Pth" Set-Content -Path $Pth -Encoding ascii -Value @( "python$Tag.zip" "." "Lib\site-packages" "" "# Enable site (pip / pywin32 .pth)" "import site" ) # ---------- 2. pip + dependencies ---------- Download-File "https://bootstrap.pypa.io/get-pip.py" $GetPip Write-Host "bootstrapping pip ..." & $PyExe $GetPip --no-warn-script-location --disable-pip-version-check | Out-Host if ($LASTEXITCODE -ne 0) { throw "get-pip failed (exit $LASTEXITCODE)" } Write-Host "installing pinned deps ($($Pinned.Count)) with --only-binary ..." $PipArgs = @("-m", "pip", "install", "--no-warn-script-location", "--disable-pip-version-check", "--only-binary=:all:") if ($PipIndex) { $PipArgs += "--index-url", $PipIndex } $PipArgs += $Pinned & $PyExe $PipArgs | Out-Host if ($LASTEXITCODE -ne 0) { throw "pip install failed (exit $LASTEXITCODE)" } } $PyExe = Join-Path $PyDir "python.exe" if (-not (Test-Path $PyExe)) { throw "missing python.exe in build dir" } # copy pywin32 DLLs next to the interpreter (no postinstall / PATH dependency) $PyWin32Sys = Join-Path $PyDir "Lib\site-packages\pywin32_system32" if (Test-Path $PyWin32Sys) { Copy-Item -Path (Join-Path $PyWin32Sys "*.dll") -Destination $PyDir -Force Write-Host "pywin32 DLLs copied to interpreter root" } # copy VC++ runtime DLLs next to the interpreter: onnxruntime/opencv .pyd # depends on msvcp140.dll / msvcp140_1.dll etc. On machines without VC++ # 2015-2022 Redistributable the plugin fails with "DLL load failed while # importing onnxruntime_pybind11_state" (1.1.1 只拷了 3 个,漏了 msvcp140_1.dll, # 无 VC 运行库的客户机必现). VC++ redist DLLs are redistributable (MS license). foreach ($dll in (Get-ChildItem -Path $env:SystemRoot\System32 -Filter "*.dll" | Where-Object { $_.Name -match '^(msvcp140|vcruntime140)' })) { Copy-Item $dll.FullName -Destination $PyDir -Force Write-Host " VC runtime: $($dll.Name)" } $VcCount = (Get-ChildItem -Path $PyDir -Filter "*.dll" | Where-Object { $_.Name -match '^(msvcp140|vcruntime140)' }).Count if ($VcCount -lt 3) { throw "VC++ runtime DLLs incomplete ($VcCount): install VC++ 2015-2022 Redistributable x64 on this build machine first" } # ---------- 3. webhost runtime subset ---------- $Wb = Join-Path $Repo "desktop\webhost\backend" $EnvWb = Join-Path $PyDir "webhost\backend" New-Item -ItemType Directory -Force -Path (Join-Path $EnvWb "plugins"), (Join-Path $EnvWb "core"), (Join-Path $EnvWb "shared") | Out-Null # top-level __init__ files: minimal (do NOT import the full core, avoids fastapi etc.) Set-Content -Path (Join-Path $PyDir "webhost\__init__.py") -Encoding utf8 -Value @( "# -*- coding: utf-8 -*-" '"""37du env-package runtime (self-contained)."""' ) Set-Content -Path (Join-Path $EnvWb "__init__.py") -Encoding utf8 -Value @( "# -*- coding: utf-8 -*-" '"""37du env-package runtime subset (webhost.backend).' 'Carries only the minimal modules needed for plugin execution and platform login:' 'plugin_runner + plugins + shared + core.auth (+ winjob/job_guard).' 'Deliberately does NOT import the full core (scheduler/http/etc. live in Node)."""' ) # core: plugin_runner + auth + winjob + job_guard (no scheduler/http modules) $CoreFiles = @("__init__.py", "plugin_runner.py", "auth.py", "winjob.py", "job_guard.py") foreach ($f in $CoreFiles) { $src = Join-Path (Join-Path $Wb "core") $f if (-not (Test-Path $src)) { throw "missing webhost core file: $f" } Copy-Item -Path $src -Destination (Join-Path $EnvWb "core") -Force } # plugins: loader + base foreach ($f in @("__init__.py", "base.py")) { $src = Join-Path (Join-Path $Wb "plugins") $f if (-not (Test-Path $src)) { throw "missing webhost plugins file: $f" } Copy-Item -Path $src -Destination (Join-Path $EnvWb "plugins") -Force } # shared: all platform login / export modules Get-ChildItem -Path (Join-Path $Wb "shared") -Filter "*.py" | ForEach-Object { Copy-Item -Path $_.FullName -Destination (Join-Path $EnvWb "shared") -Force } # ---------- 4. smoke test ---------- Write-Host "=== smoke test ===" -ForegroundColor Cyan & $PyExe -c "import sys; print(' python:', sys.version.split()[0])" | Out-Host & $PyExe -c "import requests,pandas,numpy,openpyxl,websocket,dotenv,cryptography; print(' core deps ok')" | Out-Host if ($LASTEXITCODE -ne 0) { throw "core deps import failed" } & $PyExe -c "import DrissionPage; print(' DrissionPage', DrissionPage.__version__)" | Out-Host & $PyExe -c "import ddddocr; print(' ddddocr ok')" | Out-Host & $PyExe -c "import onnxruntime; print(' onnxruntime', onnxruntime.__version__)" | Out-Host & $PyExe -c "import win32com.client; print(' win32com ok')" | Out-Host Push-Location $PyDir try { & $PyExe -c "from webhost.backend.plugins import load_plugins; print(' webhost plugins ok')" | Out-Host if ($LASTEXITCODE -ne 0) { throw "webhost plugins import failed" } & $PyExe -c "from webhost.backend.core import auth, job_guard; print(' webhost core ok')" | Out-Host if ($LASTEXITCODE -ne 0) { throw "webhost core import failed" } } finally { Pop-Location } # ---------- 5. package ---------- $Zip = Join-Path $Dist "python-env-$EnvVersion.zip" if (Test-Path $Zip) { Remove-Item -Force $Zip } Write-Host "packaging: $Zip" Add-Type -AssemblyName System.IO.Compression.FileSystem Push-Location $PyDir try { [System.IO.Compression.ZipFile]::CreateFromDirectory($PyDir, $Zip, [System.IO.Compression.CompressionLevel]::Optimal, $false) } finally { Pop-Location } $Sha = (Get-FileHash -Algorithm SHA256 $Zip).Hash.ToLower() Set-Content -Path "$Zip.sha256" -Value $Sha -Encoding ascii Set-Content -Path (Join-Path $Dist "python-env-latest.txt") -Value $EnvVersion -Encoding ascii Write-Host " sha256: $Sha" Write-Host " artifact: $Zip ($([math]::Round((Get-Item $Zip).Length / 1MB, 1)) MB)" # ---------- 6. local install (for dev integration testing) ---------- if (-not $SkipLocal) { $LocalEnv = Join-Path $Shell "python-env" $LocalVer = Join-Path $LocalEnv $EnvVersion if (Test-Path $LocalVer) { Remove-Item -Recurse -Force $LocalVer } New-Item -ItemType Directory -Force -Path $LocalEnv, $LocalVer | Out-Null Copy-Item -Path (Join-Path $PyDir "*") -Destination $LocalVer -Recurse -Force $Stamp = Get-Date -Format o $Json = "{`n `"version`": `"$EnvVersion`",`n `"updated_at`": `"$Stamp`"`n}" # BOM-less UTF-8(PS 5.1 的 Set-Content -Encoding utf8 会写 BOM,JSON.parse 会挂) [System.IO.File]::WriteAllText((Join-Path $LocalEnv "current.json"), $Json, (New-Object System.Text.UTF8Encoding($false))) Write-Host "local install done: $LocalVer (current.json -> $EnvVersion)" -ForegroundColor Green } Write-Host "=== build complete v$EnvVersion ===" -ForegroundColor Green