Files
37duAutomation/desktop/electron-shell/scripts/build-python-env.ps1
T
puddy aae706bd8a chore: 环境包依赖收敛到 requirements.txt,清理旧插件目录与 _pack.py
- build-python-env.ps1:白名单只留包名,版本统一从仓库根 requirements.txt 解析;-FromVenv 打包前加版本守卫校验 .venv 一致性,支持 -ShowDeps 只打印解析结果

- 桌面端发版SOP 同步新流程与历史坑(1.1.9 环境包、禁止用 -FromVenv 打补丁包)

- requirements.txt 补 pycryptodome 3.24.0;package-lock 版本对齐 1.10.8

- 删除已废弃的插件级 _pack.py(统一走 tools/agent_cli.py 打包)与旧英文目录 plugins/xq0077(已由 XQ0077 携程数据导出 取代)
2026-11-09 18:46:35 +08:00

315 lines
17 KiB
PowerShell
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Build portable Python + environment package (python-env-<version>.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: electron-shell/python/webhost/backend/{plugins,core,shared}
# (minimal for plugin_runner protocol + platform login; vendored, no webhost dep)
# - Output: dist-env/python-env-<version>.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
[switch]$ShowDeps # 只解析并打印依赖清单后退出(校验 requirements.txt 用,不打包)
)
$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"
# ================== 依赖清单:版本唯一真源 = 仓库根 requirements.txt ==================
# 历史坑:这里曾硬编码一份 pin 列表(第三份清单),与 requirements.txt 长期漂移
# (numpy/pandas/onnxruntime 等都落后多个小版本),而 .venv 装的是 requirements 的版本,
# 导致「-FromVenv 打包」与「embeddable+pip 打包」产物不一致。
# 现在只维护「环境包需要哪些包」的白名单,版本一律从 requirements.txt 解析。
$ReqFile = Join-Path $Repo "requirements.txt"
if (-not (Test-Path $ReqFile)) { throw "缺少依赖清单:$ReqFile" }
$ReqVersion = @{}
foreach ($line in Get-Content -Path $ReqFile) {
if ($line -match '^\s*([A-Za-z0-9][A-Za-z0-9_.\-]*)\s*==\s*([^\s;#]+)') {
$ReqVersion[$matches[1].ToLower().Replace('_', '-').Replace('.', '-')] = $matches[2]
}
}
# 环境包白名单(只写包名,版本取自 requirements.txt)
$EnvPackages = @(
"requests", "python-dotenv", "cryptography", "pycryptodome",
"pandas", "numpy", "openpyxl",
"python-dateutil", "tzdata", "et-xmlfile",
"websocket-client",
"DrissionPage", "DrissionGet", "DrissionRecord",
"lxml", "psutil", "tldextract", "cssselect", "click",
"ddddocr", "onnxruntime", "Pillow",
"opencv-python-headless", "flatbuffers", "protobuf",
# OCR(XQ0003 请假附件:病假/结婚证/产检关键词与登记日期核验)
# rapidocr>=3 必须显式固定,连同 opencv_python/omegaconf 等运行依赖,否则
# 走 embeddable+pip 模式时该栈不会装、插件 OCR 全面降级为人工复核。
"rapidocr", "opencv-python",
"omegaconf", "antlr4-python3-runtime", "colorlog",
"pyclipper", "Shapely", "PyYAML", "tqdm",
"pywin32",
"urllib3", "certifi", "idna",
"charset-normalizer", "six", "packaging"
)
$Pinned = @()
foreach ($p in $EnvPackages) {
$k = $p.ToLower().Replace('_', '-').Replace('.', '-')
if (-not $ReqVersion.ContainsKey($k)) { throw "requirements.txt 缺少环境包依赖:$p" }
$Pinned += "$p==$($ReqVersion[$k])"
}
Write-Host "依赖来源:requirements.txt(白名单 $($Pinned.Count) 个包)" -ForegroundColor DarkGray
# 版本守卫:本地 .venv 必须与 requirements.txt 一致(唯一真源),否则打出来的包会跟随
# 一个「没被记录」的版本。返回对象(用对象而非数组:PowerShell 里返回空数组会被展开成 $null):
# Found = $false 表示 .venv 不存在;否则 Drift 为漂移项数组。
function Get-VenvDrift([string]$VenvPath) {
$VenvPy = Join-Path $VenvPath "Scripts\python.exe"
if (-not (Test-Path $VenvPy)) { return [pscustomobject]@{ Found = $false; Drift = @() } }
$Frozen = @{}
& $VenvPy -m pip freeze 2>$null | ForEach-Object {
if ($_ -match '^([A-Za-z0-9][A-Za-z0-9_.\-]*)\s*==\s*([^\s]+)') {
$Frozen[$matches[1].ToLower().Replace('_', '-').Replace('.', '-')] = $matches[2]
}
}
$drift = @()
foreach ($p in $EnvPackages) {
$k = $p.ToLower().Replace('_', '-').Replace('.', '-')
$want = $ReqVersion[$k]
$have = $Frozen[$k]
if ($have -ne $want) { $drift += "$p .venv=$have / requirements.txt=$want" }
}
return [pscustomobject]@{ Found = $true; Drift = $drift }
}
if ($ShowDeps) {
$Pinned | ForEach-Object { Write-Host " $_" }
$guard = Get-VenvDrift (Join-Path $Repo ".venv")
if (-not $guard.Found) {
Write-Host " (.venv 不存在,跳过版本一致性校验)" -ForegroundColor DarkGray
} elseif ($guard.Drift.Count -eq 0) {
Write-Host " 版本守卫通过:.venv 与 requirements.txt 一致($($EnvPackages.Count) 个包)" -ForegroundColor Green
} else {
Write-Host " [!] 本地 .venv 与 requirements.txt 不一致:" -ForegroundColor Yellow
$guard.Drift | ForEach-Object { Write-Host " $_" -ForegroundColor Yellow }
}
Write-Host "(-ShowDeps:仅解析依赖,不执行打包)" -ForegroundColor Cyan
return
}
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"
}
# 版本守卫:本地 .venv 必须与 requirements.txt 一致(唯一真源),否则打出来的包会跟随
# 一个「没被记录」的版本。不一致时先 pip install -r requirements.txt 对齐再打包。
$guard = Get-VenvDrift $Venv
if (-not $guard.Found) {
Write-Host " 未发现 .venv,跳过版本一致性校验" -ForegroundColor DarkGray
} elseif ($guard.Drift.Count -gt 0) {
throw ("本地 .venv 与 requirements.txt 版本不一致,请先 pip install -r requirements.txt 对齐:`n " + ($guard.Drift -join "`n "))
} else {
Write-Host " 版本守卫通过:.venv 与 requirements.txt 一致($($EnvPackages.Count) 个包)"
}
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(单一真源 = electron-shell/python/webhost) ----------
$Wb = Join-Path $Shell "python\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 from source(minimal,不 import 完整 core)
Copy-Item (Join-Path $Wb "__init__.py") (Join-Path $EnvWb "__init__.py") -Force
Copy-Item (Join-Path (Join-Path $Shell "python\webhost") "__init__.py") (Join-Path $PyDir "webhost\__init__.py") -Force
# core: plugin_runner + auth + winjob + job_guard + sdk_mount (no scheduler/http modules)
$CoreFiles = @("__init__.py", "plugin_runner.py", "auth.py", "winjob.py", "job_guard.py", "sdk_mount.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,Crypto,cv2; 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 "from rapidocr import RapidOCR; import rapidocr; print(' rapidocr ok')" | Out-Host
if ($LASTEXITCODE -ne 0) { throw "rapidocr import failed (XQ0003 附件 OCR 依赖缺失)" }
& $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