feat(electron-shell): 补录壳子源码(排除运行环境与构建产物)

This commit is contained in:
2026-09-24 16:14:24 +08:00
parent 08a9b962b4
commit f3311339e5
56 changed files with 17858 additions and 0 deletions
@@ -0,0 +1,191 @@
# 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)
# - 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-<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] [-SkipLocal]
# Needs: access to python.org / pypi.org (or an internal mirror via $PipIndex)
# ============================================================================
[CmdletBinding()]
param(
[string]$EnvVersion = "1.0.0",
[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
Download-File $EmbedUrl $EmbedZip
if (Test-Path $PyDir) { Remove-Item -Recurse -Force $PyDir }
New-Item -ItemType Directory -Force -Path $PyDir | Out-Null
Write-Host "extracting embeddable python ..."
Expand-Archive -Path $EmbedZip -DestinationPath $PyDir -Force
$PyExe = Join-Path $PyDir "python.exe"
if (-not (Test-Path $PyExe)) { throw "missing python.exe in embeddable" }
# 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)" }
# 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"
}
# ---------- 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 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