From ba057ae43ed3c22b569db1b4cb629021f11778f9 Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 25 Nov 2026 10:08:52 +0800 Subject: [PATCH] =?UTF-8?q?=E9=80=80=E5=BD=B9=E6=97=A7=E9=9B=B6=E4=BB=B6?= =?UTF-8?q?=E6=A0=87=E6=B3=A8=E8=AE=AD=E7=BB=83=E5=8F=8A=E5=85=B6=E5=AE=89?= =?UTF-8?q?=E8=A3=85=E5=85=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AVALONIA.md | 32 +- LINUX.md | 49 +- WINDOWS.md | 2 +- .../Presentation/DesktopPlatform.cs | 13 +- .../SopHelper.Avalonia.csproj | 2 - .../Training/AnnotationCanvas.cs | 135 ---- .../Training/MainViewModel.cs | 559 ----------------- .../Training/TrainingPage.axaml | 167 ----- .../Training/TrainingPage.axaml.cs | 92 --- .../Training/Project.cs | 83 --- .../Training/WorkerClient.cs | 78 --- tests/Avalonia.Smoke/Program.cs | 94 --- .../PartCatalog.Smoke.csproj | 7 - tests/PartCatalog.Smoke/Program.cs | 127 ---- tests/Training.Smoke/Program.cs | 124 ---- tests/Training.Smoke/Training.Smoke.csproj | 1 - tests/Training.Smoke/check_gpu.py | 58 -- tests/Training.Smoke/test_recipe_training.py | 226 ------- tests/Training.WorkerSmoke/check.py | 79 --- tests/test_worker.py | 173 ------ tools/Deploy-Windows.ps1 | 4 +- tools/Publish-Avalonia.ps1 | 3 +- tools/Setup-Python.ps1 | 34 -- tools/Start-HandAiD3.ps1 | 2 +- tools/Start-HandAiLaya.ps1 | 2 +- tools/linux/Setup-Python.sh | 18 - tools/requirements.txt | 7 - tools/worker.py | 574 ------------------ 28 files changed, 17 insertions(+), 2728 deletions(-) delete mode 100644 src/SopHelper.Avalonia/Training/AnnotationCanvas.cs delete mode 100644 src/SopHelper.Avalonia/Training/MainViewModel.cs delete mode 100644 src/SopHelper.Avalonia/Training/TrainingPage.axaml delete mode 100644 src/SopHelper.Avalonia/Training/TrainingPage.axaml.cs delete mode 100644 src/SopHelper.CrossPlatform.Engine/Training/Project.cs delete mode 100644 src/SopHelper.CrossPlatform.Engine/Training/WorkerClient.cs delete mode 100644 tests/PartCatalog.Smoke/PartCatalog.Smoke.csproj delete mode 100644 tests/PartCatalog.Smoke/Program.cs delete mode 100644 tests/Training.Smoke/Program.cs delete mode 100644 tests/Training.Smoke/Training.Smoke.csproj delete mode 100644 tests/Training.Smoke/check_gpu.py delete mode 100644 tests/Training.Smoke/test_recipe_training.py delete mode 100644 tests/Training.WorkerSmoke/check.py delete mode 100644 tests/test_worker.py delete mode 100644 tools/Setup-Python.ps1 delete mode 100644 tools/linux/Setup-Python.sh delete mode 100644 tools/requirements.txt delete mode 100644 tools/worker.py 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 @@ - - - - - - - - - - - - - - - - - - - - -