修复:补齐 Linux 标注 Python 环境并在升级时保留运行时

This commit is contained in:
tfarcraw 2026-11-08 22:52:09 +08:00
parent eb37b56e96
commit 20537967e4
12 changed files with 182 additions and 11 deletions

View File

@ -58,7 +58,7 @@ dotnet run --project tests/Avalonia.Smoke -c Release
2026-11-08:Windows 本地上述自动检查通过,Windows/Linux 发布构建通过。
后续已验证 Linux 原生 GPU 渲染、合成动态预览和海康实机预览;结果和推理后端边界见 [LINUX.md](LINUX.md)。
Linux 标注及训练仍待现场验收。
Linux 标注后端已验证视频导入、SAM2 传播和导出;完整训练仍待现场验收。
Linux 海康使用 MVS 4.9 Linux 自带的 netstandard2.0 封装,并通过原生库名映射接入 `libMvCameraControl.so`。
2026-11-08 已在 LH-GC10-HS500 上验证 2448×2048 BayerRG8 转 BGR、归还缓冲和断开后重开。
Windows 继续使用原 Windows SDK;两平台应用和采集服务代码相同,仅供应商 SDK 绑定不同。

View File

@ -17,14 +17,46 @@ PYTHON=python3.12 bash tools/Setup-Python.sh /absolute/application/directory --s
相机接口、模型和 YAML 配方逻辑与 Windows 来自同一套源码。UVC 使用 V4L2;
海康需要匹配的 Linux MVS,并根据 SDK 安装位置设置 `MVS_LIB_DIR`、`LD_LIBRARY_PATH`。
Linux 海康已验证 2448×2048 BayerRG8 采集和 BGR 转换;标注训练仍待真机验收。
Linux 海康已验证 2448×2048 BayerRG8 采集和 BGR 转换;标注后端已验证导入、SAM2 传播和导出,完整训练仍待现场验收。
## 后续部署
`tools/Deploy-Linux.ps1` 已切换为统一 Avalonia 工程;仅在明确要求部署时执行。
它在新版本目录执行 `--check-runtime` 和 `--check-gpu`,通过后更新启动入口,保留 `configs`、`models`、`workspace`。
它在新版本目录执行 `--check-runtime` 和 `--check-gpu`,通过后更新启动入口,保留 `configs`、`models`、`workspace`、`python` 和 `.cache`。
图形环境需要 X11/XWayland、fontconfig 和中文字体;发布包自带 .NET 运行时。
## 标注 Python 环境(2026-11-08)
目标机原来只有系统 Python 3.14,程序专用环境没有安装,因而标注任务提示缺少 Python。
现已在 `~/sophelper/python` 安装独立 Python 3.12.16 环境,补齐 PyTorch、OpenCV、YOLO、
ONNX 和 SAM2。基础解释器位于 `~/sophelper/python-base`,系统 Python 保留。
SAM2.1 tiny 权重放在共享 `models` 目录并通过固定 SHA256 校验,首次传播不必再次下载。
每个发布目录的 `python` 和 `.cache` 都链接到安装根目录的共享环境和缓存,升级不会重新下载
或丢失环境;安装脚本解析真实路径,venv 入口不会绑定到旧发布目录。
已安装依赖版本记录在 `~/sophelper/python/requirements-installed.txt`。
当前机器重新安装/补齐依赖时可执行:
```bash
PYTHON="$HOME/sophelper/python-base/cpython-3.12-linux-x86_64-gnu/bin/python3.12" \
SOPHELPER_PYTHON_ROOT="$HOME/sophelper/python" \
bash "$HOME/sophelper/current/tools/Setup-Python.sh" "$HOME/sophelper/current" --sam2
./SopHelper.Avalonia --check-training
```
Windows/Linux 环境缺失提示现分别指向各自的安装脚本。`--check-training` 使用程序实际选择的
Python 启动真实 worker,检查标注依赖;不启动界面或相机。
已在 Linux 验证六帧视频导入、中文及空格路径、SAM2 自动传播、人工种子保留和复核后数据集导出;
`pip check` 通过。部署脚本连续切换两个测试版本时,共享 Python 和模型缓存均保持不变。
SAM2/PyTorch 标注环境当前使用 CPU,与实时 SOP 检测的 AMD WebGPU 后端分别配置。
```bash
python/bin/python3 tests/Training.WorkerSmoke/check.py tools/worker.py --sam2
bash tests/Linux.RuntimePersistence/check.sh
```
## GPU 渲染和帧率验证(2026-11-08)
Linux 默认按 EGL → GLX → 软件渲染的顺序初始化。可用 `SOPHELPER_RENDERER=egl` 或

