diff --git a/AVALONIA.md b/AVALONIA.md
index da20ca3..58c20a8 100644
--- a/AVALONIA.md
+++ b/AVALONIA.md
@@ -9,14 +9,13 @@
|---|---|
| 主窗口 Logo、左侧导航 | 原布局迁移到 `VVMs/MainWindow` |
| SOP 参数、相机、配方、步骤、违规、日志 | `VVMs/SopPage`,保留原命令和 ViewModel 逻辑 |
-| 表单式配方编辑器 | `VVMs/RecipeEditor`,包含步骤、区域、全局设置、零件列表、检测模型、SOP流程视频、零件标注与训练七个标签页 |
+| 表单式配方编辑器 | `VVMs/RecipeEditor`,包含步骤、SOP流程视频和 Agent助手三个标签页 |
| ROI 图像画框、坐标微调、相机取图 | Avalonia `RegionCanvas`,仍保存原图像素坐标 |
-| 零件标注、复核、SAM2、导出、YOLO 训练 | `Training` 嵌入配方编辑窗口,固定当前配方;每个编辑窗口独立持有模型和 worker,关闭时取消任务 |
-| 相机预览、录像、退出清理 | `Training/CameraWindow`,保留相机互斥与关闭等待流程 |
-| SOP、检测器、左右手稳定器、录像器、训练数据与 worker 客户端 | `SopHelper.CrossPlatform.Engine` 独立保存全部共享引擎源码,不引用归档仓库 |
+| 相机预览、录像、退出清理 | 配方编辑器的 SOP流程视频页,保留相机互斥与关闭等待流程 |
+| SOP、手部检测、左右手稳定器与录像器 | `SopHelper.CrossPlatform.Engine` 独立保存全部共享引擎源码,不引用归档仓库 |
界面框架相关 API(绘图、图像缓冲、文件选择、UI 调度、窗口关闭)统一由 Avalonia 实现。
-ViewModel 不按操作系统分叉。UVC 的 MSMF/DSHOW 与 V4L2、Python 可执行文件路径和原生 SDK 库名,
+ViewModel 不按操作系统分叉。UVC 的 MSMF/DSHOW 与 V4L2,
由同一套适配代码根据平台选择;两边仅发布不同的原生运行库。
## 本地构建和发布
@@ -35,19 +34,9 @@ pwsh -File tools/Publish-Avalonia.ps1
两个发布目录都带有内容相同的 `source-manifest.json`,记录 UI、ViewModel、共享引擎源码及工程文件的 SHA256。
平台相关的中间文件/PDB 路径会影响 PE 文件字节,不能用整个 DLL 的文件哈希判断源代码是否相同。
-Windows 默认携带仓库 `python/` 运行时;缺少时先执行原来的 `tools/Setup-Python.ps1 -Sam2`。
-`-SkipPython` 仅供不携带训练依赖的开发构建。
-Linux 在发布目录建立独立运行时:
-
-```bash
-# PYTHON 可选择已安装且受 PyTorch 支持的 Python 版本。
-PYTHON=python3.12 bash tools/Setup-Python.sh /absolute/path/to/application --sam2
-./SopHelper.Avalonia
-```
-
## 检查与边界
-Windows 模型推理使用 ONNX Runtime CUDA 后端。运行页会分别显示手部和目标模型的实际后端;
+Windows 模型推理使用 ONNX Runtime CUDA 后端。运行日志会显示手部模型的实际后端;
正常应为 `GPU (CUDA)`,显示 CPU 时检查运行库。安装到仓库后重新构建并重启:
```powershell
@@ -68,14 +57,9 @@ CUDA 12 与 CUDA 13 的 cuDNN 9 DLL 名称相同,不能仅凭文件名混用
dotnet run --project tests/Avalonia.Smoke -c Release
```
-测试覆盖实际共享壳与 Prism 导航、SOP 启停和原生推理、相机缓冲显示、配方对话框及七个标签页、
-打开编辑器不改配方字段、标注保存与切页保留、Python 环境检查、BGR 颜色和缓冲所有权、
+测试覆盖实际共享壳与 Prism 导航、SOP 启停和原生推理、相机缓冲显示、配方对话框及三个标签页、
+打开编辑器不改配方字段、BGR 颜色和缓冲所有权、
实际鼠标正反向画框与留白坐标映射。渲染图与报告在 `artifacts/avalonia-smoke/`。
测试使用假相机,避免枚举或占用现场硬件。也可对发布包执行 `--check-runtime` 验证模型与 SOP 引擎。
-2026-11-08:Windows 本地上述自动检查通过,Windows/Linux 发布构建通过。
-后续已验证 Linux 原生 GPU 渲染、合成动态预览和海康实机预览;结果和推理后端边界见 [LINUX.md](LINUX.md)。
-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 绑定不同。
+Windows 和 Linux 的部署记录见 [WINDOWS.md](WINDOWS.md) 和 [LINUX.md](LINUX.md)。
diff --git a/LINUX.md b/LINUX.md
index 233eef3..e01493c 100644
--- a/LINUX.md
+++ b/LINUX.md
@@ -176,7 +176,7 @@ MD002 后续切换至 `/home/wl/sophelper/releases/avalonia-20261118-a2414fd`,
已将源码提交 `8d356af` 发布到 `wl@192.168.0.167`(主机名 `md002`),
版本目录为 `/home/wl/sophelper/releases/avalonia-20261118-8d356af`。
`current` 和桌面启动器已切换到新版,图形会话中存在 SopHelper 窗口,程序保持运行。
-这是当前移除 YOLO / 标注训练功能后的版本;下文 11 月 8 日的训练部署记录仅供历史参考。
+该版本已移除 YOLO 推理和标注训练功能。
启动入口 `/home/wl/sophelper/run.sh` 设置:
@@ -214,15 +214,7 @@ D3 服务日志在 `/home/wl/sophelper/logs/d3-service/`,桌面输出在
dotnet publish src/SopHelper.Avalonia -c Release -r linux-x64 -p:NativePlatform=Linux --self-contained true -o artifacts/avalonia/linux-x64
```
-在目标机的图形会话中执行 `./SopHelper.Avalonia`。训练功能需要为 Linux 单独安装 Python 运行时:
-
-```bash
-PYTHON=python3.12 bash tools/Setup-Python.sh /absolute/application/directory --sam2
-```
-
-相机接口、模型和 YAML 配方逻辑与 Windows 来自同一套源码。UVC 使用 V4L2;
-海康需要匹配的 Linux MVS,并根据 SDK 安装位置设置 `MVS_LIB_DIR`、`LD_LIBRARY_PATH`。
-Linux 海康已验证 2448×2048 BayerRG8 采集和 BGR 转换;标注后端已验证导入、SAM2 传播和导出,完整训练仍待现场验收。
+在目标机的图形会话中执行 `./SopHelper.Avalonia`。桌面版通过 V4L2 采集 USB 相机,djev 服务使用独立运行环境。
## 后续部署
@@ -230,43 +222,6 @@ Linux 海康已验证 2448×2048 BayerRG8 采集和 BGR 转换;标注后端已
它在新版本目录执行 `--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 后端分别配置。
-
-已部署至 `~/sophelper/releases/avalonia-20261108-225209`。新版 `--check-training` 确认识别
-Python 3.12.16,cv2、numpy、torch、ultralytics、sam2 和 onnx 均可用;
-`--check-runtime` 和 `--check-gpu` 也通过,实时检测仍报告 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` 或
diff --git a/WINDOWS.md b/WINDOWS.md
index 330bab0..a12369a 100644
--- a/WINDOWS.md
+++ b/WINDOWS.md
@@ -53,7 +53,7 @@ Ryzen 5 5600XT、32GB 内存、NVIDIA GeForce RTX 5060(驱动 32.0.16.1088)
- 数据目录:`C:\sophelper\configs\sop` 带入 `d3-workflow.yaml`、`demo.yaml`、`hand-ai.yaml` 三个模板配方;
`C:\sophelper\models` 有 palm、landmark 两个手部模型(另有旧包遗留的 `yolo11n.onnx`,当前代码不加载)。
- 未随包部署:djev 服务(该机没有 `E:\D3Lite`,程序启动时不会自动拉起,需在“运行设置 → djev”配置远端 `SOPHELPER_VISION_ENDPOINT`,
- 或在工位机安装 djev 后由程序自动启动)、SAM2/训练用 Python 环境(`BundlePythonRuntime=false`,`current\python` 不存在)。
+ 或在工位机安装 djev 后由程序自动启动)、SAM2/训练用 Python 环境。
- 相机:现场按 USB(UVC)接入,首次运行在“运行设置”里选择设备并确认实测 fps;本次未接相机,未做采集验证。
## W-184 d3-nano 部署(2026-11-20)
diff --git a/src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs b/src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs
index 2143b69..6b6a082 100644
--- a/src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs
+++ b/src/SopHelper.Avalonia/Presentation/DesktopPlatform.cs
@@ -1,4 +1,4 @@
-// 桌面平台适配:集中解析工作区、配方和 Python 路径,并封装系统文件选择及目录展示。
+// 桌面平台适配:集中解析工作区、配方路径,并封装系统文件选择及目录展示。
using System.Diagnostics;
using Avalonia.Controls;
@@ -39,17 +39,6 @@ internal static class DesktopPlatform
}
}
public static Window Owner => ((IClassicDesktopStyleApplicationLifetime)Avalonia.Application.Current!.ApplicationLifetime!).MainWindow!;
- public static string PythonPath
- {
- get
- {
- var relative=OperatingSystem.IsWindows()?Path.Combine("python","python.exe"):Path.Combine("python","bin","python3");
- return Path.Combine(AppContext.BaseDirectory,relative);
- }
- }
- 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;
diff --git a/src/SopHelper.Avalonia/SopHelper.Avalonia.csproj b/src/SopHelper.Avalonia/SopHelper.Avalonia.csproj
index bebd076..2c1c7e4 100644
--- a/src/SopHelper.Avalonia/SopHelper.Avalonia.csproj
+++ b/src/SopHelper.Avalonia/SopHelper.Avalonia.csproj
@@ -14,7 +14,6 @@
Windows
Linux
BWS.ico
- false
@@ -29,6 +28,5 @@
-
diff --git a/src/SopHelper.Avalonia/Training/AnnotationCanvas.cs b/src/SopHelper.Avalonia/Training/AnnotationCanvas.cs
deleted file mode 100644
index 2a92c24..0000000
--- a/src/SopHelper.Avalonia/Training/AnnotationCanvas.cs
+++ /dev/null
@@ -1,135 +0,0 @@
-// 视频标注画布:处理图像缩放、拖动及矩形框编辑,将屏幕交互映射为图像坐标。
-
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Input;
-using Avalonia.Media;
-using System.Globalization;
-using SopHelper.Presentation.Imaging;
-using SopHelper.Engine.Training;
-
-namespace SopHelper.Training;
-public sealed class AnnotationCanvas : Control
-{
- public static readonly StyledProperty SourceProperty=AvaloniaProperty.Register(nameof(Source));
- public static readonly StyledProperty BoxProperty=AvaloniaProperty.Register(nameof(Box));
- public static readonly StyledProperty TargetNameProperty=AvaloniaProperty.Register(nameof(TargetName), "");
- public static readonly StyledProperty?> AnnotationsProperty=AvaloniaProperty.Register?>(nameof(Annotations));
- public IReadOnlyList? Annotations {get=>GetValue(AnnotationsProperty);set=>SetValue(AnnotationsProperty,value);}
- public BitmapSource? Source {get=>GetValue(SourceProperty);set=>SetValue(SourceProperty,value);}
- public double[]? Box {get=>GetValue(BoxProperty);set=>SetValue(BoxProperty,value);}
- public string TargetName {get=>GetValue(TargetNameProperty);set=>SetValue(TargetNameProperty,value);}
- public event Action? BoxDrawn;
- private Point? _start;private Point _end;private IPointer? _pointer;
- private double _zoom=1;
- private Vector _offset;
- private Point? _panStart;
- static AnnotationCanvas(){AffectsRender(SourceProperty,BoxProperty,TargetNameProperty,AnnotationsProperty);}
- public AnnotationCanvas(){ClipToBounds=true;Cursor=new Cursor(StandardCursorType.Cross);Focusable=true;}
- private Rect ImageRect
- {
- get
- {
- if(Source is null)return default;
- var fit=VVMs.RecipeEditor.RegionCanvas.FitImage(Bounds.Size,new Size(Source.PixelWidth,Source.PixelHeight));
- return new Rect(fit.X+_offset.X,fit.Y+_offset.Y,fit.Width*_zoom,fit.Height*_zoom);
- }
- }
- public void ResetView()
- {_zoom=1;_offset=default;EndGesture();InvalidateVisual();}
- protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
- {
- base.OnPropertyChanged(change);
- if(change.Property==SourceProperty)
- {
- EndGesture();
- var previous=change.GetOldValue();
- if(Source is null||previous is null||Source.PixelWidth!=previous.PixelWidth||Source.PixelHeight!=previous.PixelHeight)ResetView();
- }
- }
- protected override void OnPointerWheelChanged(PointerWheelEventArgs e)
- {
- if(!IsEnabled||Source is null||ImageRect.Width<=0)return;
- e.Handled=true;
- if(_pointer is not null||e.Delta.Y==0)return;
- var zoom=Math.Clamp(_zoom*Math.Pow(1.2,e.Delta.Y),0.1,20);
- var position=e.GetPosition(this);var image=ImageRect;var ratio=zoom/_zoom;
- _offset+=new Vector((position.X-image.X)*(1-ratio),(position.Y-image.Y)*(1-ratio));
- _zoom=zoom;InvalidateVisual();
- }
- public override void Render(DrawingContext dc)
- {
- dc.DrawRectangle(Brushes.Transparent,null,new Rect(Bounds.Size));var image=ImageRect;if(Source is null||image.Width<=0)return;
- dc.DrawImage(Source,image);var pen=new Pen(new SolidColorBrush(Color.FromRgb(0,220,220)),2);
- foreach(var item in Annotations??[])
- {
- if(item.Label==TargetName||item.Box is not {Length:4} other)continue;
- var scale=image.Width/Source.PixelWidth;
- var rect=new Rect(image.X+other[0]*scale,image.Y+other[1]*scale,(other[2]-other[0])*scale,(other[3]-other[1])*scale);
- dc.DrawRectangle(null,new Pen(Brushes.Orange,2),rect);DrawTargetName(dc,rect,Brushes.Orange,item.Label);
- }
- if(Box is { Length:4 } b)
- {
- var scale=image.Width/Source.PixelWidth;
- var rect=new Rect(image.X+b[0]*scale,image.Y+b[1]*scale,(b[2]-b[0])*scale,(b[3]-b[1])*scale);
- dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(30,0,220,220)),pen,rect);
- if(_start is null)DrawTargetName(dc,rect,pen.Brush!);
- }
- if(_start is {} start)
- {
- var rect=DragRect(start,_end);
- dc.DrawRectangle(null,new Pen(Brushes.Yellow,2),rect);
- DrawTargetName(dc,rect,Brushes.Yellow);
- }
- }
- private void DrawTargetName(DrawingContext dc,Rect box,IBrush foreground,string? label=null)
- {
- label??=TargetName;
- if(string.IsNullOrWhiteSpace(label)||Bounds.Width<=8||Bounds.Height<=8||
- box.Right<0||box.Left>Bounds.Width||box.Bottom<0||box.Top>Bounds.Height)return;
- const double padding=4;
- var text=new FormattedText(label,CultureInfo.CurrentCulture,FlowDirection.LeftToRight,
- new Typeface("Microsoft YaHei, Noto Sans CJK SC"),14,foreground)
- {MaxTextWidth=Math.Max(1,Bounds.Width-2*padding),MaxLineCount=1,Trimming=TextTrimming.CharacterEllipsis};
- var size=new Size(text.Width+2*padding,text.Height+2*padding);
- var left=Math.Clamp(box.Left,0,Math.Max(0,Bounds.Width-size.Width));
- // Keep the label visible when the box touches the top edge or is panned partly off-screen.
- var top=box.Top-size.Height-3;
- if(top<0)top=box.Top+3;
- top=Math.Clamp(top,0,Math.Max(0,Bounds.Height-size.Height));
- dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(225,12,18,24)),null,new Rect(new Point(left,top),size));
- dc.DrawText(text,new Point(left+padding,top+padding));
- }
- protected override void OnPointerPressed(PointerPressedEventArgs e)
- {
- if(!IsEnabled||Source is null||_pointer is not null)return;
- if(e.GetCurrentPoint(this).Properties.PointerUpdateKind==PointerUpdateKind.RightButtonPressed)
- {
- Focus();_panStart=e.GetPosition(this);_pointer=e.Pointer;_pointer.Capture(this);
- Cursor=new Cursor(StandardCursorType.SizeAll);e.Handled=true;return;
- }
- if(e.GetCurrentPoint(this).Properties.PointerUpdateKind!=PointerUpdateKind.LeftButtonPressed||!ImageRect.Contains(e.GetPosition(this)))return;
- Focus();_start=_end=e.GetPosition(this);_pointer=e.Pointer;_pointer.Capture(this);InvalidateVisual();e.Handled=true;
- }
- protected override void OnPointerMoved(PointerEventArgs e)
- {
- if(_panStart is {} pan)
- {var position=e.GetPosition(this);_offset+=position-pan;_panStart=position;InvalidateVisual();e.Handled=true;return;}
- if(_start is null)return;var p=e.GetPosition(this);var image=ImageRect;_end=new Point(Math.Clamp(p.X,image.Left,image.Right),Math.Clamp(p.Y,image.Top,image.Bottom));InvalidateVisual();
- }
- protected override void OnPointerReleased(PointerReleasedEventArgs e)
- {
- if(_panStart is not null)
- {if(e.InitialPressMouseButton==MouseButton.Right){EndGesture();e.Handled=true;}return;}
- if(e.InitialPressMouseButton!=MouseButton.Left||_start is not {} start||Source is null)return;
- var p=e.GetPosition(this);var image=ImageRect;
- var rectangle=DragRect(start,new Point(Math.Clamp(p.X,image.Left,image.Right),Math.Clamp(p.Y,image.Top,image.Bottom)));
- EndGesture();e.Handled=true;
- if(rectangle.Width<3||rectangle.Height<3||image.Width<=0)return;
- var scale=Source.PixelWidth/image.Width;BoxDrawn?.Invoke([(rectangle.Left-image.Left)*scale,(rectangle.Top-image.Top)*scale,Math.Min(Source.PixelWidth,(rectangle.Right-image.Left)*scale),Math.Min(Source.PixelHeight,(rectangle.Bottom-image.Top)*scale)]);
- }
- private void EndGesture()
- {var pointer=_pointer;_start=null;_panStart=null;_pointer=null;pointer?.Capture(null);Cursor=new Cursor(StandardCursorType.Cross);InvalidateVisual();}
- protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e){EndGesture();base.OnPointerCaptureLost(e);}
- private static Rect DragRect(Point a,Point b)=>new(Math.Min(a.X,b.X),Math.Min(a.Y,b.Y),Math.Abs(a.X-b.X),Math.Abs(a.Y-b.Y));
-}
diff --git a/src/SopHelper.Avalonia/Training/MainViewModel.cs b/src/SopHelper.Avalonia/Training/MainViewModel.cs
deleted file mode 100644
index 0692b0d..0000000
--- a/src/SopHelper.Avalonia/Training/MainViewModel.cs
+++ /dev/null
@@ -1,559 +0,0 @@
-// 标注工作区视图模型:组织视频导入、帧标注、旧训练任务和项目设置,向界面同步进度与日志。
-
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.IO;
-using System.Text.Json;
-using Avalonia;
-using SopHelper.Presentation.Threading;
-using SopHelper.Presentation;
-using SopHelper.Presentation.Imaging;
-using SopHelper.Engine.Training;
-using SopHelper.Engine.Sop;
-using Prism.Commands;
-using Prism.Mvvm;
-
-namespace SopHelper.Training;
-
-public sealed class MainViewModel : BindableBase
-{
- private readonly WorkerClient _worker;
- private CancellationTokenSource? _cancellation;
- private TaskCompletionSource? _completion;
- private TrainingProject? _project;
- private FrameAnnotation? _selected;
- private BitmapImage? _preview;
- private bool _busy;
- private bool _importing, _stopping;
- private Task? _importTask;
- private double _progress;
- private string _status = "新建项目:导入视频,在任意清晰帧拖动画框";
- private string _logs = "";
- private readonly object _logGate = new();
- private bool _logWriteWarningShown;
- public string RuntimeLogPath { get; } = Path.Combine(DesktopPlatform.WorkspaceRoot, "logs",
- $"training-{DateTime.Now:yyyyMMdd-HHmmss}-{Guid.NewGuid():N}.log");
- private bool _isTraining;
- private string _trainingStatus = "打开已复核项目后即可开始训练";
- private string _trainingMetrics = "尚无训练指标";
- private string _latestWeights = "";
- private string _trainingRunDirectory = "";
- public bool IsTraining { get => _isTraining; private set => SetProperty(ref _isTraining, value); }
- public string TrainingStatus { get => _trainingStatus; private set => SetProperty(ref _trainingStatus, value); }
- public string TrainingMetrics { get => _trainingMetrics; private set => SetProperty(ref _trainingMetrics, value); }
- public string LatestWeights { get => _latestWeights; private set => SetProperty(ref _latestWeights, value); }
- private string _latestOnnx = "";
- public string LatestOnnx { get => _latestOnnx; private set => SetProperty(ref _latestOnnx, value); }
- public string TrainingRunDirectory { get => _trainingRunDirectory; private set => SetProperty(ref _trainingRunDirectory, value); }
- public string? VideoImportDirectory { get; set; }
- public string Root { get; }
- public TrainingProject? Project => _project;
- public ObservableCollection Frames { get; } = [];
- public bool IsBusy { get => _busy; private set { SetProperty(ref _busy, value); RaisePropertyChanged(nameof(IsIdle)); Commands.ForEach(c => c.RaiseCanExecuteChanged()); } }
- public bool IsIdle => !IsBusy && !IsImporting && !_stopping;
- public bool IsImporting
- {
- get => _importing;
- private set { SetProperty(ref _importing, value); RaisePropertyChanged(nameof(IsIdle)); Commands.ForEach(c => c.RaiseCanExecuteChanged()); }
- }
- public double Progress { get => _progress; set => SetProperty(ref _progress, value); }
- public string Status { get => _status; set => SetProperty(ref _status, value); }
- public string Logs { get => _logs; set => SetProperty(ref _logs, value); }
- public string Summary => _project == null ? "尚未导入视频" : $"{_project.Width} × {_project.Height} · {Frames.Count} 帧 · 已复核 {Frames.Count(f => f.Status is "reviewed" or "absent")} · 待复核 {Frames.Count(f => f.Status == "auto")}";
- public string FrameInfo => _selected == null || _project == null ? "拖动画框以标记零件" : $"第 {_selected.Index + 1} 帧 · 原视频帧 {_selected.SourceIndex} · {(_project.Fps > 0 ? (_selected.SourceIndex / _project.Fps).ToString("F2") + " 秒" : "时间未知")} · {_selected.Display}";
- public string ProjectPath => _project?.FilePath ?? "项目会自动保存到你选择的文件夹";
- public BitmapImage? Preview { get => _preview; private set => SetProperty(ref _preview, value); }
- private ObjectAnnotation? CurrentObject => _selected?.Objects.FirstOrDefault(o => o.Label == Label);
- public double[]? CurrentBox => CurrentObject?.Box;
- public IReadOnlyList CurrentAnnotations => _selected?.Objects.Where(o => o.Box != null).ToArray() ?? [];
- public string AnnotationSummary => string.Join("\n", CurrentAnnotations.Select(o => $"{o.Label} · {(o.Status == "reviewed" ? "已确认" : "待复核")}"));
- public FrameAnnotation? SelectedFrame
- {
- get => _selected;
- set
- {
- if (!SetProperty(ref _selected, value)) return;
- try
- {
- if (value != null && _project != null)
- {
- var bitmap = new BitmapImage();
- bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad;
- bitmap.UriSource = new Uri(Path.Combine(_project.DirectoryPath, value.Image));
- bitmap.EndInit(); bitmap.Freeze(); Preview = bitmap;
- }
- }
- catch (Exception e) { Status = "图像读取失败:" + e.Message; Preview = null; }
- RaisePropertyChanged(nameof(CurrentBox)); RaisePropertyChanged(nameof(FrameInfo));
- RaisePropertyChanged(nameof(CurrentAnnotations)); RaisePropertyChanged(nameof(AnnotationSummary));
- }
- }
- // Configuration is saved locally, except the API key which is passed only through the worker environment.
- private static string PythonPath => DesktopPlatform.PythonPath;
- public ObservableCollection Recipes { get; } = [];
- private string _recipeName = "";
- private bool _recipeLocked;
- /// 切换标注目标配方,并刷新配方下的零件、目录及关联项目状态。
- public void BindRecipe(string name)
- {
- RecipeName = name;
- _recipeLocked = true;
- }
- public string RecipeName
- {
- get => _recipeName;
- set
- {
- if (_recipeLocked && value != _recipeName) throw new InvalidOperationException("标注与训练固定使用当前编辑的配方,请打开其他配方的编辑窗口再操作");
- if (!SetProperty(ref _recipeName, value)) return;
- LoadSettings();
- if (_project is not null && _project.RecipeName != value)
- {
- _project=null;Label="";SelectedFrame=null;Frames.Clear();Preview=null;
- RaisePropertyChanged(nameof(Project));RaisePropertyChanged(nameof(Summary));RaisePropertyChanged(nameof(ProjectPath));
- Status="已切换配方,请导入视频或打开该配方的标注项目";
- }
- LoadTrainingResult();
- RefreshPartNames();
- RaisePropertyChanged(nameof(RecipeFolder));
- }
- }
- public string RecipeFolder => string.IsNullOrWhiteSpace(RecipeName) ? "请先选择配方" : RecipeDirectoryFor(RecipeName);
- private string RecipeDirectoryFor(string name)
- {
- if (string.IsNullOrWhiteSpace(name) || name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || name is "." or "..")
- throw new ArgumentException("请先选择有效的配方");
- return DesktopPlatform.Recipes.DirectoryFor(name);
- }
- public ObservableCollection PartNames { get; } = [];
- private string _label = "";
- public string Label
- {
- get => _label;
- set
- {
- if (IsBusy || IsImporting || value is null || (!string.IsNullOrEmpty(value) && !PartNames.Contains(value))) return;
- if (!SetProperty(ref _label, value)) return;
- RaisePropertyChanged(nameof(CurrentBox)); RaisePropertyChanged(nameof(CurrentAnnotations));
- }
- }
- public Func>? SelectImportVideoAsync { get; set; }
- public void RefreshPartNames()
- {
- var selected = Label;
- IReadOnlyList names = [];
- if (!string.IsNullOrWhiteSpace(RecipeName))
- {
- var path = DesktopPlatform.Recipes.ConfigPath(RecipeName);
- if (File.Exists(path))
- names = PartCatalog.Read(SopConfigLoader.Load(path), RecipeDirectoryFor(RecipeName));
- }
- for (var index = PartNames.Count - 1; index >= 0; index--)
- if (!names.Contains(PartNames[index])) PartNames.RemoveAt(index);
- for (var index = 0; index < names.Count; index++)
- {
- var existing = PartNames.IndexOf(names[index]);
- if (existing < 0) PartNames.Insert(index, names[index]);
- else if (existing != index) PartNames.Move(existing, index);
- }
- Label = PartNames.Contains(selected) ? selected : PartNames.FirstOrDefault() ?? "";
- }
- private void ValidatePart(string name)
- {
- RefreshPartNames();
- if (!PartNames.Contains(name)) throw new InvalidOperationException("请先维护并保存当前配方的零件列表,再选择要标注的零件");
- }
- public int ExtractStride { get; set; } = 1;
- public int MaxFrames { get; set; } = 600;
- public string Checkpoint { get; set; } = "";
- public string SamConfig { get; set; } = "configs/sam2.1/sam2.1_hiera_t.yaml";
- public string Device { get; set; } = "auto";
- public int ExportEvery { get; set; } = 5;
- public int Epochs { get; set; } = 50;
- public int Batch { get; set; } = 4;
- public int ImageSize { get; set; } = 640;
- public string Model => "yolo11n.pt";
- public string Endpoint { get; set; } = "https://api.example.com/v1";
- public string ApiModel { get; set; } = "";
- public string Description { get; set; } = "";
- public Func? ReadApiKey { get; set; }
- public DelegateCommand ImportCommand { get; }
- public DelegateCommand OpenCommand { get; }
- public DelegateCommand SaveParametersCommand { get; }
- public DelegateCommand DoctorCommand { get; }
- public DelegateCommand PropagateCommand { get; }
- public DelegateCommand ExportCommand { get; }
- public DelegateCommand TrainCommand { get; }
- public DelegateCommand OpenTrainingResultsCommand { get; }
- public DelegateCommand OnnxCommand { get; }
- public DelegateCommand SuggestCommand { get; }
- public DelegateCommand ApproveCommand { get; }
- public DelegateCommand ApproveAllCommand { get; }
- public DelegateCommand AbsentCommand { get; }
- public DelegateCommand EmptyFrameCommand { get; }
- public DelegateCommand ExcludeCommand { get; }
- public DelegateCommand PreviousCommand { get; }
- public DelegateCommand NextCommand { get; }
- public DelegateCommand CancelCommand { get; }
- public DelegateCommand RevealCommand { get; }
- private List Commands { get; } = [];
-
- public MainViewModel(WorkerClient worker)
- {
- _worker = worker;
- Root = DesktopPlatform.WorkspaceRoot;
- LoadSettings();
- SaveParametersCommand = Command(() =>
- {
- SaveSettings();
- Status = "参数已保存,下次打开时自动恢复";
- });
- ImportCommand = new DelegateCommand(() => _importTask = ImportAsync(), () => IsIdle);
- Commands.Add(ImportCommand);
- OpenCommand = Command(async () =>
- {
- var partsDirectory = Path.Combine(RecipeDirectoryFor(RecipeName), "parts");
- Directory.CreateDirectory(partsDirectory);
- var dialog = new OpenFileDialog { Filter = "标注项目|project.json", InitialDirectory = partsDirectory };
- if (await dialog.ShowDialogAsync() == true) Load(dialog.FileName);
- });
- DoctorCommand = Command(async () => await Run(new { action = "doctor" }, reload: false));
- PropagateCommand = Command(async () => { ValidateProjectTarget(); ValidatePart(Label); await Run(new { action = "propagate", project = RequireProject().FilePath, label = Label, checkpoint = Checkpoint, config = SamConfig, device = Device }); });
- ExportCommand = Command(async () => { ValidateProjectTarget(); await Run(Request("export")); });
- TrainCommand = Command(async () => { ValidateProjectTarget(); await Run(Request("train")); });
- OpenTrainingResultsCommand = Command(() =>
- {
- var directory = TrainingRunDirectory;
- if (!Directory.Exists(directory)) throw new DirectoryNotFoundException("尚无训练结果目录,请先完成一次训练");
- DesktopPlatform.Reveal(directory);
- });
- OnnxCommand = Command(async () => { ValidateProjectTarget(); await Run(Request("onnx")); });
- SuggestCommand = Command(async () =>
- {
- ValidateProjectTarget();
- ValidatePart(Label);
- if (SelectedFrame == null) throw new InvalidOperationException("请先选择帧");
- await Run(new { action = "suggest", project = RequireProject().FilePath, index = SelectedFrame.Index,
- label = Label, endpoint = Endpoint, apiModel = ApiModel, description = Description }, apiKey: ReadApiKey?.Invoke());
- });
- ApproveCommand = Command(() => Update("reviewed"));
- ApproveAllCommand = Command(ApproveAll);
- AbsentCommand = Command(() => Update("absent"));
- EmptyFrameCommand = Command(() =>
- {
- if (SelectedFrame == null) return;
- if (SelectedFrame.Objects.Any(o => o.Box != null)) throw new InvalidOperationException("该帧仍有零件框,请先逐个标记“当前零件不在”,再确认整帧无零件");
- SelectedFrame.Status = "absent"; RequireProject().Save(); Refresh();
- });
- ExcludeCommand = Command(() => Update("excluded"));
- PreviousCommand = Command(() => Move(-1));
- NextCommand = Command(() => Move(1));
- CancelCommand = new DelegateCommand(() => _cancellation?.Cancel());
- RevealCommand = Command(() =>
- {
- var directory=RecipeDirectoryFor(RecipeName);Directory.CreateDirectory(directory);DesktopPlatform.Reveal(directory);
- });
- }
- private DelegateCommand Command(Action action)
- {
- var command = new DelegateCommand(() => { try { action(); } catch (Exception e) { Status = e.Message; Append(e.Message); } }, () => IsIdle);
- Commands.Add(command); return command;
- }
- private DelegateCommand Command(Func action)
- {
- var command = new DelegateCommand(async () =>
- {
- try { await action(); }
- catch (Exception e) { Status = e.Message; Append(e.Message); }
- }, () => IsIdle);
- Commands.Add(command); return command;
- }
- // Async operations catch their own exceptions inside Run. Import does synchronous validation before awaiting.
- private object Request(string action) => new { action, project = RequireProject().FilePath, every = ExportEvery,
- valRatio = 0.2, epochs = Epochs, imageSize = ImageSize, batch = Batch, model = "yolo11n.pt", device = Device,
- outputDirectory = Path.Combine(RequireProject().RecipeDirectory, "runs") };
- private TrainingProject RequireProject() => _project ?? throw new InvalidOperationException("请先导入视频或打开项目");
- private void ValidateProjectTarget()
- {
- var project = RequireProject();
- RefreshPartNames();
- var missing = project.Frames.SelectMany(f => f.Objects).Select(o => o.Label).Distinct().Where(n => !PartNames.Contains(n)).ToArray();
- if (missing.Length > 0) throw new InvalidOperationException("标注中引用了零件列表外的名称:" + string.Join("、", missing));
- if (string.IsNullOrWhiteSpace(project.RecipeDirectory))
- {
- project.RecipeDirectory = RecipeDirectoryFor(RecipeName);
- project.RecipeName = RecipeName;
- }
- if (project.RecipeName != RecipeName) throw new InvalidOperationException("当前视频属于配方“" + project.RecipeName + "”,请切回该配方;新配方请导入新视频");
- project.Save();
- }
- /// 选择视频并通过工作进程建立标注项目;操作期间维护取消和界面忙状态。
- private async Task ImportAsync()
- {
- if (!IsIdle) return;
- IsImporting = true;
- try
- {
- var recipeDirectory = RecipeDirectoryFor(RecipeName);
- RefreshPartNames();
- string? videoPath;
- if (SelectImportVideoAsync is not null) videoPath = await SelectImportVideoAsync();
- else
- {
- var video = new OpenFileDialog { Filter = "视频|*.mp4;*.avi;*.mov;*.mkv;*.wmv|所有文件|*.*", InitialDirectory = Path.Combine(recipeDirectory, "recordings") };
- videoPath = await video.ShowDialogAsync() == true ? video.FileName : null;
- }
- if (_stopping || string.IsNullOrWhiteSpace(videoPath)) { Status = "已取消导入,原标注项目保持不变"; return; }
- var output = Path.Combine(recipeDirectory, "parts", "part-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + "-" + Guid.NewGuid().ToString("N")[..4]);
- if (await Run(new { action = "extract", video = videoPath, output, name = Path.GetFileNameWithoutExtension(videoPath), recipeName = RecipeName, recipeDirectory, stride = ExtractStride, maxFrames = MaxFrames }, reload: false))
- Load(Path.Combine(output, "project.json"));
- }
- catch (Exception e) { Status = e.Message; Append(e.Message); }
- finally { IsImporting = false; RefreshPartNames(); }
- }
- /// 载入项目及选中帧,同步项目元数据、标注列表和预览。
- public void Load(string path, int index = 0)
- {
- var incoming = TrainingProject.Load(path);
- if (_recipeLocked && !string.IsNullOrWhiteSpace(incoming.RecipeName) && incoming.RecipeName != RecipeName)
- throw new InvalidOperationException("该标注项目属于其他配方,请在对应配方的编辑窗口中打开");
- var name = string.IsNullOrWhiteSpace(incoming.RecipeName) ? RecipeName : incoming.RecipeName;
- path = DesktopPlatform.Recipes.ImportProject(name, path);
- _project = TrainingProject.Load(path);
- if (!string.IsNullOrWhiteSpace(_project.RecipeName))
- {
- if (!Recipes.Contains(_project.RecipeName)) Recipes.Add(_project.RecipeName);
- RecipeName = _project.RecipeName;
- }
- RefreshPartNames();
- var preferred = _project.Frames.SelectMany(f => f.Objects).FirstOrDefault()?.Label;
- if (string.IsNullOrEmpty(Label) && preferred != null && PartNames.Contains(preferred)) Label = preferred;
- _selected = null; Frames.Clear();
- foreach (var frame in _project.Frames) Frames.Add(frame);
- SelectedFrame = Frames[Math.Clamp(index, 0, Frames.Count - 1)];
- RaisePropertyChanged(nameof(Summary)); RaisePropertyChanged(nameof(ProjectPath));
- LoadTrainingResult();
- if (!IsBusy) Status = "项目已打开;拖动画框或选择帧进行复核";
- }
- public void DrawBox(double[] box)
- {
- if (IsBusy || SelectedFrame == null || _project == null) return;
- try
- {
- ValidatePart(Label); _project.ValidateBox(box);
- var item = GetOrCreateObject(); item.Box = box; item.Prompt = true; item.Status = "reviewed";
- SelectedFrame.Status = "auto"; _project.Save(); Refresh();
- Status = "当前零件关键帧已保存;可切换零件继续画框,全部标好后确认整帧,或传播当前零件";
- }
- catch (Exception e) { Status = e.Message; }
- }
- private void Update(string status)
- {
- if (SelectedFrame == null) return;
- if (status == "reviewed")
- {
- if (!SelectedFrame.Objects.Any(o => o.Box != null)) throw new InvalidOperationException("该帧没有零件框,请画框或确认整帧无零件");
- if (SelectedFrame.Objects.Any(o => o.Box == null && o.Status != "absent")) throw new InvalidOperationException("该帧仍有未确认的空框,请为对应零件补框,或标记“当前零件不在”");
- foreach (var item in SelectedFrame.Objects.Where(o => o.Box != null)) { RequireProject().ValidateBox(item.Box!); item.Status = "reviewed"; }
- SelectedFrame.Status = "reviewed";
- }
- else if (status == "absent")
- {
- ValidatePart(Label); var item = GetOrCreateObject(); item.Box = null; item.Prompt = false; item.Status = "absent";
- SelectedFrame.Status = "auto";
- }
- else SelectedFrame.Status = status;
- RequireProject().Save(); Refresh();
- Status = "当前帧已保存";
- }
- private void ApproveAll()
- {
- var project = RequireProject();
- var pending = project.Frames.Where(frame => frame.Status == "auto" && frame.Objects.Any(o => o.Box != null)).ToList();
- if (pending.Any(f => f.Objects.Any(o => o.Box == null && o.Status != "absent")))
- throw new InvalidOperationException("待复核帧中仍有自动标注未找到的零件,请补框或标记“当前零件不在”后再复核");
- // Validate the whole batch before changing any annotation status.
- foreach (var item in pending.SelectMany(f => f.Objects).Where(o => o.Box != null)) project.ValidateBox(item.Box!);
- if (pending.Count == 0) { Status = "没有带目标框的待复核帧"; return; }
- var selectedIndex = SelectedFrame?.Index ?? 0;
- var previous = pending.SelectMany(f => f.Objects).Select(o => (Item: o, o.Status)).ToArray();
- foreach (var frame in pending) { frame.Status = "reviewed"; foreach (var item in frame.Objects.Where(o => o.Box != null)) item.Status = "reviewed"; }
- try { project.Save(); }
- catch
- {
- foreach (var frame in pending) frame.Status = "auto";
- foreach (var item in previous) item.Item.Status = item.Status;
- throw;
- }
- Load(project.FilePath, selectedIndex);
- Status = $"一键复核完成:已确认 {pending.Count} 帧并保存";
- }
- private void Refresh()
- {
- var frame = SelectedFrame;
- if (frame == null) return;
- var index = Frames.IndexOf(frame); Frames[index] = frame;
- SelectedFrame = frame;
- RaisePropertyChanged(nameof(CurrentBox)); RaisePropertyChanged(nameof(FrameInfo)); RaisePropertyChanged(nameof(Summary));
- RaisePropertyChanged(nameof(CurrentAnnotations)); RaisePropertyChanged(nameof(AnnotationSummary));
- }
- private ObjectAnnotation GetOrCreateObject()
- {
- var item = CurrentObject;
- if (item != null) return item;
- item = new ObjectAnnotation { Label = Label }; SelectedFrame!.Objects.Add(item); return item;
- }
- private void Move(int delta)
- {
- if (Frames.Count > 0) SelectedFrame = Frames[Math.Clamp(Frames.IndexOf(SelectedFrame!) + delta, 0, Frames.Count - 1)];
- }
- private void Append(string line)
- {
- var entry = $"[{DateTimeOffset.Now:yyyy-MM-dd HH:mm:ss.fff zzz}] {line}";
- string? warning = null;
- // Persist before dispatching to the UI; the on-screen buffer can be truncated independently.
- lock (_logGate)
- {
- try
- {
- Directory.CreateDirectory(Path.GetDirectoryName(RuntimeLogPath)!);
- File.AppendAllText(RuntimeLogPath, entry + Environment.NewLine, new System.Text.UTF8Encoding(false));
- }
- catch (Exception e) when (e is IOException or UnauthorizedAccessException)
- {
- if (!_logWriteWarningShown)
- {
- _logWriteWarningShown = true;
- warning = $"日志文件写入失败:{RuntimeLogPath} · {e.Message}";
- }
- }
- }
- Dispatcher.CurrentDispatcher.Invoke(() =>
- {
- Logs += entry + Environment.NewLine;
- if (warning != null) Logs += warning + Environment.NewLine;
- if (Logs.Length > 40000) Logs = Logs[^30000..];
- });
- }
- /// 调用隔离的 Python 工作进程,收集进度日志,并按选项重新载入项目结果。
- private async Task Run(object request, bool reload = true, string? apiKey = null)
- {
- if (IsBusy) return false;
- var action = JsonSerializer.SerializeToElement(request).GetProperty("action").GetString();
- IsTraining = action == "train";
- if (IsTraining) { TrainingStatus = "正在准备数据与模型…"; TrainingMetrics = "等待首轮训练指标"; }
- IsBusy = true; Progress = 0; Status = "任务运行中…";
- _cancellation = new CancellationTokenSource();
- _completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
- var path = _project?.FilePath; var index = SelectedFrame?.Index ?? 0; var label = Label;
- var elapsed = Stopwatch.StartNew();
- var outcome = "失败";
- try
- {
- Append($"任务开始:{action} · 项目:{path ?? "无"} · 日志:{RuntimeLogPath}");
- SaveSettings();
- if (!File.Exists(PythonPath))
- throw new FileNotFoundException(DesktopPlatform.MissingPythonMessage, PythonPath);
- await _worker.RunAsync(PythonPath, Path.Combine(DesktopPlatform.ApplicationRoot, "tools", "worker.py"), request, line =>
- {
- try
- {
- using var json = JsonDocument.Parse(line);
- var item = json.RootElement;
- var message = item.TryGetProperty("message", out var m) ? m.GetString() ?? line : line;
- Append(message);
- Dispatcher.CurrentDispatcher.Invoke(() =>
- {
- Status = message;
- if (item.TryGetProperty("progress", out var progress) && (!IsTraining || item.TryGetProperty("event", out _))) Progress = Math.Clamp(progress.GetDouble(), 0, 1) * 100;
- if (IsTraining)
- {
- TrainingStatus = message;
- if (item.TryGetProperty("metrics", out var metrics)) TrainingMetrics = FormatMetrics(metrics);
- if (item.TryGetProperty("runDirectory", out var directory)) TrainingRunDirectory = directory.GetString() ?? "";
- if (item.TryGetProperty("weights", out var weights)) LatestWeights = weights.GetString() ?? "";
- }
- if (item.TryGetProperty("onnx", out var onnx)) LatestOnnx = onnx.GetString() ?? "";
- });
- if (item.TryGetProperty("modules", out var modules)) Append(modules.ToString());
- if (item.TryGetProperty("output", out var output)) Append(output.GetString() ?? "");
- }
- catch (Exception e) when (e is JsonException or InvalidOperationException or FormatException) { Append(line); }
- }, _cancellation.Token, apiKey);
- outcome = "完成"; Progress = 100; return true;
- }
- catch (OperationCanceledException) { outcome = "取消"; Status = "任务已取消;已保存的标注保留"; if (IsTraining) TrainingStatus = "训练已停止;已写入的日志与检查点保留在结果目录"; Append(Status); return false; }
- catch (Exception e) { Status = e.Message; if (IsTraining) TrainingStatus = "训练失败,请查看运行日志:" + e.Message; Append(e.Message); return false; }
- finally
- {
- Append($"任务{outcome}:{action} · 耗时 {elapsed.Elapsed.TotalSeconds:F2} 秒");
- if (reload && path != null)
- {
- try { Load(path, index); } catch (Exception e) { Append("重新读取项目失败:" + e.Message); }
- }
- _cancellation.Dispose(); _cancellation = null; IsBusy = false; IsTraining = false;
- RefreshPartNames(); if (PartNames.Contains(label)) Label = label;
- _completion.TrySetResult();
- }
- }
- public void Cancel() => _cancellation?.Cancel();
- /// 请求取消当前后台操作,并等待其完成清理。
- public async Task StopAsync()
- {
- _stopping = true; RaisePropertyChanged(nameof(IsIdle)); Commands.ForEach(c => c.RaiseCanExecuteChanged());
- Cancel();
- if (_completion != null) await _completion.Task;
- if (_importTask != null) await _importTask;
- }
- private static string FormatMetrics(JsonElement metrics) => string.Join(Environment.NewLine,
- metrics.EnumerateObject().Where(m => m.Value.ValueKind == JsonValueKind.Number)
- .Select(m => $"{m.Name}: {m.Value.GetDouble():F4}"));
- private void LoadTrainingResult()
- {
- if (IsTraining) return;
- LatestWeights = ""; LatestOnnx = ""; TrainingRunDirectory = ""; TrainingMetrics = "尚无训练指标";
- if (string.IsNullOrWhiteSpace(RecipeName)) return;
- var file = Path.Combine(RecipeDirectoryFor(RecipeName), "latest-model.json");
- if (!File.Exists(file)) return;
- try
- {
- using var result = JsonDocument.Parse(File.ReadAllText(file));
- LatestWeights = result.RootElement.GetProperty("weights").GetString() ?? "";
- if (result.RootElement.TryGetProperty("onnx", out var onnx)) LatestOnnx = onnx.GetString() ?? "";
- else if (File.Exists(Path.ChangeExtension(LatestWeights, ".onnx"))) LatestOnnx = Path.ChangeExtension(LatestWeights, ".onnx");
- TrainingRunDirectory = result.RootElement.TryGetProperty("runDirectory", out var directory) ? directory.GetString() ?? "" : Path.GetDirectoryName(Path.GetDirectoryName(LatestWeights)) ?? "";
- if (result.RootElement.TryGetProperty("metrics", out var metrics)) TrainingMetrics = FormatMetrics(metrics);
- }
- catch (Exception e) { Append("读取训练结果失败:" + e.Message); }
- }
- private void SaveSettings()
- {
- var directory = RecipeDirectoryFor(RecipeName);
- Directory.CreateDirectory(directory);
- File.WriteAllText(Path.Combine(directory, "training-settings.json"), JsonSerializer.Serialize(new
- { Checkpoint, SamConfig, Device, ExportEvery, Epochs, Batch, ImageSize, Model, Endpoint, ApiModel, Description, ExtractStride, MaxFrames }));
- }
- private void LoadSettings()
- {
- var path = string.IsNullOrWhiteSpace(RecipeName) ? Path.Combine(Root, "workspace", "settings.json")
- : Path.Combine(RecipeDirectoryFor(RecipeName), "training-settings.json");
- // 新配方使用默认参数,避免沿用刚刚查看的其他配方。
- ExtractStride=1; MaxFrames=600; ExportEvery=5; Epochs=50; Batch=4; ImageSize=640;
- Checkpoint=""; SamConfig="configs/sam2.1/sam2.1_hiera_t.yaml"; Device="auto";
- Endpoint="https://api.example.com/v1"; ApiModel=""; Description="";
- foreach (var property in GetType().GetProperties().Where(p => p.CanWrite)) RaisePropertyChanged(property.Name);
- if (!File.Exists(path)) return;
- try
- {
- using var settings = JsonDocument.Parse(File.ReadAllText(path));
- foreach (var item in settings.RootElement.EnumerateObject())
- {
- var property = GetType().GetProperty(item.Name);
- if (property?.SetMethod?.IsPublic == true && property.PropertyType == typeof(string)) property.SetValue(this, item.Value.GetString());
- else if (property?.SetMethod?.IsPublic == true && property.PropertyType == typeof(int)) property.SetValue(this, item.Value.GetInt32());
- if (property?.SetMethod?.IsPublic == true) RaisePropertyChanged(property.Name);
- }
- }
- catch (Exception) { Status = "设置文件不可读,已使用默认配置"; }
- }
-}
diff --git a/src/SopHelper.Avalonia/Training/TrainingPage.axaml b/src/SopHelper.Avalonia/Training/TrainingPage.axaml
deleted file mode 100644
index 0e20f6f..0000000
--- a/src/SopHelper.Avalonia/Training/TrainingPage.axaml
+++ /dev/null
@@ -1,167 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/SopHelper.Avalonia/Training/TrainingPage.axaml.cs b/src/SopHelper.Avalonia/Training/TrainingPage.axaml.cs
deleted file mode 100644
index 390dc7e..0000000
--- a/src/SopHelper.Avalonia/Training/TrainingPage.axaml.cs
+++ /dev/null
@@ -1,92 +0,0 @@
-// 标注页面事件层:连接选帧、标注操作与视图模型,并在页面退出时停止后台操作。
-
-using Avalonia.Controls;
-using Avalonia.Input;
-using Avalonia.Interactivity;
-using Avalonia.Threading;
-using Avalonia.Platform.Storage;
-using SopHelper.Engine.Camera;
-using SopHelper.VVMs.SopPage;
-
-namespace SopHelper.Training;
-
-public partial class TrainingPage : UserControl
-{
- private readonly MainViewModel _model;
- private readonly SopPageViewModel? _sop;
- private CameraWindow? _cameraWindow;
- private Window? _host;
- private bool _closing,_closedSafely;
- private readonly Func _selectedCameraProvider;
- private readonly Func _canOpenCamera;
- public MainViewModel Model => _model;
- public TrainingPage(MainViewModel model,SopPageViewModel? sop, bool embedded = false, Func? selectedCameraProvider = null, Func? canOpenCamera = null)
- {
- InitializeComponent();_model=model;_sop=sop;DataContext=model;
- _selectedCameraProvider=selectedCameraProvider??(()=>_sop?.SelectedCamera);
- _canOpenCamera=canOpenCamera??(()=>true);
- Canvas.BoxDrawn+=model.DrawBox;
- model.ReadApiKey=()=>ApiKey.Text??"";
- model.SelectImportVideoAsync=SelectImportVideoAsync;
- AttachedToVisualTree+=(_,_)=>
- {
- if (!embedded && !model.IsBusy && sop != null)
- {
- foreach (var recipe in sop.Recipes.Select(System.IO.Path.GetFileNameWithoutExtension).OfType())
- if (!model.Recipes.Contains(recipe)) model.Recipes.Add(recipe);
- if (string.IsNullOrWhiteSpace(model.RecipeName)) model.RecipeName = System.IO.Path.GetFileNameWithoutExtension(sop.SelectedRecipe) ?? "";
- }
- if(!model.IsBusy)model.RefreshPartNames();
- if(embedded)return;
- if(_host!=null || TopLevel.GetTopLevel(this) is not Window host)return;
- _host=host;host.Closing+=HostClosing;
- };
- AddHandler(KeyDownEvent,(_,e)=>
- {
- if(model.IsBusy || TopLevel.GetTopLevel(this)?.FocusManager?.GetFocusedElement() is TextBox)return;
- if(e.Key==Key.Left){model.PreviousCommand.Execute();e.Handled=true;}
- else if(e.Key==Key.Right){model.NextCommand.Execute();e.Handled=true;}
- else if(e.Key==Key.Enter && model.CurrentAnnotations.Count>0)
- {model.ApproveCommand.Execute();model.NextCommand.Execute();e.Handled=true;}
- },RoutingStrategies.Tunnel);
- }
- private async void OpenCameraClicked(object? sender,RoutedEventArgs e)
- {
- if(_closing || !_model.IsIdle)return;
- if(!_canOpenCamera() || _sop is { CanSelectCamera:false } || _sop is { IsConnected:true })
- {_model.Status="请先停止其他相机预览或 SOP 采集,再打开零件录像";return;}
- if(TopLevel.GetTopLevel(this) is not Window owner)return;
- if(string.IsNullOrWhiteSpace(_model.RecipeName)){_model.Status="请先选择配方,再打开录像";return;}
- _cameraWindow=new CameraWindow(new CameraViewModel(new CameraService(),_model.Root,_model.RecipeName,selectedCameraProvider:_selectedCameraProvider));
- try { await _cameraWindow.ShowDialog(owner); }
- finally { _model.VideoImportDirectory=_cameraWindow.Model.SaveDirectory;_cameraWindow=null; }
- }
- public async Task ShutdownAsync()
- {
- _closing=true;
- await _model.StopAsync();
- if(_cameraWindow is { } cameraWindow){await cameraWindow.Model.ShutdownAsync();cameraWindow.Close();}
- }
- private async Task SelectImportVideoAsync()
- {
- if(_closing || TopLevel.GetTopLevel(this) is not Window owner)return null;
- var directory=_model.VideoImportDirectory??System.IO.Path.Combine(_model.RecipeFolder,"recordings");
- var files=await owner.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
- {
- Title="选择标注视频",AllowMultiple=false,
- SuggestedStartLocation=System.IO.Directory.Exists(directory)?await owner.StorageProvider.TryGetFolderFromPathAsync(directory):null,
- FileTypeFilter=[new FilePickerFileType("视频"){Patterns=["*.mp4","*.avi","*.mov","*.mkv","*.wmv"]},FilePickerFileTypes.All]
- });
- if(files.Count==0)return null;
- return files[0].TryGetLocalPath()??throw new System.IO.IOException("请选择本地视频文件");
- }
- private async void HostClosing(object? sender,WindowClosingEventArgs e)
- {
- if(_closedSafely)return;e.Cancel=true;if(_closing)return;_closing=true;_host!.IsEnabled=false;
- try{await ShutdownAsync();}catch(Exception error){_model.Status="关闭训练任务时出错:"+error.Message;}
- _closedSafely=true;Dispatcher.UIThread.Post(()=>_host.Close());
- }
- private void LogChanged(object? sender,TextChangedEventArgs e)
- {if(sender is TextBox box)box.CaretIndex=box.Text?.Length??0;}
- private void ResetImageViewClicked(object? sender,RoutedEventArgs e)=>Canvas.ResetView();
-}
diff --git a/src/SopHelper.CrossPlatform.Engine/Training/Project.cs b/src/SopHelper.CrossPlatform.Engine/Training/Project.cs
deleted file mode 100644
index c39b327..0000000
--- a/src/SopHelper.CrossPlatform.Engine/Training/Project.cs
+++ /dev/null
@@ -1,83 +0,0 @@
-// 旧版标注项目数据:读取帧和对象标注、校验像素框,并保存为 JSON 项目文件。
-
-using System.Text.Json;
-using System.Text.Json.Serialization;
-
-namespace SopHelper.Engine.Training;
-
-public sealed class ObjectAnnotation
-{
- public string Label { get; set; } = "";
- public double[]? Box { get; set; }
- public string Status { get; set; } = "unlabeled";
- public bool Prompt { get; set; }
-}
-
-public sealed class FrameAnnotation
-{
- public int Index { get; set; }
- public int SourceIndex { get; set; }
- public string Image { get; set; } = "";
- [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public double[]? Box { get; set; }
- public string Status { get; set; } = "unlabeled";
- [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public bool Prompt { get; set; }
- public List Objects { get; set; } = [];
- [JsonIgnore] public string Display => $"{Index + 1:0000} · {Status switch { "reviewed" => "整帧已复核", "auto" => "自动待复核", "absent" => "整帧无零件", "excluded" => "已排除", _ => "待整帧复核" }} · {Objects.Count(o => o.Box != null)} 框";
-}
-
-public sealed class TrainingProject
-{
- public int AnnotationVersion { get; set; } = 1;
- public string Name { get; set; } = "零件";
- public string RecipeName { get; set; } = "";
- public string RecipeDirectory { get; set; } = "";
- public string Video { get; set; } = "";
- public int Width { get; set; }
- public int Height { get; set; }
- public double Fps { get; set; }
- public int Stride { get; set; } = 1;
- public List Frames { get; set; } = [];
- [JsonIgnore] public string FilePath { get; set; } = "";
- [JsonIgnore] public string DirectoryPath => Path.GetDirectoryName(FilePath)!;
- public static readonly JsonSerializerOptions JsonOptions = new()
- {
- PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true,
- PropertyNameCaseInsensitive = true
- };
- public static TrainingProject Load(string path)
- {
- var project = JsonSerializer.Deserialize(File.ReadAllText(path), JsonOptions)
- ?? throw new InvalidDataException("项目文件为空");
- project.FilePath = Path.GetFullPath(path);
- if (project.Width <= 0 || project.Height <= 0 || project.Frames.Count == 0)
- throw new InvalidDataException("项目没有有效的视频帧");
- foreach (var frame in project.Frames)
- {
- if (project.AnnotationVersion < 2 && frame.Objects.Count == 0 && (frame.Box != null || frame.Status is "reviewed" or "absent"))
- frame.Objects.Add(new ObjectAnnotation { Label = project.Name, Box = frame.Box, Status = frame.Status, Prompt = frame.Prompt });
- frame.Box = null; frame.Prompt = false;
- var root = Path.GetFullPath(project.DirectoryPath) + Path.DirectorySeparatorChar;
- if (!Path.GetFullPath(Path.Combine(root, frame.Image)).StartsWith(root, StringComparison.OrdinalIgnoreCase))
- throw new InvalidDataException("帧路径超出项目目录");
- if (frame.Objects.Any(o => string.IsNullOrWhiteSpace(o.Label)) || frame.Objects.Select(o => o.Label).Distinct().Count() != frame.Objects.Count)
- throw new InvalidDataException("同一帧的零件名称不能为空或重复");
- foreach (var item in frame.Objects)
- if (item.Box is { } box) project.ValidateBox(box);
- }
- project.AnnotationVersion = 2;
- return project;
- }
- public void ValidateBox(double[] box)
- {
- if (box.Length != 4 || box.Any(x => !double.IsFinite(x)) ||
- box[0] < 0 || box[1] < 0 || box[2] > Width || box[3] > Height ||
- box[2] <= box[0] || box[3] <= box[1])
- throw new ArgumentException("标注框必须位于图像内,且有正的宽度和高度");
- }
- public void Save()
- {
- var temporary = FilePath + ".tmp";
- File.WriteAllText(temporary, JsonSerializer.Serialize(this, JsonOptions));
- File.Move(temporary, FilePath, true);
- }
-}
diff --git a/src/SopHelper.CrossPlatform.Engine/Training/WorkerClient.cs b/src/SopHelper.CrossPlatform.Engine/Training/WorkerClient.cs
deleted file mode 100644
index cfcafe7..0000000
--- a/src/SopHelper.CrossPlatform.Engine/Training/WorkerClient.cs
+++ /dev/null
@@ -1,78 +0,0 @@
-// Python 工作进程桥接:每次操作传入 JSON 请求文件,异步读取输出,取消时终止进程树并清理请求。
-
-using System.Diagnostics;
-using System.Text;
-using System.Text.Json;
-
-namespace SopHelper.Engine.Training;
-
-/// One isolated Python process per operation; cancellation kills its entire process tree.
-public sealed class WorkerClient : IDisposable
-{
- private readonly object _gate = new();
- private readonly HashSet _processes = [];
- private bool _disposed;
-
- /// 终止当前桥接器登记的全部工作进程,后续调用将被拒绝。
- public void Dispose()
- {
- lock (_gate)
- {
- _disposed = true;
- foreach (var process in _processes)
- Kill(process);
- }
- }
-
- private static void Kill(Process process)
- {
- try { if (!process.HasExited) process.Kill(entireProcessTree: true); }
- catch (InvalidOperationException) { }
- }
- /// 通过请求文件传递结构化参数,密钥仅置于子进程环境;并发读取 stdout/stderr 避免管道阻塞。
- public async Task RunAsync(string python, string worker, object request, Action log,
- CancellationToken cancellationToken, string? apiKey = null)
- {
- var requestPath = Path.Combine(Path.GetTempPath(), $"parttrainer-{Guid.NewGuid():N}.json");
- await File.WriteAllTextAsync(requestPath, JsonSerializer.Serialize(request, TrainingProject.JsonOptions), cancellationToken);
- try
- {
- var info = new ProcessStartInfo(python)
- {
- UseShellExecute = false, CreateNoWindow = true,
- RedirectStandardOutput = true, RedirectStandardError = true,
- StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8,
- WorkingDirectory = Path.GetDirectoryName(worker)!
- };
- info.ArgumentList.Add("-u");
- info.ArgumentList.Add(worker);
- info.ArgumentList.Add(requestPath);
- info.Environment["PYTHONUTF8"] = "1";
- info.Environment["PARTTRAINER_API_KEY"] = apiKey ?? "";
- using var process = new Process { StartInfo = info };
- lock (_gate)
- {
- ObjectDisposedException.ThrowIf(_disposed, this);
- cancellationToken.ThrowIfCancellationRequested();
- if (!process.Start()) throw new IOException("无法启动 Python");
- _processes.Add(process);
- }
- try
- {
- using var registration = cancellationToken.Register(() =>
- {
- Kill(process);
- });
- async Task ReadAsync(StreamReader reader)
- {
- while (await reader.ReadLineAsync() is { } line) log(line);
- }
- await Task.WhenAll(ReadAsync(process.StandardOutput), ReadAsync(process.StandardError), process.WaitForExitAsync());
- cancellationToken.ThrowIfCancellationRequested();
- if (process.ExitCode != 0) throw new InvalidOperationException($"任务失败(退出码 {process.ExitCode}),请查看日志");
- }
- finally { lock (_gate) _processes.Remove(process); }
- }
- finally { File.Delete(requestPath); }
- }
-}
diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs
index b5ece13..9e6df80 100644
--- a/tests/Avalonia.Smoke/Program.cs
+++ b/tests/Avalonia.Smoke/Program.cs
@@ -420,31 +420,6 @@ internal static class Smoke
var drawing=new Window {Width=400,Height=400,Content=canvas};drawing.Show();await Task.Delay(60);
drawing.MouseDown(new Point(300,250),MouseButton.Left);drawing.MouseMove(new Point(100,150));drawing.MouseUp(new Point(100,150),MouseButton.Left);
Check(region.X1==50&®ion.Y1==25&®ion.X2==150&®ion.Y2==75,"Actual ROI pointer drag excludes image letterboxing and supports reverse drawing");
- double[]? drawn=null;var annotation=new AnnotationCanvas {Source=image,TargetName="目标零件 · 支架"};annotation.BoxDrawn+=box=>drawn=box;drawing.Content=annotation;await Task.Delay(60);
- drawing.MouseDown(new Point(100,150),MouseButton.Left);drawing.MouseMove(new Point(300,250));Save(drawing,"annotation-target-drag");drawing.MouseUp(new Point(300,250),MouseButton.Left);
- annotation.Box=drawn;Save(drawing,"annotation-target-saved");
- annotation.Box=[0,0,100,60];Save(drawing,"annotation-target-edge");annotation.Box=null;
- drawing.MouseDown(new Point(300,250),MouseButton.Left);drawing.MouseMove(new Point(100,150));drawing.MouseUp(new Point(100,150),MouseButton.Left);
- Check(drawn is {Length:4}&&drawn.SequenceEqual(new double[]{50,25,150,75}),"Actual annotation drag preserves original-image box coordinates");
- drawn=null;
- drawing.MouseWheel(new Point(150,175),new Vector(0,1));
- drawing.MouseDown(new Point(150,175),MouseButton.Right);drawing.MouseMove(new Point(170,185));drawing.MouseUp(new Point(170,185),MouseButton.Right);
- Check(drawn is null,"Right-button panning never creates an annotation");
- drawing.MouseDown(new Point(350,275),MouseButton.Left);drawing.MouseMove(new Point(110,155));drawing.MouseUp(new Point(110,155),MouseButton.Left);
- Check(drawn is {Length:4}&&drawn.Zip(new double[]{50,25,150,75}).All(p=>Math.Abs(p.First-p.Second)<.001),"Cursor-centered wheel zoom and right-button pan preserve original-image box coordinates");
- using(var nextImage=SopHelper.Presentation.Imaging.BitmapSource.Create(200,100,96,96,SopHelper.Presentation.Imaging.PixelFormats.Bgr24,null,new byte[200*100*3],600))
- {
- annotation.Source=nextImage;drawn=null;
- drawing.MouseDown(new Point(110,155),MouseButton.Left);drawing.MouseUp(new Point(350,275),MouseButton.Left);
- Check(drawn is {Length:4}&&drawn.Zip(new double[]{50,25,150,75}).All(p=>Math.Abs(p.First-p.Second)<.001),"Switching same-size frames retains zoom and pan");
- annotation.ResetView();drawn=null;
- drawing.MouseDown(new Point(100,150),MouseButton.Left);drawing.MouseUp(new Point(300,250),MouseButton.Left);
- Check(drawn is {Length:4}&&drawn.SequenceEqual(new double[]{50,25,150,75}),"Fit-to-window resets both zoom and pan");
- drawing.MouseDown(new Point(200,200),MouseButton.Right);drawing.MouseMove(new Point(220,210));
- annotation.Source=null;drawing.MouseUp(new Point(220,210),MouseButton.Right);annotation.Source=image;drawn=null;
- drawing.MouseDown(new Point(100,150),MouseButton.Left);drawing.MouseUp(new Point(300,250),MouseButton.Left);
- Check(drawn is {Length:4}&&drawn.SequenceEqual(new double[]{50,25,150,75}),"Clearing the image cancels panning and restores the fitted view");
- }
drawing.Close();
}
Check(userCameraBefore is null ? !File.Exists(userCameraPath) : File.Exists(userCameraPath)&&userCameraBefore.SequenceEqual(File.ReadAllBytes(userCameraPath)),"Smoke tests leave the real user's camera preference unchanged");
@@ -454,75 +429,6 @@ internal static class Smoke
catch(Exception ex){Console.Error.WriteLine(ex);}
finally{lifetime.Shutdown(_exit);}
}
- private static async Task CheckTrainingImport(IClassicDesktopStyleApplicationLifetime lifetime,Window owner,TrainingPage view,SopHelper.Training.MainViewModel trainer)
- {
- var store=new RecipeWorkspace(trainer.Root);var configPath=store.ConfigPath(trainer.RecipeName);
- var config=SopHelper.Engine.Sop.SopConfigLoader.Load(configPath);config.Sop.Parts=["支架","螺丝","测试零件"];
- SopHelper.Engine.Sop.SopConfigLoader.Save(config,configPath);trainer.RefreshPartNames();
- var selectVideo=trainer.SelectImportVideoAsync;
- async Task Import()
- {
- trainer.ImportCommand.Execute();
- for(var i=0;i<400&&(trainer.IsBusy||trainer.IsImporting);i++)await Task.Delay(20);
- Check(!trainer.IsBusy&&!trainer.IsImporting,"Video import finishes without a part picker");
- }
- try
- {
- trainer.SelectImportVideoAsync=()=>Task.FromResult(null);await Import();
- Check(trainer.Project is null,"Cancelling the video picker leaves the current project unchanged");
- var videoPath=Path.Combine(trainer.Root,"multi-part-test.avi");
- using(var writer=new VideoWriter(videoPath,FourCC.MJPG,10,new OpenCvSharp.Size(64,48)))
- {
- Check(writer.IsOpened(),"Import fixture video opens for writing");
- using var frame=new Mat(48,64,MatType.CV_8UC3,new Scalar(30,60,90));for(var i=0;i<30;i++)writer.Write(frame);
- }
- trainer.SelectImportVideoAsync=()=>Task.FromResult(videoPath);await Import();
- Check(trainer.Project is {AnnotationVersion:2}&&trainer.Frames.Count>0,"Video import creates an unassigned multi-part project");
- var selector=view.FindControl("TrainingTargetPart")!;
- selector.SelectedItem="支架";trainer.DrawBox([1,1,60,44]);
- selector.SelectedItem="螺丝";trainer.DrawBox([10,10,25,25]);
- Check(trainer.SelectedFrame!.Objects.Count==2&&trainer.CurrentAnnotations.Count==2&&trainer.SelectedFrame.Status=="auto","A nested second part preserves the first box and requires whole-frame review");
- Check(view.GetVisualDescendants().OfType().Single().Annotations!.Count==2,"Annotation canvas receives both part boxes at once");
- trainer.ApproveCommand.Execute();var first=trainer.Project!.FilePath;
- var saved=TrainingProject.Load(first);
- Check(saved.Frames[0].Status=="reviewed"&&saved.Frames[0].Objects.All(o=>o.Status=="reviewed"),"Whole-frame review saves both part labels");
- Save(owner,"multi-part-annotation");
- trainer.AbsentCommand.Execute();
- Check(trainer.SelectedFrame.Objects.Single(o=>o.Label=="支架").Box!=null&&trainer.CurrentBox==null,"Marking the selected part absent preserves other part boxes");
- trainer.Label="支架";trainer.DrawBox([2,2,58,43]);
- Check(trainer.SelectedFrame.Objects.Count==2&&trainer.SelectedFrame.Objects.Single(o=>o.Label=="螺丝").Status=="absent","Redrawing updates only the selected part");
- trainer.SelectedFrame=trainer.Frames[1];trainer.Label="螺丝";trainer.DrawBox([10,10,25,25]);trainer.Label="支架";
- trainer.Load(first,1);Check(trainer.SelectedFrame!.Objects.Single().Label=="螺丝","Reopening preserves per-frame part identities without relabeling");
- var before=File.ReadAllBytes(first);trainer.SelectImportVideoAsync=()=>Task.FromResult(null);await Import();
- Check(trainer.Project.FilePath==first&&File.ReadAllBytes(first).SequenceEqual(before),"Cancelling a later import preserves every existing annotation");
- }
- finally{trainer.SelectImportVideoAsync=selectVideo;}
- }
- private static async Task CheckTrainingLayout(Window window,TrainingPage view,SopHelper.Training.MainViewModel trainer)
- {
- var width=window.Width;var logs=trainer.Logs;var status=trainer.Status;
- var scroll=(ScrollViewer)view.Content!;var layout=(Grid)scroll.Content!;
- var canvas=view.GetVisualDescendants().OfType().Single();
- var tabs=view.GetVisualDescendants().OfType().Single();var selectedTab=tabs.SelectedIndex;
- try
- {
- trainer.Logs="训练日志:"+new string('W',3000);trainer.Status="训练状态:"+new string('W',1000);
- foreach(var size in new[]{1180d,1600d,1000d,1180d})
- {
- window.Width=size;
- for(var tab=0;tab100&&canvas.Bounds.Width<=expected-504,
- "Annotation canvas stays within the center column after resizing and tab changes");
- }
- }
- }
- finally {window.Width=width;trainer.Logs=logs;trainer.Status=status;tabs.SelectedIndex=selectedTab;}
- }
private static async Task CheckRecipeDeletion(IClassicDesktopStyleApplicationLifetime lifetime,Control settings,SopPageViewModel sop)
{
var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
diff --git a/tests/PartCatalog.Smoke/PartCatalog.Smoke.csproj b/tests/PartCatalog.Smoke/PartCatalog.Smoke.csproj
deleted file mode 100644
index be00036..0000000
--- a/tests/PartCatalog.Smoke/PartCatalog.Smoke.csproj
+++ /dev/null
@@ -1,7 +0,0 @@
-
- Exenet8.0enableenable
-
-
-
-
-
diff --git a/tests/PartCatalog.Smoke/Program.cs b/tests/PartCatalog.Smoke/Program.cs
deleted file mode 100644
index 1ab30fe..0000000
--- a/tests/PartCatalog.Smoke/Program.cs
+++ /dev/null
@@ -1,127 +0,0 @@
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Headless;
-using Avalonia.Markup.Xaml.Styling;
-using Avalonia.Themes.Fluent;
-using Avalonia.VisualTree;
-using Prism.Dialogs;
-using SopHelper.Engine.Sop;
-using SopHelper.Engine.Training;
-using SopHelper.Training;
-using SopHelper.VVMs.RecipeEditor;
-using System.Text.Json;
-
-internal static class Program
-{
- [STAThread]
- public static void Main()
- {
- var root = Path.Combine(Path.GetTempPath(), "part-catalog-smoke-" + Guid.NewGuid().ToString("N"));
- var previous = Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT");
- Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT", root);
- try
- {
- AppBuilder.Configure().UseHeadless(new AvaloniaHeadlessPlatformOptions()).SetupWithoutStarting();
- Application.Current!.Styles.Add(new FluentTheme());
- Application.Current.Styles.Add(new StyleInclude(new Uri("avares://SopHelper.Avalonia/")) { Source = new Uri("avares://SopHelper.Avalonia/Themes/Styles.axaml") });
- Run(new RecipeWorkspace(root));
- }
- finally
- {
- Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT", previous);
- // Test-owned temporary root, never application data.
- if (Path.GetFileName(root).StartsWith("part-catalog-smoke-") && Directory.Exists(root)) Directory.Delete(root, true);
- }
- }
-
- private static void Run(RecipeWorkspace storage)
- {
- var directory = storage.DirectoryFor("装配");
- Directory.CreateDirectory(directory);
- var config = new SopConfig(); config.Sop.Name = "装配";
- config.Sop.Model = new ModelDef { Classes = ["螺丝", "支架"] };
- config.Sop.Steps = [new StepDef { Id = 1, Name = "检查", Detection = new StepCondition { Method = ConditionMethod.ObjectPresent, TargetObject = "螺丝" }, MustKeep = ["支架"], RequiredObjects = ["螺丝"] }];
- var modelPath = Path.Combine(directory, "装配.onnx"); File.WriteAllText(modelPath, "test-model");
- File.WriteAllText(Path.Combine(directory, "latest-model.json"), JsonSerializer.Serialize(new { recipeName = "装配", onnx = modelPath, weights = Path.ChangeExtension(modelPath, ".pt"), imageSize = 640, classes = new[] { "支架", "螺丝" } }));
- Check(PartCatalog.Read(config, directory).SequenceEqual(new[] { "支架", "螺丝" }), "Legacy migration preserves trained class order and names");
- SopConfigLoader.Save(config, storage.ConfigPath("装配"));
- var vm = Open(storage, "装配");
- Check(vm.Recipe.PartNames.SequenceEqual(new[] { "", "支架", "螺丝" }), "Editor migrates the legacy catalog with an optional empty selection");
- var window = new Window { Width = 1180, Height = 820 };
- var editor = new RecipeEditor { DataContext = vm }; window.Content = editor; window.Show(); window.UpdateLayout();
- var pickers = editor.GetVisualDescendants().OfType().Where(c => ReferenceEquals(c.ItemsSource, vm.Recipe.PartNames)).ToArray();
- Check(pickers.Length == 3, "Target, must-keep and required-object fields use catalog pickers");
- var target = editor.FindControl("TargetPartPicker")!;
- target.SelectedItem = "支架";
- Check(vm.Recipe.SelectedStep!.Detection!.TargetObject == "支架", "Target selection writes back");
- vm.Recipe.Parts.AddCommand.Execute(); var added = vm.Recipe.Parts.Items.Last(); added.Text = "垫片";
- window.UpdateLayout();
- Check(target.Items.Contains("垫片") && vm.Recipe.SelectedStep.Detection.TargetObject == "支架", "Catalog edits refresh choices without erasing references");
- target.SelectedItem = "";
- Check(vm.Recipe.SelectedStep.Detection.TargetObject == "", "Explicit empty selection clears an optional target");
- target.SelectedItem = "螺丝";
- vm.Recipe.Model.Path = Path.Combine(storage.Root, "manual-model.onnx"); vm.Recipe.Model.InputSize = 999;
- vm.SaveCommand.Execute();
- var saved = SopConfigLoader.Load(storage.ConfigPath("装配"));
- Check(saved.Sop.Parts!.SequenceEqual(new[] { "支架", "螺丝", "垫片" }), "Central catalog persists with the recipe");
- Check(saved.Sop.Model!.Classes.SequenceEqual(new[] { "支架", "螺丝" }), "Saved model labels follow the recipe training publication order");
- Check(Path.GetFullPath(saved.Sop.Model.Path, directory) == modelPath && saved.Sop.Model.InputSize == 640, "Saving always uses the published recipe model instead of stale/manual settings");
- var before = File.ReadAllBytes(storage.ConfigPath("装配"));
- vm.Recipe.Parts.Items[0].Text = ""; vm.SaveCommand.Execute();
- Check(File.ReadAllBytes(storage.ConfigPath("装配")).SequenceEqual(before), "Empty catalog names cannot be saved");
- vm.Recipe.Parts.Items[0].Text = "螺丝"; vm.SaveCommand.Execute();
- Check(File.ReadAllBytes(storage.ConfigPath("装配")).SequenceEqual(before), "Duplicate catalog names cannot be saved");
- vm.Recipe.Parts.Items[0].Text = "支架";
- vm.Recipe.Parts.RemoveCommand.Execute(vm.Recipe.Parts.Items[0]); vm.SaveCommand.Execute();
- Check(File.ReadAllBytes(storage.ConfigPath("装配")).SequenceEqual(before), "Referenced parts cannot be deleted");
- var tabs = editor.GetVisualDescendants().OfType().Single();
- tabs.SelectedIndex = 4; window.UpdateLayout();
- Check(editor.FindControl("RecipeModelPath")!.Text == modelPath && !editor.GetVisualDescendants().OfType