View File

@ -63,5 +63,6 @@ dotnet run --project tests/Mvs.Smoke -c Release -- --hardware
```
运行 `--check-runtime` 可检查发布包的模型和 SOP 引擎。
运行 `--check-training` 可检查程序实际识别的 Python 路径及标注/训练依赖。
Avalonia 验证使用假相机,覆盖导航、原始配方字段保持、标注保存、相机缓冲显示和画框坐标。
详细架构与平台验证记录见 [AVALONIA.md](AVALONIA.md),研发方向见 [研发计划.md](研发计划.md)。

View File

@ -0,0 +1,27 @@
using System.Text;
using System.Text.Json;
using SopHelper.Engine.Training;
using SopHelper.Presentation;
namespace SopHelper.Diagnostics;
internal static class TrainingRuntimeCheck
{
public static int Run()
{
try
{
// WinExe may have redirected streams without an attached Windows console.
Console.SetOut(new StreamWriter(Console.OpenStandardOutput(), new UTF8Encoding(false)) { AutoFlush = true });
Console.SetError(new StreamWriter(Console.OpenStandardError(), new UTF8Encoding(false)) { AutoFlush = true });
var python = DesktopPlatform.PythonPath;
if (!File.Exists(python)) throw new FileNotFoundException(DesktopPlatform.MissingPythonMessage, python);
using var worker = new WorkerClient();
worker.RunAsync(python, Path.Combine(AppContext.BaseDirectory, "tools", "worker.py"),
new { action = "doctor" }, Console.WriteLine, CancellationToken.None).GetAwaiter().GetResult();
Console.WriteLine(JsonSerializer.Serialize(new { passed = true, python }));
return 0;
}
catch (Exception error) { Console.Error.WriteLine(error.Message); return 1; }
}
}

View File

@ -21,6 +21,9 @@ internal static class DesktopPlatform
return bundled;
}
}
public static string MissingPythonMessage => OperatingSystem.IsWindows()
? "缺少内置 Python 环境,请运行 tools/Setup-Python.ps1 -Sam2 后重新构建程序。"
: "缺少标注用 Python 环境,请使用 Python 3.12 运行 tools/Setup-Python.sh 程序目录 --sam2,或联系维护人员安装。";
public static void Reveal(string path)
{
var directory=File.Exists(path)?Path.GetDirectoryName(path)!:path;

View File

@ -6,6 +6,7 @@ internal static class Program
[STAThread]
public static int Main(string[] args)
{
if(args.Contains("--check-training"))return Diagnostics.TrainingRuntimeCheck.Run();
if(args.Contains("--check-gpu"))return Diagnostics.RuntimeCheck.Run(requireGpu:true);
if(args.Contains("--check-runtime"))return Diagnostics.RuntimeCheck.Run();
return Presentation.DesktopRendering.Configure(AppBuilder.Configure<App>().UsePlatformDetect())

View File

@ -278,7 +278,7 @@ public sealed class MainViewModel : BindableBase
{
SaveSettings();
if (!File.Exists(PythonPath))
throw new FileNotFoundException("缺少内置 Python 环境,请运行 tools/Setup-Python.ps1 -Sam2 后重新构建程序。", PythonPath);
throw new FileNotFoundException(DesktopPlatform.MissingPythonMessage, PythonPath);
await _worker.RunAsync(PythonPath, Path.Combine(Root, "tools", "worker.py"), request, line =>
{
try

View File

@ -0,0 +1,24 @@
#!/usr/bin/env bash
set -euo pipefail
installer=${1:-"$(cd "$(dirname "$0")/../.." && pwd)/tools/linux/install-desktop.sh"}
stage=$(mktemp -d)
trap 'rm -rf -- "$stage"' EXIT
root="$stage/application"
mkdir -p "$stage/home" "$root/releases/v1" "$root/releases/v2/python" "$root/python/bin" "$root/.cache"
for release in v1 v2; do
printf '#!/bin/sh\nexit 0\n' > "$root/releases/$release/SopHelper.Avalonia"
chmod +x "$root/releases/$release/SopHelper.Avalonia"
done
printf 'preserved-python\n' > "$root/python/bin/python3"
printf 'preserved-cache\n' > "$root/.cache/model-marker"
printf 'packaged-python\n' > "$root/releases/v2/python/packaged-marker"
HOME="$stage/home" bash "$installer" "$root/releases/v1" "$root" >/dev/null
HOME="$stage/home" bash "$installer" "$root/releases/v2" "$root" >/dev/null
for release in v1 v2; do
test "$(readlink -f "$root/releases/$release/python")" = "$root/python"
test "$(readlink -f "$root/releases/$release/.cache")" = "$root/.cache"
done
test "$(cat "$root/python/bin/python3")" = preserved-python
test "$(cat "$root/.cache/model-marker")" = preserved-cache
test "$(readlink -f "$root/current")" = "$root/releases/v2"
printf 'PASS: Python and model cache survive two releases; existing runtime preserved\n'

View File

@ -0,0 +1,79 @@
"""Exercise the real annotation worker, with optional SAM2 propagation, in a temporary project."""
import argparse
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import cv2
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument("worker", type=Path)
parser.add_argument("--sam2", action="store_true")
options = parser.parse_args()
worker = options.worker.resolve()
with tempfile.TemporaryDirectory(prefix="sophelper-worker-") as directory:
root = Path(directory)
def run(request):
request_file = root / "request.json"
request_file.write_text(json.dumps(request, ensure_ascii=False), encoding="utf-8")
process = subprocess.run([sys.executable, "-u", str(worker), str(request_file)],
capture_output=True, text=True, encoding="utf-8", timeout=240,
env=dict(os.environ, PYTHONUTF8="1"))
if process.returncode:
raise RuntimeError(process.stdout + process.stderr)
events = []
for line in process.stdout.splitlines():
try:
events.append(json.loads(line))
except json.JSONDecodeError:
pass
return events
events = run({"action": "doctor"})
modules = next(event["modules"] for event in events if "modules" in event)
required = ["cv2", "numpy", "torch", "ultralytics", "onnx"] + (["sam2"] if options.sam2 else [])
assert all(modules[name] for name in required), modules
print("PASS: annotation worker dependency check", flush=True)
video = root / "input.avi"
writer = cv2.VideoWriter(str(video), cv2.VideoWriter_fourcc(*"MJPG"), 10, (320, 240))
assert writer.isOpened(), "MJPEG encoder unavailable"
for index in range(6):
image = np.full((240, 320, 3), 25, dtype=np.uint8)
cv2.rectangle(image, (40 + index * 3, 60), (120 + index * 3, 140), (30, 200, 40), -1)
writer.write(image)
writer.release()
project = root / "标注 测试项目"
run({"action": "extract", "video": str(video), "output": str(project), "name": "测试零件", "maxFrames": 6})
project_file = project / "project.json"
data = json.loads(project_file.read_text(encoding="utf-8"))
assert len(data["frames"]) == 6 and data["width"] == 320 and data["height"] == 240
assert all((project / frame["image"]).is_file() for frame in data["frames"])
print("PASS: actual video import, frame extraction, Unicode and space paths", flush=True)
data["frames"][0].update(box=[40, 60, 120, 140], status="reviewed", prompt=True)
project_file.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
if options.sam2:
run({"action": "propagate", "project": str(project_file), "device": "cpu"})
data = json.loads(project_file.read_text(encoding="utf-8"))
assert data["frames"][0]["status"] == "reviewed" and data["frames"][0]["prompt"]
assert all(frame["status"] == "auto" for frame in data["frames"][1:])
assert any(frame["box"] for frame in data["frames"][1:]), "SAM2 produced no tracked boxes"
print("PASS: SAM2 model load and propagation preserve the reviewed seed", flush=True)
for index, frame in enumerate(data["frames"]):
frame.update(box=[40 + index * 3, 60, 120 + index * 3, 140], status="reviewed")
project_file.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
events = run({"action": "export", "project": str(project_file), "every": 1})
output = Path(next(event["output"] for event in events if "output" in event))
assert (output / "data.yaml").is_file()
assert len(list((output / "labels" / "train").glob("*.txt"))) >= 2
assert list((output / "labels" / "val").glob("*.txt"))
print("PASS: reviewed annotations export into training and validation data", flush=True)

View File

@ -3,13 +3,16 @@ set -euo pipefail
root=${1:?Usage: Setup-Python.sh APPLICATION_DIRECTORY [--sam2]}
root=$(cd "$root" && pwd)
bootstrap=${PYTHON:-python3}
"$bootstrap" -m venv "$root/python"
python="$root/python/bin/python3"
"$bootstrap" -c 'import sys; assert sys.version_info >= (3, 10), "Python 3.10 or later is required; Python 3.12 is recommended"'
# Resolve deployment symlinks so venv entry points do not depend on an old release directory.
runtime=$(realpath -m "${SOPHELPER_PYTHON_ROOT:-$root/python}")
"$bootstrap" -m venv "$runtime"
python="$runtime/bin/python3"
"$python" -m pip install --upgrade pip
"$python" -m pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu
"$python" -m pip install 'torch>=2.5.1' torchvision --index-url https://download.pytorch.org/whl/cpu
"$python" -m pip install -r "$root/tools/requirements.txt"
if [ "${2:-}" = --sam2 ]; then
"$python" -m pip install wheel huggingface_hub
"$python" -m pip install setuptools wheel huggingface_hub
SAM2_BUILD_CUDA=0 "$python" -m pip install --no-build-isolation 'git+https://github.com/facebookresearch/sam2.git@2b90b9f5ceec907a1c18123530e92e794ad901a4'
fi
printf 'Python runtime ready: %s\n' "$python"

View File

@ -6,8 +6,8 @@ mkdir -p "$root"
root=$(cd "$root" && pwd)
case "$release" in "$root"/releases/*) ;; *) echo 'Release must be under INSTALL_ROOT/releases' >&2; exit 1;; esac
test -x "$release/SopHelper.Avalonia"
# Keep operator settings, edited recipes, recordings and models across upgrades.
for item in configs models workspace; do
# Keep operator data, the Python environment and model caches across upgrades.
for item in configs models workspace python .cache; do
if [ ! -e "$root/$item" ]; then
if [ -d "$release/$item" ] && [ ! -L "$release/$item" ]; then
mv -- "$release/$item" "$root/$item"

View File

@ -79,7 +79,8 @@ def doctor(request):
import torch
emit(f"PyTorch {torch.__version__} · CUDA {'可用' if torch.cuda.is_available() else '不可用,将使用 CPU'}")
if not all(modules[m] for m in ("cv2", "numpy", "torch", "ultralytics")):
raise RuntimeError("运行 tools/Setup-Python.ps1 安装基础依赖;SAM2 需加 -Sam2")
setup = "tools/Setup-Python.ps1 -Sam2" if sys.platform == "win32" else "PYTHON=python3.12 bash tools/Setup-Python.sh 程序目录 --sam2"
raise RuntimeError(f"标注运行环境依赖不完整,请运行 {setup} 安装")
if not modules["sam2"]:
emit("尚未安装 SAM2;手动标注、导出、训练仍可用,自动传播需安装 SAM2")