退役旧零件标注训练及其安装入口
This commit is contained in:
parent
9600ae7674
commit
ba057ae43e
32
AVALONIA.md
32
AVALONIA.md
@ -9,14 +9,13 @@
|
|||||||
|---|---|
|
|---|---|
|
||||||
| 主窗口 Logo、左侧导航 | 原布局迁移到 `VVMs/MainWindow` |
|
| 主窗口 Logo、左侧导航 | 原布局迁移到 `VVMs/MainWindow` |
|
||||||
| SOP 参数、相机、配方、步骤、违规、日志 | `VVMs/SopPage`,保留原命令和 ViewModel 逻辑 |
|
| SOP 参数、相机、配方、步骤、违规、日志 | `VVMs/SopPage`,保留原命令和 ViewModel 逻辑 |
|
||||||
| 表单式配方编辑器 | `VVMs/RecipeEditor`,包含步骤、区域、全局设置、零件列表、检测模型、SOP流程视频、零件标注与训练七个标签页 |
|
| 表单式配方编辑器 | `VVMs/RecipeEditor`,包含步骤、SOP流程视频和 Agent助手三个标签页 |
|
||||||
| ROI 图像画框、坐标微调、相机取图 | Avalonia `RegionCanvas`,仍保存原图像素坐标 |
|
| ROI 图像画框、坐标微调、相机取图 | Avalonia `RegionCanvas`,仍保存原图像素坐标 |
|
||||||
| 零件标注、复核、SAM2、导出、YOLO 训练 | `Training` 嵌入配方编辑窗口,固定当前配方;每个编辑窗口独立持有模型和 worker,关闭时取消任务 |
|
| 相机预览、录像、退出清理 | 配方编辑器的 SOP流程视频页,保留相机互斥与关闭等待流程 |
|
||||||
| 相机预览、录像、退出清理 | `Training/CameraWindow`,保留相机互斥与关闭等待流程 |
|
| SOP、手部检测、左右手稳定器与录像器 | `SopHelper.CrossPlatform.Engine` 独立保存全部共享引擎源码,不引用归档仓库 |
|
||||||
| SOP、检测器、左右手稳定器、录像器、训练数据与 worker 客户端 | `SopHelper.CrossPlatform.Engine` 独立保存全部共享引擎源码,不引用归档仓库 |
|
|
||||||
|
|
||||||
界面框架相关 API(绘图、图像缓冲、文件选择、UI 调度、窗口关闭)统一由 Avalonia 实现。
|
界面框架相关 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。
|
两个发布目录都带有内容相同的 `source-manifest.json`,记录 UI、ViewModel、共享引擎源码及工程文件的 SHA256。
|
||||||
平台相关的中间文件/PDB 路径会影响 PE 文件字节,不能用整个 DLL 的文件哈希判断源代码是否相同。
|
平台相关的中间文件/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 时检查运行库。安装到仓库后重新构建并重启:
|
正常应为 `GPU (CUDA)`,显示 CPU 时检查运行库。安装到仓库后重新构建并重启:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
@ -68,14 +57,9 @@ CUDA 12 与 CUDA 13 的 cuDNN 9 DLL 名称相同,不能仅凭文件名混用
|
|||||||
dotnet run --project tests/Avalonia.Smoke -c Release
|
dotnet run --project tests/Avalonia.Smoke -c Release
|
||||||
```
|
```
|
||||||
|
|
||||||
测试覆盖实际共享壳与 Prism 导航、SOP 启停和原生推理、相机缓冲显示、配方对话框及七个标签页、
|
测试覆盖实际共享壳与 Prism 导航、SOP 启停和原生推理、相机缓冲显示、配方对话框及三个标签页、
|
||||||
打开编辑器不改配方字段、标注保存与切页保留、Python 环境检查、BGR 颜色和缓冲所有权、
|
打开编辑器不改配方字段、BGR 颜色和缓冲所有权、
|
||||||
实际鼠标正反向画框与留白坐标映射。渲染图与报告在 `artifacts/avalonia-smoke/`。
|
实际鼠标正反向画框与留白坐标映射。渲染图与报告在 `artifacts/avalonia-smoke/`。
|
||||||
测试使用假相机,避免枚举或占用现场硬件。也可对发布包执行 `--check-runtime` 验证模型与 SOP 引擎。
|
测试使用假相机,避免枚举或占用现场硬件。也可对发布包执行 `--check-runtime` 验证模型与 SOP 引擎。
|
||||||
|
|
||||||
2026-11-08:Windows 本地上述自动检查通过,Windows/Linux 发布构建通过。
|
Windows 和 Linux 的部署记录见 [WINDOWS.md](WINDOWS.md) 和 [LINUX.md](LINUX.md)。
|
||||||
后续已验证 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 绑定不同。
|
|
||||||
|
|||||||
49
LINUX.md
49
LINUX.md
@ -176,7 +176,7 @@ MD002 后续切换至 `/home/wl/sophelper/releases/avalonia-20261118-a2414fd`,
|
|||||||
已将源码提交 `8d356af` 发布到 `wl@192.168.0.167`(主机名 `md002`),
|
已将源码提交 `8d356af` 发布到 `wl@192.168.0.167`(主机名 `md002`),
|
||||||
版本目录为 `/home/wl/sophelper/releases/avalonia-20261118-8d356af`。
|
版本目录为 `/home/wl/sophelper/releases/avalonia-20261118-8d356af`。
|
||||||
`current` 和桌面启动器已切换到新版,图形会话中存在 SopHelper 窗口,程序保持运行。
|
`current` 和桌面启动器已切换到新版,图形会话中存在 SopHelper 窗口,程序保持运行。
|
||||||
这是当前移除 YOLO / 标注训练功能后的版本;下文 11 月 8 日的训练部署记录仅供历史参考。
|
该版本已移除 YOLO 推理和标注训练功能。
|
||||||
|
|
||||||
启动入口 `/home/wl/sophelper/run.sh` 设置:
|
启动入口 `/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
|
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 运行时:
|
在目标机的图形会话中执行 `./SopHelper.Avalonia`。桌面版通过 V4L2 采集 USB 相机,djev 服务使用独立运行环境。
|
||||||
|
|
||||||
```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 传播和导出,完整训练仍待现场验收。
|
|
||||||
|
|
||||||
## 后续部署
|
## 后续部署
|
||||||
|
|
||||||
@ -230,43 +222,6 @@ Linux 海康已验证 2448×2048 BayerRG8 采集和 BGR 转换;标注后端已
|
|||||||
它在新版本目录执行 `--check-runtime` 和 `--check-gpu`,通过后更新启动入口,保留 `configs`、`models`、`workspace`、`python` 和 `.cache`。
|
它在新版本目录执行 `--check-runtime` 和 `--check-gpu`,通过后更新启动入口,保留 `configs`、`models`、`workspace`、`python` 和 `.cache`。
|
||||||
图形环境需要 X11/XWayland、fontconfig 和中文字体;发布包自带 .NET 运行时。
|
图形环境需要 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)
|
## GPU 渲染和帧率验证(2026-11-08)
|
||||||
|
|
||||||
Linux 默认按 EGL → GLX → 软件渲染的顺序初始化。可用 `SOPHELPER_RENDERER=egl` 或
|
Linux 默认按 EGL → GLX → 软件渲染的顺序初始化。可用 `SOPHELPER_RENDERER=egl` 或
|
||||||
|
|||||||
@ -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\configs\sop` 带入 `d3-workflow.yaml`、`demo.yaml`、`hand-ai.yaml` 三个模板配方;
|
||||||
`C:\sophelper\models` 有 palm、landmark 两个手部模型(另有旧包遗留的 `yolo11n.onnx`,当前代码不加载)。
|
`C:\sophelper\models` 有 palm、landmark 两个手部模型(另有旧包遗留的 `yolo11n.onnx`,当前代码不加载)。
|
||||||
- 未随包部署:djev 服务(该机没有 `E:\D3Lite`,程序启动时不会自动拉起,需在“运行设置 → djev”配置远端 `SOPHELPER_VISION_ENDPOINT`,
|
- 未随包部署:djev 服务(该机没有 `E:\D3Lite`,程序启动时不会自动拉起,需在“运行设置 → djev”配置远端 `SOPHELPER_VISION_ENDPOINT`,
|
||||||
或在工位机安装 djev 后由程序自动启动)、SAM2/训练用 Python 环境(`BundlePythonRuntime=false`,`current\python` 不存在)。
|
或在工位机安装 djev 后由程序自动启动)、SAM2/训练用 Python 环境。
|
||||||
- 相机:现场按 USB(UVC)接入,首次运行在“运行设置”里选择设备并确认实测 fps;本次未接相机,未做采集验证。
|
- 相机:现场按 USB(UVC)接入,首次运行在“运行设置”里选择设备并确认实测 fps;本次未接相机,未做采集验证。
|
||||||
|
|
||||||
## W-184 d3-nano 部署(2026-11-20)
|
## W-184 d3-nano 部署(2026-11-20)
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
// 桌面平台适配:集中解析工作区、配方和 Python 路径,并封装系统文件选择及目录展示。
|
// 桌面平台适配:集中解析工作区、配方路径,并封装系统文件选择及目录展示。
|
||||||
|
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using Avalonia.Controls;
|
using Avalonia.Controls;
|
||||||
@ -39,17 +39,6 @@ internal static class DesktopPlatform
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
public static Window Owner => ((IClassicDesktopStyleApplicationLifetime)Avalonia.Application.Current!.ApplicationLifetime!).MainWindow!;
|
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)
|
public static void Reveal(string path)
|
||||||
{
|
{
|
||||||
var directory=File.Exists(path)?Path.GetDirectoryName(path)!:path;
|
var directory=File.Exists(path)?Path.GetDirectoryName(path)!:path;
|
||||||
|
|||||||
@ -14,7 +14,6 @@
|
|||||||
<NativePlatform Condition="'$(NativePlatform)' == '' and '$(OS)' == 'Windows_NT'">Windows</NativePlatform>
|
<NativePlatform Condition="'$(NativePlatform)' == '' and '$(OS)' == 'Windows_NT'">Windows</NativePlatform>
|
||||||
<NativePlatform Condition="'$(NativePlatform)' == ''">Linux</NativePlatform>
|
<NativePlatform Condition="'$(NativePlatform)' == ''">Linux</NativePlatform>
|
||||||
<ApplicationIcon>BWS.ico</ApplicationIcon>
|
<ApplicationIcon>BWS.ico</ApplicationIcon>
|
||||||
<BundlePythonRuntime Condition="'$(BundlePythonRuntime)' == ''">false</BundlePythonRuntime>
|
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="../SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj" />
|
<ProjectReference Include="../SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj" />
|
||||||
@ -29,6 +28,5 @@
|
|||||||
<Content Include="../../tools/start_d3_lite_local.py" Link="services/start_d3_lite_local.py" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
|
<Content Include="../../tools/start_d3_lite_local.py" Link="services/start_d3_lite_local.py" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
|
||||||
<Content Include="../../models/palm*.onnx;../../models/hand_landmark*.onnx" Link="models/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
|
<Content Include="../../models/palm*.onnx;../../models/hand_landmark*.onnx" Link="models/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
|
||||||
<Content Include="BWS.ico" />
|
<Content Include="BWS.ico" />
|
||||||
<Content Include="../../python/**/*" Exclude="../../python/**/__pycache__/**;../../python/**/*.pyc;../../python/**/*.lnk" Link="python/%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="Never" Condition="'$(NativePlatform)' == 'Windows' and '$(BundlePythonRuntime)' == 'true'" />
|
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@ -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<BitmapSource?> SourceProperty=AvaloniaProperty.Register<AnnotationCanvas,BitmapSource?>(nameof(Source));
|
|
||||||
public static readonly StyledProperty<double[]?> BoxProperty=AvaloniaProperty.Register<AnnotationCanvas,double[]?>(nameof(Box));
|
|
||||||
public static readonly StyledProperty<string> TargetNameProperty=AvaloniaProperty.Register<AnnotationCanvas,string>(nameof(TargetName), "");
|
|
||||||
public static readonly StyledProperty<IReadOnlyList<ObjectAnnotation>?> AnnotationsProperty=AvaloniaProperty.Register<AnnotationCanvas,IReadOnlyList<ObjectAnnotation>?>(nameof(Annotations));
|
|
||||||
public IReadOnlyList<ObjectAnnotation>? 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<double[]>? BoxDrawn;
|
|
||||||
private Point? _start;private Point _end;private IPointer? _pointer;
|
|
||||||
private double _zoom=1;
|
|
||||||
private Vector _offset;
|
|
||||||
private Point? _panStart;
|
|
||||||
static AnnotationCanvas(){AffectsRender<AnnotationCanvas>(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<BitmapSource?>();
|
|
||||||
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));
|
|
||||||
}
|
|
||||||
@ -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<FrameAnnotation> 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<ObjectAnnotation> 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<string> Recipes { get; } = [];
|
|
||||||
private string _recipeName = "";
|
|
||||||
private bool _recipeLocked;
|
|
||||||
/// <summary>切换标注目标配方,并刷新配方下的零件、目录及关联项目状态。</summary>
|
|
||||||
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<string> 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<Task<string?>>? SelectImportVideoAsync { get; set; }
|
|
||||||
public void RefreshPartNames()
|
|
||||||
{
|
|
||||||
var selected = Label;
|
|
||||||
IReadOnlyList<string> 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<string>? 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<DelegateCommand> 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<Task> 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();
|
|
||||||
}
|
|
||||||
/// <summary>选择视频并通过工作进程建立标注项目;操作期间维护取消和界面忙状态。</summary>
|
|
||||||
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(); }
|
|
||||||
}
|
|
||||||
/// <summary>载入项目及选中帧,同步项目元数据、标注列表和预览。</summary>
|
|
||||||
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..];
|
|
||||||
});
|
|
||||||
}
|
|
||||||
/// <summary>调用隔离的 Python 工作进程,收集进度日志,并按选项重新载入项目结果。</summary>
|
|
||||||
private async Task<bool> 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();
|
|
||||||
/// <summary>请求取消当前后台操作,并等待其完成清理。</summary>
|
|
||||||
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 = "设置文件不可读,已使用默认配置"; }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,167 +0,0 @@
|
|||||||
<UserControl xmlns="https://github.com/avaloniaui" xmlns:local="clr-namespace:SopHelper.Training" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SopHelper.Training.TrainingPage" xmlns:conv="using:Avalonia.Data.Converters">
|
|
||||||
<UserControl.Styles>
|
|
||||||
<StyleInclude Source="avares://SopHelper.Avalonia/Training/Styles.axaml" />
|
|
||||||
</UserControl.Styles>
|
|
||||||
<UserControl.Resources>
|
|
||||||
</UserControl.Resources>
|
|
||||||
<ScrollViewer Margin="12" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
|
|
||||||
<Grid Width="{Binding Viewport.Width, RelativeSource={RelativeSource AncestorType=ScrollViewer}}" Height="{Binding Viewport.Height, RelativeSource={RelativeSource AncestorType=ScrollViewer}}" MinWidth="960" MinHeight="540">
|
|
||||||
<Grid.RowDefinitions>
|
|
||||||
<RowDefinition Height="Auto" />
|
|
||||||
<RowDefinition Height="*" />
|
|
||||||
<RowDefinition Height="130" />
|
|
||||||
<RowDefinition Height="Auto" />
|
|
||||||
</Grid.RowDefinitions>
|
|
||||||
<StackPanel Margin="0,0,0,10" Spacing="8">
|
|
||||||
<Grid ColumnDefinitions="*,Auto">
|
|
||||||
<TextBlock Text="零件标注与训练" FontSize="18" FontWeight="Bold" Foreground="{StaticResource Accent}" />
|
|
||||||
<TextBlock Grid.Column="1" Text="{Binding RecipeName}" Foreground="{StaticResource Dim}" TextTrimming="CharacterEllipsis" MaxWidth="360" ToolTip.Tip="{Binding RecipeFolder}" />
|
|
||||||
</Grid>
|
|
||||||
<WrapPanel>
|
|
||||||
<Button Content="相机与录像" Click="OpenCameraClicked" IsEnabled="{Binding IsIdle}" />
|
|
||||||
<Button Content="导入视频" Command="{Binding ImportCommand}" />
|
|
||||||
<Button Content="打开项目" Command="{Binding OpenCommand}" />
|
|
||||||
<Button Content="保存参数" Command="{Binding SaveParametersCommand}" ToolTip.Tip="保存标注、训练和设置参数,下次打开时自动恢复" />
|
|
||||||
<Button Content="配方文件夹" Command="{Binding RevealCommand}" />
|
|
||||||
<Button Content="取消任务" Command="{Binding CancelCommand}" IsEnabled="{Binding IsBusy}" />
|
|
||||||
</WrapPanel>
|
|
||||||
</StackPanel>
|
|
||||||
<Grid Grid.Row="1">
|
|
||||||
<Grid.ColumnDefinitions>
|
|
||||||
<ColumnDefinition Width="180" />
|
|
||||||
<ColumnDefinition Width="12" />
|
|
||||||
<ColumnDefinition Width="*" />
|
|
||||||
<ColumnDefinition Width="12" />
|
|
||||||
<ColumnDefinition Width="300" />
|
|
||||||
</Grid.ColumnDefinitions>
|
|
||||||
<DockPanel>
|
|
||||||
<StackPanel DockPanel.Dock="Top" Margin="0,0,0,10">
|
|
||||||
<TextBlock Text="视频帧" FontSize="16" FontWeight="Bold" />
|
|
||||||
<TextBlock Text="{Binding Summary}" Classes="Hint" />
|
|
||||||
</StackPanel>
|
|
||||||
<ListBox ItemsSource="{Binding Frames}" SelectedItem="{Binding SelectedFrame}" IsEnabled="{Binding IsIdle}">
|
|
||||||
<ListBox.ItemTemplate>
|
|
||||||
<DataTemplate>
|
|
||||||
<TextBlock Text="{Binding Display}" FontSize="12" />
|
|
||||||
</DataTemplate>
|
|
||||||
</ListBox.ItemTemplate>
|
|
||||||
</ListBox>
|
|
||||||
</DockPanel>
|
|
||||||
<Grid Grid.Column="2">
|
|
||||||
<Grid.RowDefinitions>
|
|
||||||
<RowDefinition Height="Auto" />
|
|
||||||
<RowDefinition Height="*" />
|
|
||||||
<RowDefinition Height="Auto" />
|
|
||||||
<RowDefinition Height="Auto" />
|
|
||||||
</Grid.RowDefinitions>
|
|
||||||
<TextBlock Text="{Binding FrameInfo}" Margin="0,0,0,10" TextWrapping="Wrap" />
|
|
||||||
<Border Grid.Row="1" Background="#080E14" BorderBrush="{StaticResource Line}" BorderThickness="1" CornerRadius="6" ClipToBounds="True" Classes="panel">
|
|
||||||
<local:AnnotationCanvas x:Name="Canvas" Source="{Binding Preview}" Box="{Binding CurrentBox}" Annotations="{Binding CurrentAnnotations}" TargetName="{Binding Label}" IsEnabled="{Binding IsIdle}" />
|
|
||||||
</Border>
|
|
||||||
<WrapPanel Grid.Row="2" Margin="0,12,0,0">
|
|
||||||
<Button Content="适应窗口" Click="ResetImageViewClicked" />
|
|
||||||
<Button Content="← 上一帧" Command="{Binding PreviousCommand}" />
|
|
||||||
<Button Content="下一帧 →" Command="{Binding NextCommand}" />
|
|
||||||
<Button Content="确认整帧" Command="{Binding ApproveCommand}" ToolTip.Tip="确认这一帧所有可见零件均已标全,允许导出训练" />
|
|
||||||
<Button Content="一键复核" Command="{Binding ApproveAllCommand}" ToolTip.Tip="请先检查所有待复核帧的可见零件是否标全;此操作会将它们全部确认为完整训练样本" />
|
|
||||||
<Button Content="当前零件不在" Command="{Binding AbsentCommand}" />
|
|
||||||
<Button Content="整帧无零件" Command="{Binding EmptyFrameCommand}" />
|
|
||||||
<Button Content="排除此帧" Command="{Binding ExcludeCommand}" />
|
|
||||||
</WrapPanel>
|
|
||||||
<TextBlock Grid.Row="3" Text="滚轮缩放,右键拖动图像,左键画框或修正并自动保存。← → 切帧,Enter 确认并进入下一帧。" Classes="Hint" TextWrapping="Wrap" />
|
|
||||||
</Grid>
|
|
||||||
<TabControl Grid.Column="4" IsEnabled="{Binding IsIdle}">
|
|
||||||
<TabItem Header="标注">
|
|
||||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
|
||||||
<StackPanel>
|
|
||||||
<TextBlock Text="所属配方" />
|
|
||||||
<TextBlock Text="{Binding RecipeName}" FontWeight="Bold" />
|
|
||||||
<TextBlock Text="一个视频可标注多种零件;零件名称在“零件列表”中维护,修改后请先保存配方。" Classes="Hint" />
|
|
||||||
<TextBlock Text="当前标注零件" Margin="0,12,0,0" />
|
|
||||||
<ComboBox x:Name="TrainingTargetPart" ItemsSource="{Binding PartNames}" SelectedItem="{Binding Label, Mode=TwoWay, Converter={StaticResource SelectionConverter}}" />
|
|
||||||
<TextBlock Text="切换零件后画框,每种零件每帧保存一个框;其他零件的框会保留,允许重叠和包含。" Classes="Hint" />
|
|
||||||
<TextBlock Text="本帧已标零件" FontWeight="Bold" Margin="0,8,0,4" />
|
|
||||||
<TextBlock Text="{Binding AnnotationSummary}" TextWrapping="Wrap" />
|
|
||||||
<TextBlock Text="抽帧间隔(原视频帧数)" />
|
|
||||||
<TextBox Text="{Binding ExtractStride, Mode=TwoWay}" />
|
|
||||||
<TextBlock Text="最多导入帧数" />
|
|
||||||
<TextBox Text="{Binding MaxFrames, Mode=TwoWay}" />
|
|
||||||
<TextBlock Text="默认最多600帧;长视频会自动增大间隔覆盖全片。快速旋转建议分成短片导入。" Classes="Hint" />
|
|
||||||
<TextBlock Text="02 画框并自动传播" FontWeight="Bold" Foreground="{StaticResource Accent}" Margin="0,10,0,8" />
|
|
||||||
<Button Content="自动标注当前零件" Command="{Binding PropagateCommand}" BorderBrush="{StaticResource Accent}" />
|
|
||||||
<TextBlock Text="先为当前零件补充清晰关键帧,再自动传播;仅更新当前零件,保留其他零件以及当前零件已手工确认的框。多个零件分别运行,遮挡或装配处请补框复核。" Classes="Hint" />
|
|
||||||
<TextBlock Text="03 人工复核" FontWeight="Bold" Foreground="{StaticResource Accent}" />
|
|
||||||
<TextBlock Text="所有可见零件均标全后点“确认整帧”;仅画框或自动传播不会将整帧加入训练。当前零件不在只清除该零件,整帧无零件用于负样本,排除帧不参与训练。" Classes="Hint" />
|
|
||||||
</StackPanel>
|
|
||||||
</ScrollViewer>
|
|
||||||
</TabItem>
|
|
||||||
<TabItem Header="训练">
|
|
||||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
|
||||||
<StackPanel>
|
|
||||||
<TextBlock Text="YOLO 目标检测训练" FontSize="16" FontWeight="Bold" />
|
|
||||||
<TextBlock Text="按时间分段:前段训练、末尾20%验证,边界留出间隔。正式评估请另拍独立测试视频。" Classes="Hint" />
|
|
||||||
<TextBlock Text="训练抽样间隔(导入后的帧数)" />
|
|
||||||
<TextBox Text="{Binding ExportEvery, Mode=TwoWay}" />
|
|
||||||
<TextBlock Text="配方模型(自动管理)" />
|
|
||||||
<TextBlock Text="{Binding RecipeName}" FontWeight="Bold" />
|
|
||||||
<TextBlock Text="首次自动使用预训练模型,之后自动加载上一版配方模型。" Classes="Hint" />
|
|
||||||
<TextBlock Text="训练轮数" />
|
|
||||||
<TextBox Text="{Binding Epochs, Mode=TwoWay}" />
|
|
||||||
<TextBlock Text="图像尺寸(32的倍数)" />
|
|
||||||
<TextBox Text="{Binding ImageSize, Mode=TwoWay}" />
|
|
||||||
<TextBlock Text="批次大小" />
|
|
||||||
<TextBox Text="{Binding Batch, Mode=TwoWay}" />
|
|
||||||
<Button Content="导出 YOLO 数据集" Command="{Binding ExportCommand}" />
|
|
||||||
<Button Content="训练并更新配方模型" Command="{Binding TrainCommand}" BorderBrush="{StaticResource Accent}" />
|
|
||||||
<Button Content="打开最新训练结果" Command="{Binding OpenTrainingResultsCommand}" />
|
|
||||||
<TextBlock Text="{Binding LatestWeights}" Classes="Hint" />
|
|
||||||
<Button Content="重新导出配方 ONNX" Command="{Binding OnnxCommand}" />
|
|
||||||
<TextBlock Text="{Binding LatestOnnx}" TextWrapping="Wrap" />
|
|
||||||
<TextBlock Text="每次训练累计使用本配方已加入的零件视频复核数据,自动导出配方同名 ONNX 并保留独立版本。导出成功后更新最新模型;运行前重新应用配方即可加载。" Classes="Hint" />
|
|
||||||
</StackPanel>
|
|
||||||
</ScrollViewer>
|
|
||||||
</TabItem>
|
|
||||||
<TabItem Header="设置">
|
|
||||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
|
||||||
<StackPanel>
|
|
||||||
<Button Content="检查环境与 CUDA" Command="{Binding DoctorCommand}" />
|
|
||||||
<TextBlock Text="设备:auto / cpu / cuda(训练可填0)" />
|
|
||||||
<TextBox Text="{Binding Device, Mode=TwoWay}" />
|
|
||||||
<TextBlock Text="SAM2 checkpoint(留空自动下载 tiny)" />
|
|
||||||
<TextBox Text="{Binding Checkpoint, Mode=TwoWay}" />
|
|
||||||
<TextBlock Text="SAM2 配置(仅本地 checkpoint 使用)" />
|
|
||||||
<TextBox Text="{Binding SamConfig, Mode=TwoWay}" />
|
|
||||||
<TextBlock Text="可选:视觉大模型建议框" FontWeight="Bold" Margin="0,12,0,0" />
|
|
||||||
<TextBlock Text="兼容 chat/completions 的视觉接口。点击时会上传当前帧到下方地址;结果需人工确认,再用于 SAM2 传播。" Classes="Hint" />
|
|
||||||
<TextBlock Text="API Base URL(包含 /v1,不含 /chat/completions)" />
|
|
||||||
<TextBox Text="{Binding Endpoint, Mode=TwoWay}" />
|
|
||||||
<TextBlock Text="视觉模型名称" />
|
|
||||||
<TextBox Text="{Binding ApiModel, Mode=TwoWay}" />
|
|
||||||
<TextBlock Text="API Key(仅本次运行,不写入项目)" />
|
|
||||||
<TextBox x:Name="ApiKey" PasswordChar="●" />
|
|
||||||
<TextBlock Text="零件外观描述" />
|
|
||||||
<TextBox Text="{Binding Description, Mode=TwoWay}" AcceptsReturn="True" Height="64" TextWrapping="Wrap" />
|
|
||||||
<Button Content="让视觉模型建议当前帧目标框" Command="{Binding SuggestCommand}" />
|
|
||||||
</StackPanel>
|
|
||||||
</ScrollViewer>
|
|
||||||
</TabItem>
|
|
||||||
</TabControl>
|
|
||||||
</Grid>
|
|
||||||
<Grid Grid.Row="2" Margin="0,12,0,0">
|
|
||||||
<Grid.RowDefinitions>
|
|
||||||
<RowDefinition Height="Auto" />
|
|
||||||
<RowDefinition Height="*" />
|
|
||||||
</Grid.RowDefinitions>
|
|
||||||
<DockPanel>
|
|
||||||
<TextBlock Text="运行日志" Foreground="{StaticResource Dim}" />
|
|
||||||
<TextBlock Text="{Binding ProjectPath}" TextTrimming="CharacterEllipsis" HorizontalAlignment="Right" MaxWidth="850" Foreground="{StaticResource Dim}" />
|
|
||||||
</DockPanel>
|
|
||||||
<TextBox x:Name="LogBox" Grid.Row="1" Text="{Binding Logs, Mode=OneWay}" IsReadOnly="True" TextWrapping="Wrap" ScrollViewer.VerticalScrollBarVisibility="Auto" FontFamily="Consolas, Microsoft YaHei" TextChanged="LogChanged" Margin="0,6,0,0" />
|
|
||||||
</Grid>
|
|
||||||
<DockPanel Grid.Row="3" Margin="0,10,0,0">
|
|
||||||
<ProgressBar DockPanel.Dock="Right" Width="180" Height="5" Value="{Binding Progress}" Foreground="{StaticResource Accent}" Background="{StaticResource Line}" />
|
|
||||||
<TextBlock Text="{Binding Status}" TextTrimming="CharacterEllipsis" Margin="0,0,15,0" />
|
|
||||||
</DockPanel>
|
|
||||||
</Grid>
|
|
||||||
</ScrollViewer>
|
|
||||||
</UserControl>
|
|
||||||
@ -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<CameraInfo?> _selectedCameraProvider;
|
|
||||||
private readonly Func<bool> _canOpenCamera;
|
|
||||||
public MainViewModel Model => _model;
|
|
||||||
public TrainingPage(MainViewModel model,SopPageViewModel? sop, bool embedded = false, Func<CameraInfo?>? selectedCameraProvider = null, Func<bool>? 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<string>())
|
|
||||||
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<string?> 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();
|
|
||||||
}
|
|
||||||
@ -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<ObjectAnnotation> 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<FrameAnnotation> 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<TrainingProject>(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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,78 +0,0 @@
|
|||||||
// Python 工作进程桥接:每次操作传入 JSON 请求文件,异步读取输出,取消时终止进程树并清理请求。
|
|
||||||
|
|
||||||
using System.Diagnostics;
|
|
||||||
using System.Text;
|
|
||||||
using System.Text.Json;
|
|
||||||
|
|
||||||
namespace SopHelper.Engine.Training;
|
|
||||||
|
|
||||||
/// <summary>One isolated Python process per operation; cancellation kills its entire process tree.</summary>
|
|
||||||
public sealed class WorkerClient : IDisposable
|
|
||||||
{
|
|
||||||
private readonly object _gate = new();
|
|
||||||
private readonly HashSet<Process> _processes = [];
|
|
||||||
private bool _disposed;
|
|
||||||
|
|
||||||
/// <summary>终止当前桥接器登记的全部工作进程,后续调用将被拒绝。</summary>
|
|
||||||
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) { }
|
|
||||||
}
|
|
||||||
/// <summary>通过请求文件传递结构化参数,密钥仅置于子进程环境;并发读取 stdout/stderr 避免管道阻塞。</summary>
|
|
||||||
public async Task RunAsync(string python, string worker, object request, Action<string> 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); }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -420,31 +420,6 @@ internal static class Smoke
|
|||||||
var drawing=new Window {Width=400,Height=400,Content=canvas};drawing.Show();await Task.Delay(60);
|
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);
|
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");
|
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();
|
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");
|
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);}
|
catch(Exception ex){Console.Error.WriteLine(ex);}
|
||||||
finally{lifetime.Shutdown(_exit);}
|
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<string?>(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<string?>(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<ComboBox>("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<AnnotationCanvas>().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<string?>(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<AnnotationCanvas>().Single();
|
|
||||||
var tabs=view.GetVisualDescendants().OfType<TabControl>().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;tab<tabs.ItemCount;tab++)
|
|
||||||
{
|
|
||||||
tabs.SelectedIndex=tab;await Task.Delay(60);window.UpdateLayout();
|
|
||||||
var expected=Math.Max(960,scroll.Viewport.Width);
|
|
||||||
Check(Math.Abs(layout.Bounds.Width-expected)<1,
|
|
||||||
$"Training layout stays within viewport/minimum width with long logs and status ({size}, tab {tab}); actual={layout.Bounds.Width}, expected={expected}");
|
|
||||||
Check(canvas.Bounds.Width>100&&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)
|
private static async Task CheckRecipeDeletion(IClassicDesktopStyleApplicationLifetime lifetime,Control settings,SopPageViewModel sop)
|
||||||
{
|
{
|
||||||
var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
|
var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
|
||||||
|
|||||||
@ -1,7 +0,0 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
|
||||||
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
|
|
||||||
<ItemGroup>
|
|
||||||
<ProjectReference Include="../../src/SopHelper.Avalonia/SopHelper.Avalonia.csproj" />
|
|
||||||
<PackageReference Include="Avalonia.Headless" Version="12.1.5" />
|
|
||||||
</ItemGroup>
|
|
||||||
</Project>
|
|
||||||
@ -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<Application>().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<ComboBox>().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<ComboBox>("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<TabControl>().Single();
|
|
||||||
tabs.SelectedIndex = 4; window.UpdateLayout();
|
|
||||||
Check(editor.FindControl<TextBlock>("RecipeModelPath")!.Text == modelPath && !editor.GetVisualDescendants().OfType<Button>().Any(b => b.Content?.ToString() == "选择模型…"), "Recipe model path is automatic and read-only");
|
|
||||||
var modelClasses = editor.GetVisualDescendants().OfType<ItemsControl>().Single(c => ReferenceEquals(c.ItemsSource, vm.Recipe.Model.Classes.Items));
|
|
||||||
Check(!modelClasses.GetVisualDescendants().OfType<TextBox>().Any() && !modelClasses.GetVisualDescendants().OfType<ComboBox>().Any(), "Model label mapping is read-only");
|
|
||||||
window.Close(); vm.OnDialogClosed();
|
|
||||||
|
|
||||||
var projectDirectory = Path.Combine(directory, "parts", "video"); Directory.CreateDirectory(projectDirectory);
|
|
||||||
var project = new TrainingProject { AnnotationVersion = 2, FilePath = Path.Combine(projectDirectory, "project.json"), Name = "装配视频", RecipeName = "装配", RecipeDirectory = directory, Width = 100, Height = 100, Frames = [new FrameAnnotation { Index = 0, Image = "frame.png", Objects = [new() {Label="支架", Box=[0,0,90,90]}, new() {Label="螺丝", Box=[20,20,30,30]}] }] };
|
|
||||||
project.Save();
|
|
||||||
Check(PartCatalog.ProjectNames(directory).Contains("支架") && PartCatalog.ProjectNames(directory).Contains("螺丝") && !PartCatalog.ProjectNames(directory).Contains("装配视频"), "Multi-part annotation references use object labels instead of the video title");
|
|
||||||
var trainer = new MainViewModel(new WorkerClient()); trainer.RecipeName = "装配";
|
|
||||||
Check(trainer.PartNames.SequenceEqual(saved.Sop.Parts!), "Training offers the same catalog");
|
|
||||||
trainer.Load(project.FilePath);
|
|
||||||
Check(trainer.Label == "支架", "Loading a project selects its existing catalog part");
|
|
||||||
var training = new TrainingPage(trainer, null); var trainingWindow = new Window { Content = training, Width = 1180, Height = 820 }; trainingWindow.Show(); trainingWindow.UpdateLayout();
|
|
||||||
var targetPart = training.FindControl<ComboBox>("TrainingTargetPart")!;
|
|
||||||
Check(targetPart.SelectedItem?.ToString() == "支架", "Training offers a part selector after loading a project");
|
|
||||||
targetPart.SelectedItem = "螺丝";
|
|
||||||
Check(trainer.Label == "螺丝", "Annotation part can switch within a video");
|
|
||||||
trainer.RefreshPartNames();
|
|
||||||
Check(trainer.Label == "螺丝", "Catalog refresh preserves the selected annotation part");
|
|
||||||
trainingWindow.Close();
|
|
||||||
var other = new SopConfig(); other.Sop.Name = "另一配方"; other.Sop.Parts = ["外壳"];
|
|
||||||
Directory.CreateDirectory(storage.DirectoryFor(other.Sop.Name)); SopConfigLoader.Save(other, storage.ConfigPath(other.Sop.Name));
|
|
||||||
trainer.RecipeName = other.Sop.Name;
|
|
||||||
Check(trainer.PartNames.SequenceEqual(new[] { "外壳" }) && trainer.Label == "外壳" && trainer.Project is null, "Switching recipes clears the previous project and selects an available part");
|
|
||||||
var changed = SopConfigLoader.Load(storage.ConfigPath("装配")); changed.Sop.Parts!.Remove("支架"); changed.Sop.Steps.Clear();
|
|
||||||
try { PartCatalog.Validate(changed, directory); throw new Exception("Annotation reference was ignored"); }
|
|
||||||
catch (InvalidDataException error) { Check(error.Message.Contains("支架"), "Parts referenced only by annotation projects cannot be removed"); }
|
|
||||||
var reopened = Open(storage, "装配");
|
|
||||||
Check(reopened.Recipe.Parts.Items.Select(i => i.Text).SequenceEqual(saved.Sop.Parts!), "Reopening restores the saved catalog");
|
|
||||||
var nextModel = Path.Combine(directory, "models", "v2", "装配.onnx"); Directory.CreateDirectory(Path.GetDirectoryName(nextModel)!); File.WriteAllText(nextModel, "next-version");
|
|
||||||
File.WriteAllText(Path.Combine(directory, "latest-model.json"), JsonSerializer.Serialize(new { recipeName = "装配", onnx = nextModel, weights = Path.ChangeExtension(nextModel, ".pt"), imageSize = 960, classes = new[] { "支架", "螺丝" } }));
|
|
||||||
reopened.TrainingView!.Model.Load(project.FilePath);
|
|
||||||
Check(reopened.Recipe.Model.Path == nextModel && reopened.Recipe.Model.InputSize == 960, "Editor refreshes automatically when training publishes a newer recipe model");
|
|
||||||
reopened.OnDialogClosed();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static RecipeEditorViewModel Open(RecipeWorkspace storage, string name)
|
|
||||||
{
|
|
||||||
var vm = new RecipeEditorViewModel();
|
|
||||||
vm.OnDialogOpened(new DialogParameters { { "directory", storage.RecipesDirectory }, { "path", storage.ConfigPath(name) }, { "config", SopConfigLoader.Load(storage.ConfigPath(name)) }, { "new", false } });
|
|
||||||
return vm;
|
|
||||||
}
|
|
||||||
private static void Check(bool value, string message)
|
|
||||||
{
|
|
||||||
if (!value) throw new Exception(message);
|
|
||||||
Console.WriteLine("PASS: " + message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,124 +0,0 @@
|
|||||||
using SopHelper.Engine.Training;
|
|
||||||
using SopHelper.Engine.Sop;
|
|
||||||
using System.Text.Json.Nodes;
|
|
||||||
|
|
||||||
var root = Path.Combine(Path.GetTempPath(), "parttrainer-test-" + Guid.NewGuid().ToString("N"));
|
|
||||||
Directory.CreateDirectory(root);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var project = new TrainingProject { FilePath = Path.Combine(root, "project.json"), Name = "中文零件", Width = 640, Height = 480,
|
|
||||||
Frames = [new FrameAnnotation { Image = "frames/000000.jpg", Box = [10, 20, 100, 200], Status = "reviewed", Prompt = true }] };
|
|
||||||
project.Save();
|
|
||||||
var loaded = TrainingProject.Load(project.FilePath);
|
|
||||||
if (loaded.Name != project.Name || !loaded.Frames[0].Objects[0].Prompt || loaded.Frames[0].Objects[0].Box![2] != 100 || loaded.AnnotationVersion != 2) throw new Exception("Legacy project migration failed");
|
|
||||||
foreach (var invalid in new double[][] { [-1,0,10,10], [0,0,0,10], [0,0,641,10], [double.NaN,0,1,1] })
|
|
||||||
{
|
|
||||||
try { loaded.ValidateBox(invalid); throw new Exception("Invalid box accepted"); }
|
|
||||||
catch (ArgumentException) { }
|
|
||||||
}
|
|
||||||
loaded.Frames[0].Image = "../outside.jpg"; loaded.Save();
|
|
||||||
try { TrainingProject.Load(loaded.FilePath); throw new Exception("Traversal accepted"); }
|
|
||||||
catch (InvalidDataException) { }
|
|
||||||
Console.WriteLine("PASS: project persistence, Unicode, invalid box rejection, path traversal rejection");
|
|
||||||
var storageRoot=Path.Combine(root,"layout");
|
|
||||||
var store=new RecipeWorkspace(storageRoot);
|
|
||||||
var legacyConfigs=Path.Combine(storageRoot,"configs","sop");Directory.CreateDirectory(legacyConfigs);
|
|
||||||
var legacyTraining=Path.Combine(storageRoot,"workspace","training","配方甲");
|
|
||||||
var part=Path.Combine(legacyTraining,"parts","part1");Directory.CreateDirectory(part);
|
|
||||||
var video=Path.Combine(root,"source.avi");File.WriteAllText(video,"video");
|
|
||||||
File.WriteAllText(Path.Combine(part,"frame.jpg"),"image");
|
|
||||||
var oldProject=new TrainingProject {FilePath=Path.Combine(part,"project.json"),RecipeName="配方甲",RecipeDirectory=legacyTraining,Name="零件甲",Video=video,Width=100,Height=100,
|
|
||||||
Frames=[new FrameAnnotation {Image="frame.jpg",Box=[0,0,30,30],Status="reviewed"}]};oldProject.Save();
|
|
||||||
var externalPart=Path.Combine(root,"external-part");Directory.CreateDirectory(externalPart);
|
|
||||||
File.WriteAllText(Path.Combine(externalPart,"frame.jpg"),"image");
|
|
||||||
var externalProject=new TrainingProject {FilePath=Path.Combine(externalPart,"project.json"),Name="零件乙",Video=video,Width=100,Height=100,
|
|
||||||
Frames=[new FrameAnnotation {Image="frame.jpg",Box=[0,0,30,30],Status="reviewed"}]};externalProject.Save();
|
|
||||||
var externalRun=Path.Combine(root,"external-run");Directory.CreateDirectory(externalRun);
|
|
||||||
var weights=Path.Combine(externalRun,"配方甲.pt");File.WriteAllText(weights,"weights");
|
|
||||||
var onnx=Path.ChangeExtension(weights,".onnx");File.WriteAllText(onnx,"model");
|
|
||||||
File.WriteAllText(Path.Combine(legacyTraining,"latest-model.json"),System.Text.Json.JsonSerializer.Serialize(new {weights,onnx,runDirectory=externalRun,recipeName="配方甲",classes=new[]{"零件甲"},imageSize=640}));
|
|
||||||
File.WriteAllText(Path.Combine(legacyTraining,"recipe-training.json"),new JsonObject { ["projects"]=new JsonArray(oldProject.FilePath,externalProject.FilePath),["labels"]=new JsonObject{[oldProject.FilePath]="零件甲",[externalProject.FilePath]="零件乙"},["classes"]=new JsonArray("零件甲","零件乙")}.ToJsonString());
|
|
||||||
var config=new SopConfig();config.Sop.Name="配方甲";config.Sop.Model=new ModelDef{Path=onnx};
|
|
||||||
SopConfigLoader.Save(config,Path.Combine(legacyConfigs,"配方甲.yaml"));
|
|
||||||
store.Initialize(legacyConfigs);
|
|
||||||
var recipe=store.DirectoryFor("配方甲");
|
|
||||||
var migratedProject=TrainingProject.Load(Path.Combine(recipe,"parts","part1","project.json"));
|
|
||||||
if(migratedProject.RecipeDirectory!=recipe||!RecipeWorkspace.IsWithin(migratedProject.Video,recipe)||!File.Exists(migratedProject.Video))throw new Exception("Project/video migration failed");
|
|
||||||
var latest=JsonNode.Parse(File.ReadAllText(Path.Combine(recipe,"latest-model.json")))!;
|
|
||||||
if(!RecipeWorkspace.IsWithin(latest["weights"]!.GetValue<string>(),recipe)||!File.Exists(latest["onnx"]!.GetValue<string>()))throw new Exception("External training output was not migrated");
|
|
||||||
var registry=JsonNode.Parse(File.ReadAllText(Path.Combine(recipe,"recipe-training.json")))!;
|
|
||||||
if(registry["projects"]![0]!.GetValue<string>()!=migratedProject.FilePath||registry["labels"]![migratedProject.FilePath]!.GetValue<string>()!="零件甲")throw new Exception("Registry references were not rebased");
|
|
||||||
var relocatedExternal=registry["projects"]![1]!.GetValue<string>();
|
|
||||||
if(!RecipeWorkspace.IsWithin(relocatedExternal,recipe)||TrainingProject.Load(relocatedExternal).RecipeDirectory!=recipe)throw new Exception("External annotation projects were not migrated");
|
|
||||||
var managedModel=SopConfigLoader.Load(store.ConfigPath("配方甲")).Sop.Model!.Path;
|
|
||||||
if(Path.IsPathRooted(managedModel)||!File.Exists(Path.Combine(recipe,managedModel)))throw new Exception("Configured model was not localized");
|
|
||||||
File.WriteAllText(Path.Combine(legacyConfigs,"配方甲.yaml"),"obsolete");store.Initialize(legacyConfigs);
|
|
||||||
if(SopConfigLoader.Load(store.ConfigPath("配方甲")).Sop.Name!="配方甲")throw new Exception("Migration overwrote managed settings");
|
|
||||||
if(!File.Exists(oldProject.FilePath)||!File.Exists(video))throw new Exception("Migration modified original data");
|
|
||||||
foreach(var bad in new[]{"..","../escape","a/b","a\\b","配方:甲","配方*甲","配方?","配方\"","配方<","配方>","配方|","末尾 ","末尾.","CON","nul.txt","COM1","LPT9","COM¹","换\n行",new string('长',100)})
|
|
||||||
try{store.DirectoryFor(bad);throw new Exception("Unsafe recipe name accepted");}catch(ArgumentException){}
|
|
||||||
foreach(var good in new[]{"装配线A","配方.v1","配方 甲","COM10","普通配方(测试)"})
|
|
||||||
if(RecipeWorkspace.GetNameError(good) is not null)throw new Exception("Valid recipe name rejected: "+good);
|
|
||||||
var renamedDisplay=SopConfigLoader.Load(store.ConfigPath("配方甲"));renamedDisplay.Sop.Name="另一个显示名称";
|
|
||||||
SopConfigLoader.Save(renamedDisplay,store.ConfigPath("配方甲"));store.Initialize(legacyConfigs);
|
|
||||||
if(SopConfigLoader.Load(store.ConfigPath("配方甲")).Sop.Name!="配方甲")throw new Exception("Existing recipe name differs from filename");
|
|
||||||
Console.WriteLine("PASS: Unified recipe migration, model/video copies, registry rebasing, independent config and safe names");
|
|
||||||
var portable=new RecipeWorkspace(Path.Combine(root,"portable"));portable.ImportFrom(storageRoot);
|
|
||||||
var portableRoot=portable.DirectoryFor("配方甲");
|
|
||||||
var portableRegistry=JsonNode.Parse(File.ReadAllText(Path.Combine(portableRoot,"recipe-training.json")))!;
|
|
||||||
var portableProject=TrainingProject.Load(portableRegistry["projects"]![0]!.GetValue<string>());
|
|
||||||
if(!RecipeWorkspace.IsWithin(portableProject.Video,portableRoot)||portableProject.RecipeDirectory!=portableRoot)throw new Exception("Portable recipe references source data");
|
|
||||||
var portableModel=JsonNode.Parse(File.ReadAllText(Path.Combine(portableRoot,"latest-model.json")))!;
|
|
||||||
if(!RecipeWorkspace.IsWithin(portableModel["weights"]!.GetValue<string>(),portableRoot))throw new Exception("Portable model references source data");
|
|
||||||
var portableConfig=SopConfigLoader.Load(portable.ConfigPath("配方甲"));portableConfig.Sop.Version="local-version";SopConfigLoader.Save(portableConfig,portable.ConfigPath("配方甲"));
|
|
||||||
portable.ImportFrom(storageRoot);
|
|
||||||
if(SopConfigLoader.Load(portable.ConfigPath("配方甲")).Sop.Version!="local-version")throw new Exception("Source recipe overwrote a runtime recipe");
|
|
||||||
Console.WriteLine("PASS: Runtime-directory migration rebases assets and preserves existing runtime recipes");
|
|
||||||
var relocated=new RecipeWorkspace(Path.Combine(root,"relocated"));
|
|
||||||
foreach(var file in Directory.GetFiles(store.RecipesDirectory,"*",SearchOption.AllDirectories))
|
|
||||||
{
|
|
||||||
var target=Path.Combine(relocated.RecipesDirectory,Path.GetRelativePath(store.RecipesDirectory,file));
|
|
||||||
Directory.CreateDirectory(Path.GetDirectoryName(target)!);File.Copy(file,target);
|
|
||||||
}
|
|
||||||
relocated.Initialize();
|
|
||||||
var relocatedRegistry=JsonNode.Parse(File.ReadAllText(Path.Combine(relocated.DirectoryFor("配方甲"),"recipe-training.json")))!;
|
|
||||||
var movedProject=TrainingProject.Load(relocatedRegistry["projects"]![0]!.GetValue<string>());
|
|
||||||
if(!RecipeWorkspace.IsWithin(movedProject.Video,relocated.RecipesDirectory)||!File.Exists(movedProject.Video))throw new Exception("Moving a complete runtime directory left stale source references");
|
|
||||||
Console.WriteLine("PASS: Moving the entire runtime directory automatically rebases recipe paths");
|
|
||||||
var archive=store.Delete("配方甲");
|
|
||||||
if(Directory.Exists(store.DirectoryFor("配方甲"))||!File.Exists(Path.Combine(archive,"配方甲.yaml"))||!Directory.Exists(Path.Combine(archive,"parts")))
|
|
||||||
throw new Exception("Recipe deletion failed to preserve its complete directory");
|
|
||||||
store.Initialize(legacyConfigs);store.ImportFrom(portable.Root);
|
|
||||||
if(File.Exists(store.ConfigPath("配方甲")))throw new Exception("Deleted recipe was automatically reimported");
|
|
||||||
if(!File.Exists(oldProject.FilePath)||!File.Exists(video))throw new Exception("Deletion modified legacy/source data");
|
|
||||||
Directory.CreateDirectory(store.DirectoryFor("配方甲"));SopConfigLoader.Save(new SopConfig{Sop=new SopBody{Name="配方甲"}},store.ConfigPath("配方甲"));
|
|
||||||
if(!store.Names().Contains("配方甲"))throw new Exception("Deleted name could not be reused for a new recipe");
|
|
||||||
store.Delete("配方甲");
|
|
||||||
if(Directory.GetDirectories(Path.Combine(store.DeletedRecipesDirectory,"配方甲")).Length!=2)throw new Exception("Second deletion overwrote the first archive");
|
|
||||||
try{store.Delete("../escape");throw new Exception("Delete accepted traversal");}catch(ArgumentException){}
|
|
||||||
Console.WriteLine("PASS: Recipe deletion archives all data, blocks automatic reimport, allows name reuse and rejects unsafe paths");
|
|
||||||
if (args.Length > 0)
|
|
||||||
{
|
|
||||||
var script = Path.Combine(root, "worker.py");
|
|
||||||
File.WriteAllText(script, "import json,sys,time\nr=json.load(open(sys.argv[1]))\nprint('worker-ready',flush=True)\ntime.sleep(r.get('sleep',0))\nsys.exit(r.get('exit',0))\n");
|
|
||||||
var client = new WorkerClient();
|
|
||||||
var lines = new List<string>();
|
|
||||||
await client.RunAsync(args[0], script, new { sleep = 0 }, line => { lock(lines) lines.Add(line); }, CancellationToken.None);
|
|
||||||
if (!lines.Contains("worker-ready")) throw new Exception("Worker output was lost");
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await client.RunAsync(args[0], script, new { exit = 2 }, _ => { }, CancellationToken.None);
|
|
||||||
throw new Exception("Worker exit failure was ignored");
|
|
||||||
}
|
|
||||||
catch (InvalidOperationException) { }
|
|
||||||
using var cancel = new CancellationTokenSource(TimeSpan.FromSeconds(1));
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await client.RunAsync(args[0], script, new { sleep = 60 }, _ => { }, cancel.Token);
|
|
||||||
throw new Exception("Worker cancellation was ignored");
|
|
||||||
}
|
|
||||||
catch (OperationCanceledException) { }
|
|
||||||
Console.WriteLine("PASS: real Python process output, exit failure, cancellation");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
finally { Directory.Delete(root, true); }
|
|
||||||
@ -1 +0,0 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup><ItemGroup><ProjectReference Include="../../src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj"/></ItemGroup></Project>
|
|
||||||
@ -1,58 +0,0 @@
|
|||||||
"""Verify real CUDA kernels and SAM2 propagation without touching user annotations."""
|
|
||||||
import argparse
|
|
||||||
import importlib.util
|
|
||||||
import json
|
|
||||||
from pathlib import Path
|
|
||||||
import tempfile
|
|
||||||
import time
|
|
||||||
|
|
||||||
import cv2
|
|
||||||
import numpy as np
|
|
||||||
import torch
|
|
||||||
from torchvision.ops import nms
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
parser = argparse.ArgumentParser(description=__doc__)
|
|
||||||
parser.add_argument("--runtime-root", type=Path, default=Path(__file__).resolve().parents[2])
|
|
||||||
runtime_root = parser.parse_args().runtime_root.resolve()
|
|
||||||
assert torch.cuda.is_available(), "CUDA is unavailable in this Python runtime"
|
|
||||||
boxes = torch.tensor([[0, 0, 20, 20], [1, 1, 19, 19]], dtype=torch.float32, device="cuda")
|
|
||||||
scores = torch.tensor([0.9, 0.8], device="cuda")
|
|
||||||
assert nms(boxes, scores, 0.5).tolist() == [0], "TorchVision CUDA NMS failed"
|
|
||||||
del boxes, scores
|
|
||||||
torch.cuda.empty_cache()
|
|
||||||
torch.cuda.reset_peak_memory_stats()
|
|
||||||
spec = importlib.util.spec_from_file_location("worker", runtime_root / "tools" / "worker.py")
|
|
||||||
worker = importlib.util.module_from_spec(spec)
|
|
||||||
spec.loader.exec_module(worker)
|
|
||||||
messages = []
|
|
||||||
worker.emit = lambda message, **kwargs: messages.append(message)
|
|
||||||
started = time.perf_counter()
|
|
||||||
with tempfile.TemporaryDirectory(prefix="sam2-gpu-check-") as temporary:
|
|
||||||
root = Path(temporary)
|
|
||||||
frames = root / "frames"
|
|
||||||
frames.mkdir()
|
|
||||||
for index in range(3):
|
|
||||||
image = np.full((192, 256, 3), 210, dtype=np.uint8)
|
|
||||||
cv2.rectangle(image, (70 + index * 2, 50), (150 + index * 2, 130), (40, 60, 200), -1)
|
|
||||||
assert cv2.imwrite(str(frames / f"{index:06d}.jpg"), image)
|
|
||||||
project = root / "project.json"
|
|
||||||
worker.save_json(project, {"name": "GPU测试零件", "width": 256, "height": 192,
|
|
||||||
"frames": [{"index": i, "image": f"frames/{i:06d}.jpg", "status": "reviewed" if i == 0 else "unlabeled",
|
|
||||||
"prompt": i == 0, "box": [70, 50, 151, 131] if i == 0 else None} for i in range(3)]})
|
|
||||||
worker.propagate({"project": str(project), "device": "auto"})
|
|
||||||
torch.cuda.synchronize()
|
|
||||||
result = worker.read_json(project)
|
|
||||||
assert result["frames"][0]["status"] == "reviewed"
|
|
||||||
assert all(f["status"] == "auto" for f in result["frames"][1:])
|
|
||||||
assert any("cuda" in message for message in messages), "SAM2 did not select CUDA"
|
|
||||||
assert torch.cuda.max_memory_allocated() > 50_000_000, "SAM2 did not allocate model memory on GPU"
|
|
||||||
print(json.dumps({"passed": True, "torch": torch.__version__, "cuda": torch.version.cuda,
|
|
||||||
"gpu": torch.cuda.get_device_name(0), "auto_frames": 2,
|
|
||||||
"peak_gpu_mb": round(torch.cuda.max_memory_allocated() / 1024 ** 2, 1),
|
|
||||||
"seconds": round(time.perf_counter() - started, 2)}, ensure_ascii=True))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@ -1,226 +0,0 @@
|
|||||||
"""Recipe training regression: real dataset export, simulated training lifecycle."""
|
|
||||||
import importlib.util
|
|
||||||
import json
|
|
||||||
from pathlib import Path
|
|
||||||
import sys
|
|
||||||
import tempfile
|
|
||||||
from types import SimpleNamespace
|
|
||||||
import unittest
|
|
||||||
from unittest.mock import patch
|
|
||||||
|
|
||||||
spec = importlib.util.spec_from_file_location("worker", Path(__file__).parents[2] / "tools" / "worker.py")
|
|
||||||
worker = importlib.util.module_from_spec(spec)
|
|
||||||
spec.loader.exec_module(worker)
|
|
||||||
|
|
||||||
|
|
||||||
class RecipeTrainingTests(unittest.TestCase):
|
|
||||||
def test_unqualified_old_projects_removed_but_current_still_validated(self):
|
|
||||||
for defect in ("unreviewed", "no_validation", "missing_box", "missing_image"):
|
|
||||||
with self.subTest(defect=defect), tempfile.TemporaryDirectory() as temporary:
|
|
||||||
root = Path(temporary).resolve()
|
|
||||||
paths = [root / name / "project.json" for name in ("old", "valid", "current")]
|
|
||||||
for path in paths:
|
|
||||||
path.parent.mkdir()
|
|
||||||
(path.parent / "frame.jpg").write_bytes(b"test-image")
|
|
||||||
worker.save_json(path, {"name": path.parent.name, "recipeDirectory": str(root),
|
|
||||||
"width": 100, "height": 100, "frames": [
|
|
||||||
{"index": i, "image": "frame.jpg", "status": "reviewed", "box": [10, 10, 50, 50]}
|
|
||||||
for i in range(30)]})
|
|
||||||
worker.recipe_context({"project": str(path)})
|
|
||||||
old, valid, current = paths
|
|
||||||
data = worker.read_json(old)
|
|
||||||
if defect == "missing_image":
|
|
||||||
(old.parent / "frame.jpg").unlink()
|
|
||||||
elif defect == "missing_box":
|
|
||||||
data["frames"][0]["box"] = None
|
|
||||||
else:
|
|
||||||
for frame in data["frames"][1 if defect == "unreviewed" else 24:]:
|
|
||||||
frame["status"] = "auto"
|
|
||||||
worker.save_json(old, data)
|
|
||||||
before = old.read_bytes()
|
|
||||||
request = {"project": str(current), "every": 1}
|
|
||||||
with patch.object(worker, "emit"):
|
|
||||||
dataset = worker.export_dataset(request).parent
|
|
||||||
state = worker.read_json(root / "recipe-training.json")
|
|
||||||
self.assertEqual(state["projects"], [str(valid), str(current)])
|
|
||||||
self.assertNotIn(str(old), state["labels"])
|
|
||||||
self.assertEqual(state["classes"], ["old", "valid", "current"])
|
|
||||||
manifest = worker.read_json(dataset / "manifest.json")
|
|
||||||
self.assertEqual([p["project"] for p in manifest["projects"]], [str(valid), str(current)])
|
|
||||||
self.assertEqual([p["classId"] for p in manifest["projects"]], [1, 2])
|
|
||||||
self.assertEqual(old.read_bytes(), before)
|
|
||||||
# Removal persists across exports; opening it explicitly restores validation.
|
|
||||||
worker.export_dataset(request)
|
|
||||||
with self.assertRaises(ValueError):
|
|
||||||
worker.export_dataset({"project": str(old), "every": 1})
|
|
||||||
self.assertIn(str(old), worker.read_json(root / "recipe-training.json")["projects"])
|
|
||||||
|
|
||||||
def test_managed_catalog_is_authoritative(self):
|
|
||||||
with tempfile.TemporaryDirectory() as temporary:
|
|
||||||
root = Path(temporary).resolve()
|
|
||||||
current = root / "parts" / "current" / "project.json"
|
|
||||||
current.parent.mkdir(parents=True)
|
|
||||||
(current.parent / "frame.jpg").write_bytes(b"test-image")
|
|
||||||
data = {"name": "螺丝", "recipeName": root.name, "recipeDirectory": str(root),
|
|
||||||
"width": 100, "height": 100, "frames": [
|
|
||||||
{"index": i, "image": "frame.jpg", "status": "reviewed", "box": [10, 10, 50, 50]}
|
|
||||||
for i in range(30)]}
|
|
||||||
worker.save_json(current, data)
|
|
||||||
config = root / (root.name + ".yaml")
|
|
||||||
config.write_text('sop:\n parts: [支架, 螺丝]\n', encoding="utf-8")
|
|
||||||
worker.save_json(root / "recipe-training.json", {"projects": [str(current)], "classes": ["螺丝", "旧名称"]})
|
|
||||||
_, _, classes = worker.recipe_context({"project": str(current)})
|
|
||||||
self.assertEqual(classes, ["支架", "螺丝"])
|
|
||||||
dataset = worker.export_dataset({"project": str(current), "every": 1}).parent
|
|
||||||
self.assertEqual(worker.read_json(dataset / "manifest.json")["classes"], ["支架", "螺丝"])
|
|
||||||
self.assertEqual({p.read_text().split()[0] for p in (dataset / "labels" / "train").glob("*.txt")}, {"1"})
|
|
||||||
before = (root / "recipe-training.json").read_bytes()
|
|
||||||
worker.save_json(current, {**data, "name": "随意输入"})
|
|
||||||
with self.assertRaisesRegex(ValueError, "不在配方零件列表"):
|
|
||||||
worker.recipe_context({"project": str(current)})
|
|
||||||
self.assertEqual((root / "recipe-training.json").read_bytes(), before)
|
|
||||||
worker.save_json(current, data)
|
|
||||||
config.write_text('sop:\n parts: [螺丝, 螺丝]\n', encoding="utf-8")
|
|
||||||
with self.assertRaisesRegex(ValueError, "零件列表无效"):
|
|
||||||
worker.recipe_context({"project": str(current)})
|
|
||||||
config.write_text('sop:\n parts: []\n', encoding="utf-8")
|
|
||||||
with self.assertRaisesRegex(ValueError, "不在配方零件列表"):
|
|
||||||
worker.recipe_context({"project": str(current)})
|
|
||||||
|
|
||||||
def test_missing_project_removed_and_restored(self):
|
|
||||||
with tempfile.TemporaryDirectory() as temporary:
|
|
||||||
root = Path(temporary).resolve()
|
|
||||||
current = root / "parts" / "current" / "project.json"
|
|
||||||
missing = root / "parts" / "missing" / "project.json"
|
|
||||||
current.parent.mkdir(parents=True)
|
|
||||||
data = {"name": "已训练", "recipeDirectory": str(root), "width": 100, "height": 100,
|
|
||||||
"frames": [{"index": 0, "image": "frame.jpg"}]}
|
|
||||||
worker.save_json(current, data)
|
|
||||||
registry = root / "recipe-training.json"
|
|
||||||
state = {"projects": [str(current), str(missing)], "classes": ["已训练", "未训练"],
|
|
||||||
"labels": {str(current): "已训练", str(missing): "未训练"}}
|
|
||||||
worker.save_json(registry, state)
|
|
||||||
with patch.object(worker, "emit") as emit:
|
|
||||||
_, projects, classes = worker.recipe_context({"project": str(current)})
|
|
||||||
self.assertEqual([p for p, _ in projects], [current])
|
|
||||||
self.assertEqual(classes, state["classes"])
|
|
||||||
self.assertEqual(worker.read_json(registry)["missingProjects"], [str(missing)])
|
|
||||||
self.assertEqual(worker.read_json(registry)["projects"], [str(current)])
|
|
||||||
self.assertNotIn(str(missing), worker.read_json(registry)["labels"])
|
|
||||||
self.assertIn("自动从训练名单移除", emit.call_args.args[0])
|
|
||||||
# Persisted retirement allows subsequent exports without renumbering.
|
|
||||||
worker.recipe_context({"project": str(current)})
|
|
||||||
missing.parent.mkdir(parents=True)
|
|
||||||
worker.save_json(missing, {**data, "name": "未训练"})
|
|
||||||
_, projects, classes = worker.recipe_context({"project": str(missing)})
|
|
||||||
self.assertEqual(len(projects), 2)
|
|
||||||
self.assertEqual(classes, state["classes"])
|
|
||||||
self.assertEqual(worker.read_json(registry)["missingProjects"], [])
|
|
||||||
|
|
||||||
def test_incremental_recipe(self):
|
|
||||||
with tempfile.TemporaryDirectory() as temporary:
|
|
||||||
root = Path(temporary) / "装配配方"
|
|
||||||
def part(name, folder):
|
|
||||||
directory = root / "parts" / folder
|
|
||||||
directory.mkdir(parents=True)
|
|
||||||
(directory / "frame.jpg").write_bytes(b"test-image")
|
|
||||||
path = directory / "project.json"
|
|
||||||
worker.save_json(path, {"name": name, "recipeName": root.name, "recipeDirectory": str(root),
|
|
||||||
"width": 100, "height": 100, "frames": [
|
|
||||||
{"index": i, "image": "frame.jpg", "status": "reviewed", "box": [10, 10, 50, 50]}
|
|
||||||
for i in range(30)]})
|
|
||||||
worker.recipe_context({"project": str(path)})
|
|
||||||
return path
|
|
||||||
first = part("零件1", "first")
|
|
||||||
loaded = []
|
|
||||||
options = []
|
|
||||||
exports = []
|
|
||||||
class FakeYolo:
|
|
||||||
task = "detect"
|
|
||||||
fail = False
|
|
||||||
fail_export = False
|
|
||||||
def __init__(self, weights):
|
|
||||||
loaded.append(str(weights))
|
|
||||||
self.weights = Path(weights)
|
|
||||||
def add_callback(self, *args):
|
|
||||||
pass
|
|
||||||
def train(self, **kwargs):
|
|
||||||
options.append(kwargs)
|
|
||||||
if self.fail:
|
|
||||||
raise RuntimeError("simulated failure")
|
|
||||||
directory = Path(kwargs["project"]) / kwargs["name"]
|
|
||||||
directory.mkdir(parents=True)
|
|
||||||
best = directory / "best.pt"
|
|
||||||
best.write_bytes(b"checkpoint")
|
|
||||||
self.trainer = SimpleNamespace(best=best, save_dir=directory, metrics={"mAP": 0.9})
|
|
||||||
def export(self, **kwargs):
|
|
||||||
exports.append(kwargs)
|
|
||||||
if self.fail_export:
|
|
||||||
raise RuntimeError("simulated export failure")
|
|
||||||
output = self.weights.with_suffix(".onnx")
|
|
||||||
output.write_bytes(b"onnx-model")
|
|
||||||
return str(output)
|
|
||||||
request = {"project": str(first), "every": 1, "epochs": 1, "imageSize": 32}
|
|
||||||
with patch.dict(sys.modules, {"ultralytics": SimpleNamespace(YOLO=FakeYolo),
|
|
||||||
"torch": SimpleNamespace(cuda=SimpleNamespace(is_available=lambda: False))}):
|
|
||||||
worker.train(request)
|
|
||||||
previous = worker.read_json(root / "latest-model.json")
|
|
||||||
self.assertEqual(Path(previous["weights"]).name, "装配配方.pt")
|
|
||||||
self.assertEqual(Path(previous["onnx"]).name, "装配配方.onnx")
|
|
||||||
self.assertTrue(Path(previous["onnx"]).is_file())
|
|
||||||
second = part("零件2", "second")
|
|
||||||
request["project"] = str(second)
|
|
||||||
worker.train(request)
|
|
||||||
latest = worker.read_json(root / "latest-model.json")
|
|
||||||
self.assertEqual(loaded, ["yolo11n.pt", previous["weights"], previous["weights"], latest["weights"]])
|
|
||||||
self.assertEqual(exports[-1], {"format": "onnx", "imgsz": 32, "opset": 17,
|
|
||||||
"dynamic": False, "simplify": False, "nms": False})
|
|
||||||
self.assertNotEqual(previous["onnx"], latest["onnx"])
|
|
||||||
self.assertTrue(Path(previous["onnx"]).is_file())
|
|
||||||
self.assertEqual(worker.read_json(Path(latest["runDirectory"]) / "training-result.json"), latest)
|
|
||||||
self.assertFalse(options[-1]["resume"])
|
|
||||||
self.assertEqual(latest["classes"], ["零件1", "零件2"])
|
|
||||||
dataset = Path(latest["dataset"]).parent
|
|
||||||
self.assertEqual(len(list((dataset / "images" / "train").glob("*.jpg"))), 46)
|
|
||||||
self.assertEqual({p.read_text().split()[0] for p in (dataset / "labels" / "train").glob("*.txt")}, {"0", "1"})
|
|
||||||
self.assertTrue(Path(previous["weights"]).is_file())
|
|
||||||
# Reopening an older video retains all classes and their identifiers.
|
|
||||||
worker.export_dataset({**request, "project": str(first)})
|
|
||||||
self.assertEqual(worker.read_json(root / "recipe-training.json")["classes"], ["零件1", "零件2"])
|
|
||||||
worker.export_onnx({**request, "imageSize": 640})
|
|
||||||
self.assertEqual(exports[-1]["imgsz"], 32)
|
|
||||||
self.assertEqual(worker.read_json(root / "latest-model.json"), latest)
|
|
||||||
# A different recipe publishes into its own directory and starts independently.
|
|
||||||
other = Path(temporary) / "另一配方"
|
|
||||||
other.mkdir()
|
|
||||||
(other / "frame.jpg").write_bytes(b"test-image")
|
|
||||||
other_project = other / "project.json"
|
|
||||||
worker.save_json(other_project, {**worker.read_json(second), "recipeName": other.name,
|
|
||||||
"recipeDirectory": str(other)})
|
|
||||||
worker.train({**request, "project": str(other_project)})
|
|
||||||
other_latest = worker.read_json(other / "latest-model.json")
|
|
||||||
self.assertEqual(loaded[-2], "yolo11n.pt")
|
|
||||||
self.assertEqual(Path(other_latest["onnx"]).name, "另一配方.onnx")
|
|
||||||
self.assertEqual(worker.read_json(root / "latest-model.json"), latest)
|
|
||||||
FakeYolo.fail_export = True
|
|
||||||
with self.assertRaisesRegex(RuntimeError, "ONNX 导出失败"):
|
|
||||||
worker.train(request)
|
|
||||||
self.assertEqual(worker.read_json(root / "latest-model.json"), latest)
|
|
||||||
self.assertTrue(Path(latest["onnx"]).is_file())
|
|
||||||
FakeYolo.fail_export = False
|
|
||||||
FakeYolo.fail = True
|
|
||||||
with self.assertRaisesRegex(RuntimeError, "simulated failure"):
|
|
||||||
worker.train(request)
|
|
||||||
self.assertEqual(worker.read_json(root / "latest-model.json"), latest)
|
|
||||||
# Missing old data is removed automatically, even for trained classes.
|
|
||||||
first.unlink()
|
|
||||||
yaml = worker.export_dataset(request)
|
|
||||||
manifest = worker.read_json(yaml.parent / "manifest.json")
|
|
||||||
self.assertEqual([p["project"] for p in manifest["projects"]], [str(second.resolve())])
|
|
||||||
self.assertEqual(manifest["classes"], ["零件1", "零件2"])
|
|
||||||
self.assertEqual(worker.read_json(root / "recipe-training.json")["projects"], [str(second.resolve())])
|
|
||||||
self.assertEqual(worker.read_json(root / "latest-model.json"), latest)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@ -1,79 +0,0 @@
|
|||||||
"""Exercise the real annotation worker, with optional SAM2 propagation, in a temporary project."""
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
from pathlib import Path
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
import tempfile
|
|
||||||
|
|
||||||
import cv2
|
|
||||||
import numpy as np
|
|
||||||
|
|
||||||
parser = argparse.ArgumentParser()
|
|
||||||
parser.add_argument("worker", type=Path)
|
|
||||||
parser.add_argument("--sam2", action="store_true")
|
|
||||||
options = parser.parse_args()
|
|
||||||
worker = options.worker.resolve()
|
|
||||||
|
|
||||||
with tempfile.TemporaryDirectory(prefix="sophelper-worker-") as directory:
|
|
||||||
root = Path(directory)
|
|
||||||
|
|
||||||
def run(request):
|
|
||||||
request_file = root / "request.json"
|
|
||||||
request_file.write_text(json.dumps(request, ensure_ascii=False), encoding="utf-8")
|
|
||||||
process = subprocess.run([sys.executable, "-u", str(worker), str(request_file)],
|
|
||||||
capture_output=True, text=True, encoding="utf-8", timeout=240,
|
|
||||||
env=dict(os.environ, PYTHONUTF8="1"))
|
|
||||||
if process.returncode:
|
|
||||||
raise RuntimeError(process.stdout + process.stderr)
|
|
||||||
events = []
|
|
||||||
for line in process.stdout.splitlines():
|
|
||||||
try:
|
|
||||||
events.append(json.loads(line))
|
|
||||||
except json.JSONDecodeError:
|
|
||||||
pass
|
|
||||||
return events
|
|
||||||
|
|
||||||
events = run({"action": "doctor"})
|
|
||||||
modules = next(event["modules"] for event in events if "modules" in event)
|
|
||||||
required = ["cv2", "numpy", "torch", "ultralytics", "onnx"] + (["sam2"] if options.sam2 else [])
|
|
||||||
assert all(modules[name] for name in required), modules
|
|
||||||
print("PASS: annotation worker dependency check", flush=True)
|
|
||||||
|
|
||||||
video = root / "input.avi"
|
|
||||||
writer = cv2.VideoWriter(str(video), cv2.VideoWriter_fourcc(*"MJPG"), 10, (320, 240))
|
|
||||||
assert writer.isOpened(), "MJPEG encoder unavailable"
|
|
||||||
for index in range(6):
|
|
||||||
image = np.full((240, 320, 3), 25, dtype=np.uint8)
|
|
||||||
cv2.rectangle(image, (40 + index * 3, 60), (120 + index * 3, 140), (30, 200, 40), -1)
|
|
||||||
writer.write(image)
|
|
||||||
writer.release()
|
|
||||||
|
|
||||||
project = root / "标注 测试项目"
|
|
||||||
run({"action": "extract", "video": str(video), "output": str(project), "name": "测试零件", "maxFrames": 6})
|
|
||||||
project_file = project / "project.json"
|
|
||||||
data = json.loads(project_file.read_text(encoding="utf-8"))
|
|
||||||
assert len(data["frames"]) == 6 and data["width"] == 320 and data["height"] == 240
|
|
||||||
assert all((project / frame["image"]).is_file() for frame in data["frames"])
|
|
||||||
print("PASS: actual video import, frame extraction, Unicode and space paths", flush=True)
|
|
||||||
|
|
||||||
data["frames"][0].update(objects=[{"label":"测试零件", "box":[40,60,120,140], "status":"reviewed", "prompt":True}], status="reviewed")
|
|
||||||
project_file.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
|
||||||
if options.sam2:
|
|
||||||
run({"action": "propagate", "project": str(project_file), "label":"测试零件", "device": "cpu"})
|
|
||||||
data = json.loads(project_file.read_text(encoding="utf-8"))
|
|
||||||
assert data["frames"][0]["status"] == "reviewed" and data["frames"][0]["objects"][0]["prompt"]
|
|
||||||
assert all(frame["status"] == "auto" for frame in data["frames"][1:])
|
|
||||||
assert any(o.get("box") for frame in data["frames"][1:] for o in frame["objects"]), "SAM2 produced no tracked boxes"
|
|
||||||
print("PASS: SAM2 model load and propagation preserve the reviewed seed", flush=True)
|
|
||||||
|
|
||||||
for index, frame in enumerate(data["frames"]):
|
|
||||||
frame.update(objects=[{"label":"测试零件", "box":[40+index*3,60,120+index*3,140], "status":"reviewed", "prompt":index==0}], status="reviewed")
|
|
||||||
project_file.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
|
||||||
events = run({"action": "export", "project": str(project_file), "every": 1})
|
|
||||||
output = Path(next(event["output"] for event in events if "output" in event))
|
|
||||||
assert (output / "data.yaml").is_file()
|
|
||||||
assert len(list((output / "labels" / "train").glob("*.txt"))) >= 2
|
|
||||||
assert list((output / "labels" / "val").glob("*.txt"))
|
|
||||||
print("PASS: reviewed annotations export into training and validation data", flush=True)
|
|
||||||
@ -1,173 +0,0 @@
|
|||||||
import importlib.util
|
|
||||||
import json
|
|
||||||
from pathlib import Path
|
|
||||||
import tempfile
|
|
||||||
import io
|
|
||||||
import unittest
|
|
||||||
from unittest.mock import patch
|
|
||||||
|
|
||||||
spec = importlib.util.spec_from_file_location("worker", Path(__file__).parents[1] / "tools" / "worker.py")
|
|
||||||
worker = importlib.util.module_from_spec(spec)
|
|
||||||
spec.loader.exec_module(worker)
|
|
||||||
|
|
||||||
|
|
||||||
class DatasetTests(unittest.TestCase):
|
|
||||||
def setUp(self):
|
|
||||||
self.temp = tempfile.TemporaryDirectory(prefix="零件-")
|
|
||||||
self.root = Path(self.temp.name)
|
|
||||||
(self.root / "frames").mkdir()
|
|
||||||
self.project = self.root / "project.json"
|
|
||||||
self.data = {"name": "零件: A #1", "width": 100, "height": 80, "frames": []}
|
|
||||||
for index in range(60):
|
|
||||||
image = f"frames/{index:06d}.jpg"
|
|
||||||
(self.root / image).write_bytes(b"test-image")
|
|
||||||
self.data["frames"].append({"index": index, "image": image, "box": [10, 20, 50, 60], "status": "reviewed", "prompt": False})
|
|
||||||
|
|
||||||
def tearDown(self):
|
|
||||||
self.temp.cleanup()
|
|
||||||
|
|
||||||
def save(self):
|
|
||||||
worker.save_json(self.project, self.data)
|
|
||||||
|
|
||||||
def test_only_reviewed_frames_and_normalized_coordinates(self):
|
|
||||||
self.data["frames"][0]["status"] = "auto"
|
|
||||||
self.data["frames"][5]["status"] = "excluded"
|
|
||||||
self.data["frames"][10].update(status="absent", box=None)
|
|
||||||
self.save()
|
|
||||||
yaml = worker.export_dataset({"project": str(self.project), "every": 5})
|
|
||||||
manifest = worker.read_json(yaml.parent / "manifest.json")
|
|
||||||
samples = manifest["projects"][0]
|
|
||||||
self.assertNotIn(0, samples["train"])
|
|
||||||
self.assertNotIn(5, samples["train"])
|
|
||||||
self.assertGreater(min(samples["val"]) - max(samples["train"]), 5)
|
|
||||||
self.assertEqual((yaml.parent / "labels/train/0000_000010.txt").read_text(), "")
|
|
||||||
values = (yaml.parent / "labels/train/0000_000015.txt").read_text().split()
|
|
||||||
self.assertEqual(values[0], "0")
|
|
||||||
self.assertEqual([float(v) for v in values[1:]], [0.3, 0.5, 0.4, 0.5])
|
|
||||||
import yaml as pyyaml
|
|
||||||
self.assertEqual(pyyaml.safe_load(yaml.read_text(encoding="utf-8"))["names"][0], self.data["name"])
|
|
||||||
|
|
||||||
def test_unreviewed_or_missing_positive_validation_rejected(self):
|
|
||||||
for frame in self.data["frames"][48:]:
|
|
||||||
frame["status"] = "auto"
|
|
||||||
self.save()
|
|
||||||
with self.assertRaises(ValueError):
|
|
||||||
worker.export_dataset({"project": str(self.project)})
|
|
||||||
|
|
||||||
def test_traversal_rejected(self):
|
|
||||||
self.data["frames"][0]["image"] = "../outside.jpg"
|
|
||||||
self.save()
|
|
||||||
with self.assertRaises(ValueError):
|
|
||||||
worker.load_project(self.project)
|
|
||||||
|
|
||||||
def test_box_bounds_and_finite(self):
|
|
||||||
for box in ([0,0,101,80], [float("nan"),0,1,1], [0,0,0,1]):
|
|
||||||
with self.assertRaises(ValueError):
|
|
||||||
worker.validate_box(box, 100, 80)
|
|
||||||
|
|
||||||
def test_visual_api_normalized_coordinates_pending_review(self):
|
|
||||||
import cv2
|
|
||||||
import numpy as np
|
|
||||||
image = np.full((80,100,3), 128, dtype=np.uint8)
|
|
||||||
ok, buffer = cv2.imencode(".jpg", image)
|
|
||||||
buffer.tofile(str(self.root / "frames/000000.jpg"))
|
|
||||||
self.save()
|
|
||||||
reply = {"choices": [{"message": {"content": '{"box":[0.1,0.2,0.8,0.9]}'}}]}
|
|
||||||
opener = unittest.mock.Mock()
|
|
||||||
opener.open.return_value = io.StringIO(json.dumps(reply))
|
|
||||||
with patch.dict(worker.os.environ, {"PARTTRAINER_API_KEY": "local-test-secret"}), patch.object(worker.urllib.request, "build_opener", return_value=opener):
|
|
||||||
worker.suggest({"project": str(self.project), "index": 0, "endpoint": "http://localhost:9999/v1", "apiModel": "test-vision"})
|
|
||||||
result = worker.read_json(self.project)["frames"][0]
|
|
||||||
self.assertEqual(result["objects"][0]["box"], [10,16,80,72])
|
|
||||||
self.assertEqual(result["status"], "auto")
|
|
||||||
self.assertTrue(result["objects"][0]["prompt"])
|
|
||||||
|
|
||||||
def multi_part(self):
|
|
||||||
self.data["annotationVersion"] = 2
|
|
||||||
for frame in self.data["frames"]:
|
|
||||||
frame.pop("box", None)
|
|
||||||
frame.pop("prompt", None)
|
|
||||||
frame["objects"] = [
|
|
||||||
{"label": "盒子", "box": [5, 5, 95, 75], "status": "reviewed", "prompt": False},
|
|
||||||
{"label": "连接器", "box": [20, 20, 40, 40], "status": "reviewed", "prompt": False}]
|
|
||||||
self.save()
|
|
||||||
|
|
||||||
def test_nested_parts_export_as_two_labels_in_same_image(self):
|
|
||||||
self.multi_part()
|
|
||||||
dataset = worker.export_dataset({"project": str(self.project), "every": 5}).parent
|
|
||||||
manifest = worker.read_json(dataset / "manifest.json")
|
|
||||||
self.assertEqual(manifest["classes"], ["盒子", "连接器"])
|
|
||||||
labels = (dataset / "labels/train/0000_000000.txt").read_text().splitlines()
|
|
||||||
self.assertEqual(len(labels), 2)
|
|
||||||
self.assertEqual([row.split()[0] for row in labels], ["0", "1"])
|
|
||||||
self.assertEqual([float(x) for x in labels[1].split()[1:]], [0.3, 0.375, 0.2, 0.25])
|
|
||||||
|
|
||||||
def test_unconfirmed_frames_not_exported_and_pending_objects_rejected(self):
|
|
||||||
self.multi_part()
|
|
||||||
self.data["frames"][0]["status"] = "auto"
|
|
||||||
self.save()
|
|
||||||
dataset = worker.export_dataset({"project": str(self.project), "every": 5}).parent
|
|
||||||
self.assertFalse((dataset / "labels/train/0000_000000.txt").exists())
|
|
||||||
self.data["frames"][5]["objects"][1]["status"] = "auto"
|
|
||||||
self.save()
|
|
||||||
with self.assertRaises(ValueError):
|
|
||||||
worker.export_dataset({"project": str(self.project), "every": 5})
|
|
||||||
|
|
||||||
def test_selected_part_propagation_preserves_other_labels_and_manual_work(self):
|
|
||||||
import copy
|
|
||||||
import types
|
|
||||||
import torch
|
|
||||||
self.multi_part()
|
|
||||||
for frame in self.data["frames"]:
|
|
||||||
frame["objects"] = frame["objects"][:1]
|
|
||||||
self.data["frames"][0]["objects"].append({"label": "连接器", "box": [20,20,40,40], "prompt": True, "status": "reviewed"})
|
|
||||||
manual = {"label": "连接器", "box": [10,10,15,15], "prompt": True, "status": "reviewed"}
|
|
||||||
self.data["frames"][2]["objects"].append(copy.deepcopy(manual))
|
|
||||||
self.data["frames"][3]["objects"].append({"label": "连接器", "box": None, "prompt": False, "status": "absent"})
|
|
||||||
self.data["frames"][4]["status"] = "excluded"
|
|
||||||
original_boxes = copy.deepcopy([f["objects"][0] for f in self.data["frames"]])
|
|
||||||
self.save()
|
|
||||||
class Predictor:
|
|
||||||
def init_state(inner, *args, **kwargs): return {}
|
|
||||||
def add_new_points_or_box(inner, *args, **kwargs): pass
|
|
||||||
def propagate_in_video(inner, *args, **kwargs):
|
|
||||||
for index in range(60):
|
|
||||||
mask = torch.full((1,1,80,100), -1.0)
|
|
||||||
mask[:,:,22:42,24:44] = 1
|
|
||||||
yield index, [1], mask
|
|
||||||
module = types.ModuleType("sam2.build_sam")
|
|
||||||
module.build_sam2_video_predictor = lambda *args, **kwargs: Predictor()
|
|
||||||
with patch.dict(worker.sys.modules, {"sam2.build_sam": module}), patch.object(worker, "emit"):
|
|
||||||
worker.propagate({"project": str(self.project), "label": "连接器", "device": "cpu", "checkpoint": "mock.pt"})
|
|
||||||
result = worker.read_json(self.project)
|
|
||||||
self.assertEqual([f["objects"][0] for f in result["frames"]], original_boxes)
|
|
||||||
self.assertEqual(worker.object_for(result["frames"][1], "连接器")["box"], [24,22,44,42])
|
|
||||||
self.assertEqual(worker.object_for(result["frames"][2], "连接器"), manual)
|
|
||||||
self.assertEqual(worker.object_for(result["frames"][3], "连接器")["status"], "absent")
|
|
||||||
self.assertIsNone(worker.object_for(result["frames"][4], "连接器"))
|
|
||||||
self.assertEqual(result["frames"][1]["status"], "auto")
|
|
||||||
self.assertNotIn("local-test-secret", self.project.read_text(encoding="utf-8"))
|
|
||||||
|
|
||||||
def test_import_stores_video_in_recipe(self):
|
|
||||||
import cv2
|
|
||||||
import numpy as np
|
|
||||||
video = self.root / "source.avi"
|
|
||||||
writer = cv2.VideoWriter(str(video), cv2.VideoWriter_fourcc(*"MJPG"), 10, (64, 64))
|
|
||||||
self.assertTrue(writer.isOpened())
|
|
||||||
for _ in range(8):
|
|
||||||
writer.write(np.full((64, 64, 3), 128, dtype=np.uint8))
|
|
||||||
writer.release()
|
|
||||||
recipe = (self.root / "recipes" / "配方甲").resolve()
|
|
||||||
output = recipe / "parts" / "part1"
|
|
||||||
worker.extract({"video": str(video), "output": str(output), "recipeName": "配方甲",
|
|
||||||
"recipeDirectory": str(recipe), "maxFrames": 10})
|
|
||||||
project = worker.read_json(output / "project.json")
|
|
||||||
self.assertEqual(Path(project["video"]).parent, recipe / "recordings")
|
|
||||||
self.assertTrue(Path(project["video"]).is_file())
|
|
||||||
self.assertTrue(video.is_file())
|
|
||||||
self.assertEqual(len(project["frames"]), 8)
|
|
||||||
self.assertEqual(worker.read_json(recipe / "recipe-training.json")["projects"], [str(output / "project.json")])
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@ -24,7 +24,7 @@ if (!$ReleaseId) {
|
|||||||
Write-Host "Release: $ReleaseId (commit $sha$(if($dirty){' + 未提交修改'}))"
|
Write-Host "Release: $ReleaseId (commit $sha$(if($dirty){' + 未提交修改'}))"
|
||||||
|
|
||||||
if (!$SkipPublish) {
|
if (!$SkipPublish) {
|
||||||
& dotnet publish (Join-Path $repo 'src\SopHelper.Avalonia') -c Release -r win-x64 --self-contained true -p:PublishSingleFile=false -p:BundlePythonRuntime=false -p:NativePlatform=Windows -o $output --nologo
|
& dotnet publish (Join-Path $repo 'src\SopHelper.Avalonia') -c Release -r win-x64 --self-contained true -p:PublishSingleFile=false -p:NativePlatform=Windows -o $output --nologo
|
||||||
if ($LASTEXITCODE) { throw 'Publish failed' }
|
if ($LASTEXITCODE) { throw 'Publish failed' }
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -39,7 +39,7 @@ $runtimeCheck = Start-Process -FilePath $exe -ArgumentList '--check-runtime' -No
|
|||||||
if ($runtimeCheck.ExitCode) { throw '本机 --check-runtime 自检失败,详见 scratch/test-results/deploy-windows-local-check-runtime.*.log' }
|
if ($runtimeCheck.ExitCode) { throw '本机 --check-runtime 自检失败,详见 scratch/test-results/deploy-windows-local-check-runtime.*.log' }
|
||||||
Write-Host '本机 --check-runtime 通过。'
|
Write-Host '本机 --check-runtime 通过。'
|
||||||
|
|
||||||
# 打包:不含 python(BundlePythonRuntime=false 时发布目录里的 python 为历史遗留)。
|
# 打包:仅打包当前程序运行所需文件,排除旧训练环境。
|
||||||
$packageItems = Get-ChildItem -LiteralPath $output -Force | Where-Object { $_.Name -ne 'python' } | Select-Object -ExpandProperty Name
|
$packageItems = Get-ChildItem -LiteralPath $output -Force | Where-Object { $_.Name -ne 'python' } | Select-Object -ExpandProperty Name
|
||||||
if (!$packageItems) { throw "Nothing to package in $output" }
|
if (!$packageItems) { throw "Nothing to package in $output" }
|
||||||
$archive = Join-Path $repo ('artifacts\' + $ReleaseId + '.tar.gz')
|
$archive = Join-Path $repo ('artifacts\' + $ReleaseId + '.tar.gz')
|
||||||
|
|||||||
@ -1,6 +1,5 @@
|
|||||||
param(
|
param(
|
||||||
[string]$OutputRoot = '',
|
[string]$OutputRoot = '',
|
||||||
[switch]$SkipPython,
|
|
||||||
[string[]]$RuntimeIdentifiers = @('win-x64','linux-x64')
|
[string[]]$RuntimeIdentifiers = @('win-x64','linux-x64')
|
||||||
)
|
)
|
||||||
$ErrorActionPreference='Stop'
|
$ErrorActionPreference='Stop'
|
||||||
@ -18,7 +17,7 @@ foreach ($rid in $RuntimeIdentifiers) {
|
|||||||
if ($rid -notin @('win-x64','linux-x64')) { throw "Unsupported runtime: $rid" }
|
if ($rid -notin @('win-x64','linux-x64')) { throw "Unsupported runtime: $rid" }
|
||||||
$destination=Join-Path $OutputRoot $rid
|
$destination=Join-Path $OutputRoot $rid
|
||||||
$nativePlatform=if($rid -eq 'win-x64'){'Windows'}else{'Linux'}
|
$nativePlatform=if($rid -eq 'win-x64'){'Windows'}else{'Linux'}
|
||||||
& dotnet publish $project -c Release -r $rid --self-contained true -p:PublishSingleFile=false -p:BundlePythonRuntime=false "-p:NativePlatform=$nativePlatform" -o $destination --nologo
|
& dotnet publish $project -c Release -r $rid --self-contained true -p:PublishSingleFile=false "-p:NativePlatform=$nativePlatform" -o $destination --nologo
|
||||||
if ($LASTEXITCODE) { throw "Publish failed: $rid" }
|
if ($LASTEXITCODE) { throw "Publish failed: $rid" }
|
||||||
[IO.File]::WriteAllText((Join-Path $destination 'source-manifest.json'),$sourceJson,[Text.UTF8Encoding]::new($false))
|
[IO.File]::WriteAllText((Join-Path $destination 'source-manifest.json'),$sourceJson,[Text.UTF8Encoding]::new($false))
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,34 +0,0 @@
|
|||||||
param([switch]$Sam2, [switch]$Cpu)
|
|
||||||
$ErrorActionPreference = 'Stop'
|
|
||||||
$projectRoot = Split-Path $PSScriptRoot -Parent
|
|
||||||
$env:PIP_CACHE_DIR = Join-Path $projectRoot '.cache/pip'
|
|
||||||
$runtimeRoot = Join-Path $projectRoot 'python'
|
|
||||||
$pythonPath = Join-Path $runtimeRoot 'python.exe'
|
|
||||||
function Invoke-Checked([string]$Program, [string[]]$Arguments) {
|
|
||||||
& $Program @Arguments
|
|
||||||
if ($LASTEXITCODE -ne 0) { throw "执行失败: $Program $($Arguments -join ' ')" }
|
|
||||||
}
|
|
||||||
if (!(Test-Path -LiteralPath $pythonPath)) {
|
|
||||||
# Copy a complete runtime, independent of the system Python and venv home.
|
|
||||||
$baseRoot = & python -c "import sys; print(sys.base_prefix)"
|
|
||||||
if ($LASTEXITCODE -ne 0) { throw 'Cannot locate bootstrap Python' }
|
|
||||||
New-Item -ItemType Directory -Force -Path $runtimeRoot | Out-Null
|
|
||||||
& robocopy $baseRoot $runtimeRoot /E /XD 'site-packages' '__pycache__' /XF '*.pyc' '*.lnk' /NFL /NDL /NJH /NJS
|
|
||||||
if ($LASTEXITCODE -ge 8) { throw 'Failed to copy Python runtime' }
|
|
||||||
Invoke-Checked $pythonPath @('-m', 'ensurepip', '--upgrade')
|
|
||||||
}
|
|
||||||
Invoke-Checked $pythonPath @('-m', 'pip', 'install', '--upgrade', 'pip')
|
|
||||||
$torchFlavor = if ($Cpu) { 'cpu' } else { 'cu128' }
|
|
||||||
# Pin a matching pair: an already installed newer CPU wheel otherwise satisfies an unpinned install.
|
|
||||||
Invoke-Checked $pythonPath @('-m', 'pip', 'install', '--upgrade', "torch==2.11.0+$torchFlavor", "torchvision==0.26.0+$torchFlavor", '--index-url', "https://download.pytorch.org/whl/$torchFlavor")
|
|
||||||
Invoke-Checked $pythonPath @('-m', 'pip', 'install', '-r', (Join-Path $PSScriptRoot 'requirements.txt'))
|
|
||||||
if ($Sam2) {
|
|
||||||
# SAM2's optional CUDA extension is unnecessary for basic box propagation on Windows.
|
|
||||||
$env:SAM2_BUILD_CUDA = '0'
|
|
||||||
Invoke-Checked $pythonPath @('-m', 'pip', 'install', 'wheel', 'huggingface_hub')
|
|
||||||
Invoke-Checked $pythonPath @('-m', 'pip', 'install', '--no-build-isolation', 'git+https://github.com/facebookresearch/sam2.git@2b90b9f5ceec907a1c18123530e92e794ad901a4')
|
|
||||||
}
|
|
||||||
if (!$Cpu) {
|
|
||||||
Invoke-Checked $pythonPath @('-c', 'import torch; assert torch.cuda.is_available(), "CUDA unavailable: check the NVIDIA driver or explicitly use -Cpu"; x=torch.ones((32,32),device="cuda"); torch.cuda.synchronize(); print("GPU ready:",torch.cuda.get_device_name(0),"PyTorch",torch.__version__)')
|
|
||||||
}
|
|
||||||
Write-Host "完成。内置环境: $pythonPath;请重新构建/发布程序以携带 python 子目录。"
|
|
||||||
@ -49,7 +49,7 @@ $env:SOPHELPER_VISION_PROVIDER = 'd3-lite'
|
|||||||
$env:SOPHELPER_VISION_ENDPOINT = "http://127.0.0.1:$Port/v1/systemone"
|
$env:SOPHELPER_VISION_ENDPOINT = "http://127.0.0.1:$Port/v1/systemone"
|
||||||
Push-Location $repoRoot
|
Push-Location $repoRoot
|
||||||
try {
|
try {
|
||||||
& dotnet run --project src/SopHelper.Avalonia -p:BundlePythonRuntime=false
|
& dotnet run --project src/SopHelper.Avalonia
|
||||||
if ($LASTEXITCODE -ne 0) { throw "SOP 程序退出,代码:$LASTEXITCODE" }
|
if ($LASTEXITCODE -ne 0) { throw "SOP 程序退出,代码:$LASTEXITCODE" }
|
||||||
} finally {
|
} finally {
|
||||||
Pop-Location
|
Pop-Location
|
||||||
|
|||||||
@ -53,6 +53,6 @@ if ($AllowUncalibrated) {
|
|||||||
if ($CheckOnly) { return }
|
if ($CheckOnly) { return }
|
||||||
Push-Location $repoRoot
|
Push-Location $repoRoot
|
||||||
try {
|
try {
|
||||||
& dotnet run --project src/SopHelper.Avalonia -p:BundlePythonRuntime=false
|
& dotnet run --project src/SopHelper.Avalonia
|
||||||
if ($LASTEXITCODE -ne 0) { throw "SOP 程序退出,代码:$LASTEXITCODE" }
|
if ($LASTEXITCODE -ne 0) { throw "SOP 程序退出,代码:$LASTEXITCODE" }
|
||||||
} finally { Pop-Location }
|
} finally { Pop-Location }
|
||||||
|
|||||||
@ -1,18 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
set -euo pipefail
|
|
||||||
root=${1:?Usage: Setup-Python.sh APPLICATION_DIRECTORY [--sam2]}
|
|
||||||
root=$(cd "$root" && pwd)
|
|
||||||
bootstrap=${PYTHON:-python3}
|
|
||||||
"$bootstrap" -c 'import sys; assert sys.version_info >= (3, 10), "Python 3.10 or later is required; Python 3.12 is recommended"'
|
|
||||||
# Resolve deployment symlinks so venv entry points do not depend on an old release directory.
|
|
||||||
runtime=$(realpath -m "${SOPHELPER_PYTHON_ROOT:-$root/python}")
|
|
||||||
"$bootstrap" -m venv "$runtime"
|
|
||||||
python="$runtime/bin/python3"
|
|
||||||
"$python" -m pip install --upgrade pip
|
|
||||||
"$python" -m pip install 'torch>=2.5.1' torchvision --index-url https://download.pytorch.org/whl/cpu
|
|
||||||
"$python" -m pip install -r "$root/tools/requirements.txt"
|
|
||||||
if [ "${2:-}" = --sam2 ]; then
|
|
||||||
"$python" -m pip install setuptools wheel huggingface_hub
|
|
||||||
SAM2_BUILD_CUDA=0 "$python" -m pip install --no-build-isolation 'git+https://github.com/facebookresearch/sam2.git@2b90b9f5ceec907a1c18123530e92e794ad901a4'
|
|
||||||
fi
|
|
||||||
printf 'Python runtime ready: %s\n' "$python"
|
|
||||||
@ -1,7 +0,0 @@
|
|||||||
numpy>=1.26,<3
|
|
||||||
PyYAML>=6,<7
|
|
||||||
opencv-python>=4.10,<6
|
|
||||||
ultralytics>=8.3,<9
|
|
||||||
onnx>=1.16,<2
|
|
||||||
onnxruntime>=1.18,<2
|
|
||||||
onnxscript>=0.2,<1
|
|
||||||
574
tools/worker.py
574
tools/worker.py
@ -1,574 +0,0 @@
|
|||||||
"""PartTrainer worker. JSON request file in, JSON-line events out. No UI dependencies.
|
|
||||||
|
|
||||||
SAM2 is optional and imported only for propagation. Never silently substitute another tracker.
|
|
||||||
"""
|
|
||||||
import base64
|
|
||||||
import hashlib
|
|
||||||
from contextlib import nullcontext
|
|
||||||
import importlib.util
|
|
||||||
import json
|
|
||||||
import math
|
|
||||||
import os
|
|
||||||
from pathlib import Path
|
|
||||||
import shutil
|
|
||||||
import sys
|
|
||||||
import tempfile
|
|
||||||
import traceback
|
|
||||||
import urllib.request
|
|
||||||
import uuid
|
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parent.parent
|
|
||||||
os.environ.setdefault("YOLO_CONFIG_DIR", str(ROOT / ".cache" / "ultralytics"))
|
|
||||||
os.environ.setdefault("HF_HOME", str(ROOT / ".cache" / "huggingface"))
|
|
||||||
os.environ["TORCHINDUCTOR_CACHE_DIR"] = str(ROOT / ".cache" / "torch")
|
|
||||||
os.environ["TRITON_CACHE_DIR"] = str(ROOT / ".cache" / "triton")
|
|
||||||
os.environ["MPLCONFIGDIR"] = str(ROOT / ".cache" / "matplotlib")
|
|
||||||
os.environ.setdefault("TORCH_HOME", str(ROOT / ".cache" / "torch-hub"))
|
|
||||||
os.environ["YOLO_AUTOINSTALL"] = "false"
|
|
||||||
|
|
||||||
|
|
||||||
# 标准输出使用逐行 JSON 协议并立即刷新,桌面端可持续读取进度而无需等待进程结束。
|
|
||||||
def emit(message, **values):
|
|
||||||
print(json.dumps({"message": message, **values}, ensure_ascii=False), flush=True)
|
|
||||||
|
|
||||||
|
|
||||||
# 先写同目录临时文件再替换,避免中途失败留下半份项目 JSON。
|
|
||||||
def save_json(path, data):
|
|
||||||
path = Path(path)
|
|
||||||
temporary = path.with_suffix(path.suffix + ".tmp")
|
|
||||||
temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
||||||
temporary.replace(path)
|
|
||||||
|
|
||||||
|
|
||||||
def read_json(path):
|
|
||||||
return json.loads(Path(path).read_text(encoding="utf-8-sig"))
|
|
||||||
|
|
||||||
|
|
||||||
def sha256_file(path):
|
|
||||||
digest = hashlib.sha256()
|
|
||||||
with Path(path).open("rb") as source:
|
|
||||||
while chunk := source.read(1024 * 1024):
|
|
||||||
digest.update(chunk)
|
|
||||||
return digest.hexdigest()
|
|
||||||
|
|
||||||
|
|
||||||
# 标注框使用原图像素坐标 [x1,y1,x2,y2],拒绝非有限数值、空框和越界范围。
|
|
||||||
def validate_box(box, width, height):
|
|
||||||
if (not isinstance(box, list) or len(box) != 4
|
|
||||||
or not all(isinstance(v, (int, float)) and math.isfinite(v) for v in box)
|
|
||||||
or not (0 <= box[0] < box[2] <= width and 0 <= box[1] < box[3] <= height)):
|
|
||||||
raise ValueError("无效标注框:需要图像范围内的 [x1,y1,x2,y2] 像素坐标")
|
|
||||||
return box
|
|
||||||
|
|
||||||
|
|
||||||
# 加载并校验项目元数据及标注,后续操作共用这一入口,避免直接信任外部项目内容。
|
|
||||||
def load_project(path):
|
|
||||||
path = Path(path).resolve()
|
|
||||||
data = read_json(path)
|
|
||||||
if data["width"] <= 0 or data["height"] <= 0 or not data["frames"]:
|
|
||||||
raise ValueError("项目没有有效的视频帧")
|
|
||||||
legacy = int(data.get("annotationVersion", 1)) < 2
|
|
||||||
for frame in data["frames"]:
|
|
||||||
image = (path.parent / frame["image"]).resolve()
|
|
||||||
if not image.is_relative_to(path.parent):
|
|
||||||
raise ValueError("帧路径超出项目目录")
|
|
||||||
if legacy and not frame.get("objects"):
|
|
||||||
frame["objects"] = [{"label": data["name"], "box": frame.get("box"), "status": frame.get("status", "unlabeled"), "prompt": frame.get("prompt", False)}]
|
|
||||||
frame.pop("box", None)
|
|
||||||
frame.pop("prompt", None)
|
|
||||||
objects = frame.setdefault("objects", [])
|
|
||||||
names = [o.get("label") for o in objects]
|
|
||||||
if any(not isinstance(n, str) or not n.strip() for n in names) or len(set(names)) != len(names):
|
|
||||||
raise ValueError("同一帧的零件名称不能为空或重复")
|
|
||||||
for item in objects:
|
|
||||||
if item.get("box") is not None:
|
|
||||||
validate_box(item["box"], data["width"], data["height"])
|
|
||||||
data["annotationVersion"] = 2
|
|
||||||
return path, data
|
|
||||||
|
|
||||||
|
|
||||||
def project_labels(data):
|
|
||||||
return list(dict.fromkeys(o["label"] for f in data["frames"] for o in f.get("objects", [])))
|
|
||||||
|
|
||||||
|
|
||||||
def object_for(frame, label, create=False):
|
|
||||||
item = next((o for o in frame.get("objects", []) if o["label"] == label), None)
|
|
||||||
if item is None and create:
|
|
||||||
item = {"label": label, "box": None, "status": "unlabeled", "prompt": False}
|
|
||||||
frame.setdefault("objects", []).append(item)
|
|
||||||
return item
|
|
||||||
|
|
||||||
|
|
||||||
def doctor(request):
|
|
||||||
modules = {m: importlib.util.find_spec(m) is not None for m in ("cv2", "numpy", "torch", "ultralytics", "sam2", "onnx")}
|
|
||||||
emit("Python " + sys.version.split()[0], modules=modules)
|
|
||||||
if modules["torch"]:
|
|
||||||
import torch
|
|
||||||
emit(f"PyTorch {torch.__version__} · CUDA {'可用' if torch.cuda.is_available() else '不可用,将使用 CPU'}")
|
|
||||||
if not all(modules[m] for m in ("cv2", "numpy", "torch", "ultralytics")):
|
|
||||||
setup = "tools/Setup-Python.ps1 -Sam2" if sys.platform == "win32" else "PYTHON=python3.12 bash tools/Setup-Python.sh 程序目录 --sam2"
|
|
||||||
raise RuntimeError(f"标注运行环境依赖不完整,请运行 {setup} 安装")
|
|
||||||
if not modules["sam2"]:
|
|
||||||
emit("尚未安装 SAM2;手动标注、导出、训练仍可用,自动传播需安装 SAM2")
|
|
||||||
if request.get("strict"):
|
|
||||||
for name in ("cv2", "numpy", "torch", "ultralytics", "sam2", "onnx", "onnxruntime", "onnxscript"):
|
|
||||||
importlib.import_module(name)
|
|
||||||
initial = ROOT / "tools" / "yolo11n.pt"
|
|
||||||
checkpoint = ROOT / "models" / "sam2.1_hiera_tiny.pt"
|
|
||||||
if not initial.is_file() or not checkpoint.is_file():
|
|
||||||
raise FileNotFoundError("独立运行目录缺少 YOLO 初始权重或 SAM2 权重")
|
|
||||||
from ultralytics import YOLO
|
|
||||||
YOLO(str(initial))
|
|
||||||
from sam2.build_sam import build_sam2_video_predictor
|
|
||||||
torch.set_num_threads(min(4, os.cpu_count() or 1))
|
|
||||||
build_sam2_video_predictor("configs/sam2.1/sam2.1_hiera_t.yaml", str(default_checkpoint()), device="cpu")
|
|
||||||
emit("独立训练环境检查通过:本地 YOLO 与 SAM2 权重均成功加载")
|
|
||||||
|
|
||||||
|
|
||||||
# 将源视频抽帧为可复核标注项目;请求参数决定采样及目标配方关联。
|
|
||||||
def extract(request):
|
|
||||||
import cv2
|
|
||||||
import numpy as np
|
|
||||||
video = Path(request["video"]).resolve()
|
|
||||||
target = Path(request["output"]).resolve()
|
|
||||||
stride = int(request.get("stride", 1))
|
|
||||||
limit = int(request.get("maxFrames", 600))
|
|
||||||
if stride < 1 or not 2 <= limit <= 10000:
|
|
||||||
raise ValueError("抽帧间隔需 ≥1,帧数上限需在 2–10000 之间")
|
|
||||||
if target.exists():
|
|
||||||
raise ValueError("输出项目目录已存在,请选择新的项目名称")
|
|
||||||
cap = cv2.VideoCapture(str(video))
|
|
||||||
if not cap.isOpened():
|
|
||||||
raise ValueError("视频无法打开")
|
|
||||||
staging = target.with_name(target.name + ".importing-" + uuid.uuid4().hex[:8])
|
|
||||||
staging.mkdir(parents=True)
|
|
||||||
try:
|
|
||||||
if request.get("recipeDirectory"):
|
|
||||||
directory = Path(request["recipeDirectory"]).resolve() / "recordings"
|
|
||||||
directory.mkdir(parents=True, exist_ok=True)
|
|
||||||
if not video.is_relative_to(directory.parent):
|
|
||||||
stored = directory / video.name
|
|
||||||
if stored.exists() and sha256_file(stored) != sha256_file(video):
|
|
||||||
stored = directory / (video.stem + "-" + sha256_file(video)[:10] + video.suffix)
|
|
||||||
if not stored.exists():
|
|
||||||
shutil.copy2(video, stored)
|
|
||||||
video = stored
|
|
||||||
frames_dir = staging / "frames"
|
|
||||||
frames_dir.mkdir()
|
|
||||||
fps = cap.get(cv2.CAP_PROP_FPS)
|
|
||||||
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
|
||||||
# Bound RAM/disk use and preserve coverage across the entire source video.
|
|
||||||
stride = max(stride, math.ceil(total / limit)) if total > 0 else stride
|
|
||||||
data = {"annotationVersion": 2, "name": request.get("name", video.stem), "video": str(video), "fps": fps if math.isfinite(fps) else 0,
|
|
||||||
"width": 0, "height": 0, "stride": stride, "frames": [],
|
|
||||||
"recipeName": request.get("recipeName", ""), "recipeDirectory": request.get("recipeDirectory", "")}
|
|
||||||
index = 0
|
|
||||||
while True:
|
|
||||||
ok, image = cap.read()
|
|
||||||
if not ok:
|
|
||||||
break
|
|
||||||
if index % stride == 0:
|
|
||||||
if len(data["frames"]) >= limit:
|
|
||||||
emit("已达到帧数上限,剩余视频未导入")
|
|
||||||
break
|
|
||||||
h, w = image.shape[:2]
|
|
||||||
data["width"], data["height"] = w, h
|
|
||||||
number = len(data["frames"])
|
|
||||||
name = f"frames/{number:06d}.jpg"
|
|
||||||
success, buffer = cv2.imencode(".jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 95])
|
|
||||||
if not success:
|
|
||||||
raise RuntimeError("帧编码失败")
|
|
||||||
buffer.tofile(str(staging / name))
|
|
||||||
data["frames"].append({"index": number, "sourceIndex": index, "image": name,
|
|
||||||
"objects": [], "status": "unlabeled"})
|
|
||||||
if number % 25 == 0:
|
|
||||||
emit(f"已抽取 {number + 1} 帧", progress=min(0.99, index / max(total, 1)))
|
|
||||||
index += 1
|
|
||||||
if len(data["frames"]) < 2:
|
|
||||||
raise ValueError("视频有效帧不足两帧")
|
|
||||||
save_json(staging / "project.json", data)
|
|
||||||
staging.rename(target)
|
|
||||||
if data.get("recipeDirectory"):
|
|
||||||
recipe_context({"project": str(target / "project.json")})
|
|
||||||
emit(f"导入完成:{len(data['frames'])} 帧,原视频每 {stride} 帧采样一次", progress=1)
|
|
||||||
except BaseException:
|
|
||||||
shutil.rmtree(staging, ignore_errors=True)
|
|
||||||
raise
|
|
||||||
finally:
|
|
||||||
cap.release()
|
|
||||||
|
|
||||||
|
|
||||||
# 按需加载 SAM2 传播已有标注;缺少模型或运行环境时明确失败,不替换为其他跟踪器。
|
|
||||||
def propagate(request):
|
|
||||||
import numpy as np
|
|
||||||
import torch
|
|
||||||
from sam2.build_sam import build_sam2_video_predictor
|
|
||||||
path, data = load_project(request["project"])
|
|
||||||
label = request.get("label") or (project_labels(data)[0] if len(project_labels(data)) == 1 else "")
|
|
||||||
if not label:
|
|
||||||
raise ValueError("请先选择要自动标注的零件")
|
|
||||||
prompts = [(f, object_for(f, label)) for f in data["frames"] if f.get("status") not in ("excluded", "absent")]
|
|
||||||
prompts = [(f, o) for f, o in prompts if o and o.get("prompt") and o.get("box") and o["status"] == "reviewed"]
|
|
||||||
if not prompts:
|
|
||||||
raise ValueError("请至少手动画一个关键帧标注框")
|
|
||||||
device = request.get("device", "auto")
|
|
||||||
device = ("cuda" if torch.cuda.is_available() else "cpu") if device == "auto" else device
|
|
||||||
if str(device).isdigit():
|
|
||||||
device = "cuda:" + str(device)
|
|
||||||
if device == "cpu":
|
|
||||||
torch.set_num_threads(min(8, os.cpu_count() or 4))
|
|
||||||
checkpoint = request.get("checkpoint", "").strip()
|
|
||||||
emit(f"加载 SAM2.1 · {device};首次使用默认模型需要联网下载")
|
|
||||||
if checkpoint:
|
|
||||||
predictor = build_sam2_video_predictor(request.get("config", "configs/sam2.1/sam2.1_hiera_t.yaml"), checkpoint, device=device)
|
|
||||||
else:
|
|
||||||
checkpoint = default_checkpoint()
|
|
||||||
predictor = build_sam2_video_predictor("configs/sam2.1/sam2.1_hiera_t.yaml", str(checkpoint), device=device)
|
|
||||||
context = torch.autocast("cuda", dtype=torch.bfloat16) if device.startswith("cuda") and torch.cuda.is_bf16_supported() else nullcontext()
|
|
||||||
with torch.inference_mode(), context:
|
|
||||||
state = predictor.init_state(str(path.parent / "frames"), offload_video_to_cpu=True, offload_state_to_cpu=True)
|
|
||||||
for frame, item in prompts:
|
|
||||||
predictor.add_new_points_or_box(state, frame_idx=frame["index"], obj_id=1, box=np.array(item["box"], dtype=np.float32))
|
|
||||||
start = min(f["index"] for f, _ in prompts)
|
|
||||||
# Run both directions so a seed drawn in the middle covers earlier frames too.
|
|
||||||
directions = [False, True] if start > 0 else [False]
|
|
||||||
count = 0
|
|
||||||
for reverse in directions:
|
|
||||||
for index, ids, logits in predictor.propagate_in_video(state, start_frame_idx=start, reverse=reverse):
|
|
||||||
frame = data["frames"][index]
|
|
||||||
item = object_for(frame, label)
|
|
||||||
if frame["status"] in ("absent", "excluded") or (item and item["status"] in ("reviewed", "absent")):
|
|
||||||
continue
|
|
||||||
mask = (logits[0, 0] > 0).cpu().numpy()
|
|
||||||
ys, xs = np.where(mask)
|
|
||||||
item = object_for(frame, label, create=True)
|
|
||||||
item["box"] = [int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1] if len(xs) else None
|
|
||||||
frame["status"] = "auto" # Empty predictions still require review, never become negative labels automatically.
|
|
||||||
item["status"] = "auto"
|
|
||||||
item["prompt"] = False
|
|
||||||
count += 1
|
|
||||||
if count % 20 == 0:
|
|
||||||
save_json(path, data)
|
|
||||||
emit(f"传播帧 {index + 1}/{len(data['frames'])}" + (" · 未找到目标" if not len(xs) else ""), progress=count / len(data["frames"]))
|
|
||||||
save_json(path, data)
|
|
||||||
emit(f"{label} 的 SAM2 传播完成,其他零件标注已保留;请复核整帧", progress=1)
|
|
||||||
|
|
||||||
|
|
||||||
def default_checkpoint():
|
|
||||||
"""Download the official fixed SAM2.1 tiny checkpoint, atomically, with bounded network waits."""
|
|
||||||
target = ROOT / "models" / "sam2.1_hiera_tiny.pt"
|
|
||||||
expected_hash = "7402e0d864fa82708a20fbd15bc84245c2f26dff0eb43a4b5b93452deb34be69"
|
|
||||||
if target.is_file():
|
|
||||||
if sha256_file(target) != expected_hash:
|
|
||||||
raise IOError("默认 SAM2 模型校验失败,请移走 models/sam2.1_hiera_tiny.pt 后重新下载")
|
|
||||||
return target
|
|
||||||
target.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
temporary = target.with_suffix(".pt.download")
|
|
||||||
url = "https://dl.fbaipublicfiles.com/segment_anything_2/092824/sam2.1_hiera_tiny.pt"
|
|
||||||
downloaded = 0
|
|
||||||
try:
|
|
||||||
with urllib.request.urlopen(url, timeout=30) as response, temporary.open("wb") as output:
|
|
||||||
total = int(response.headers.get("Content-Length", 0))
|
|
||||||
while chunk := response.read(1024 * 1024):
|
|
||||||
output.write(chunk)
|
|
||||||
downloaded += len(chunk)
|
|
||||||
if downloaded % (10 * 1024 * 1024) < len(chunk):
|
|
||||||
emit(f"下载 SAM2 模型 {downloaded // 1048576}/{total // 1048576} MB")
|
|
||||||
if total and downloaded != total:
|
|
||||||
raise IOError("模型下载不完整,请重试")
|
|
||||||
if downloaded < 100_000_000:
|
|
||||||
raise IOError("模型文件尺寸异常,请手动下载官方模型")
|
|
||||||
if sha256_file(temporary) != expected_hash:
|
|
||||||
raise IOError("SAM2 模型 SHA256 校验失败,请重试")
|
|
||||||
temporary.replace(target)
|
|
||||||
finally:
|
|
||||||
temporary.unlink(missing_ok=True)
|
|
||||||
return target
|
|
||||||
|
|
||||||
|
|
||||||
def recipe_context(request):
|
|
||||||
path, data = load_project(request["project"])
|
|
||||||
directory = data.get("recipeDirectory", "")
|
|
||||||
if not directory:
|
|
||||||
return path.parent, [(path, data)], project_labels(data)
|
|
||||||
root = Path(directory).resolve()
|
|
||||||
root.mkdir(parents=True, exist_ok=True)
|
|
||||||
registry = root / "recipe-training.json"
|
|
||||||
state = read_json(registry) if registry.exists() else {"projects": [], "classes": []}
|
|
||||||
config_path = root / (data.get("recipeName", root.name) + ".yaml")
|
|
||||||
catalog = None
|
|
||||||
if config_path.exists():
|
|
||||||
import yaml
|
|
||||||
catalog = (yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}).get("sop", {}).get("parts")
|
|
||||||
if catalog is not None:
|
|
||||||
if (not isinstance(catalog, list) or any(not isinstance(n, str) or not n.strip() or n != n.strip() for n in catalog)
|
|
||||||
or len(catalog) != len(set(catalog))):
|
|
||||||
raise ValueError("配方零件列表无效,请在配方编辑中维护")
|
|
||||||
state["classes"] = list(catalog)
|
|
||||||
current = str(path)
|
|
||||||
if current not in state["projects"]:
|
|
||||||
state["projects"].append(current)
|
|
||||||
labels = state.setdefault("labels", {})
|
|
||||||
projects = []
|
|
||||||
missing = []
|
|
||||||
for item in state["projects"]:
|
|
||||||
if not Path(item).exists():
|
|
||||||
missing.append(item)
|
|
||||||
continue
|
|
||||||
projects.append(load_project(item))
|
|
||||||
for source, project in projects:
|
|
||||||
names = project_labels(project)
|
|
||||||
if catalog is not None and any(name not in catalog for name in names):
|
|
||||||
raise ValueError(f"零件“{'、'.join(n for n in names if n not in catalog)}”不在配方零件列表中,请先在配方编辑中维护")
|
|
||||||
previous = labels.get(str(source))
|
|
||||||
# A corrected name keeps its class ID when it is the sole video for that part.
|
|
||||||
if catalog is None and len(names) == 1 and isinstance(previous, str) and previous != names[0] and previous in state["classes"] and names[0] not in state["classes"]:
|
|
||||||
others = [n for other, p in projects if other != source for n in project_labels(p)]
|
|
||||||
if previous not in others:
|
|
||||||
state["classes"][state["classes"].index(previous)] = names[0]
|
|
||||||
labels[str(source)] = names[0] if len(names) == 1 else names
|
|
||||||
if Path(project.get("recipeDirectory", "")).resolve() != root:
|
|
||||||
raise ValueError(f"零件项目的配方归属不一致:{source}")
|
|
||||||
for name in names:
|
|
||||||
if name not in state["classes"]:
|
|
||||||
state["classes"].append(name)
|
|
||||||
if missing:
|
|
||||||
archived = state.setdefault("missingProjects", [])
|
|
||||||
for item in missing:
|
|
||||||
if item not in archived:
|
|
||||||
archived.append(item)
|
|
||||||
labels.pop(item, None)
|
|
||||||
emit(f"标注项目已不存在,已自动从训练名单移除:{item}。继续使用其余项目训练,类别编号保留。")
|
|
||||||
# Reopening a restored project reactivates it through the current request.
|
|
||||||
if "missingProjects" in state:
|
|
||||||
state["missingProjects"] = [item for item in state["missingProjects"] if item not in {str(p) for p, _ in projects}]
|
|
||||||
state["projects"] = [str(p) for p, _ in projects]
|
|
||||||
save_json(registry, state)
|
|
||||||
return root, projects, state["classes"]
|
|
||||||
|
|
||||||
|
|
||||||
# 将已复核标注整理为训练数据集,保持类别表与导出标签的索引一致。
|
|
||||||
def export_dataset(request):
|
|
||||||
root, projects, classes = recipe_context(request)
|
|
||||||
every = int(request.get("every", 5))
|
|
||||||
ratio = float(request.get("valRatio", 0.2))
|
|
||||||
if every < 1 or not 0 < ratio < 0.5:
|
|
||||||
raise ValueError("训练抽样间隔需 ≥1,验证比例需在 0–0.5 之间")
|
|
||||||
samples = []
|
|
||||||
current = Path(request["project"]).resolve()
|
|
||||||
rejected = []
|
|
||||||
for path, data in projects:
|
|
||||||
selected = [f for f in data["frames"] if f["status"] in ("reviewed", "absent")]
|
|
||||||
reason = None
|
|
||||||
if any(f["status"] == "reviewed" and (not any(o.get("box") for o in f["objects"]) or any(o.get("status") not in ("reviewed", "absent") or (o.get("status") == "reviewed" and not o.get("box")) for o in f["objects"])) for f in selected):
|
|
||||||
reason = "整帧复核不完整:存在未确认的零件或缺少标注框"
|
|
||||||
boundary = int(len(data["frames"]) * (1 - ratio))
|
|
||||||
training = [f for f in selected if f["index"] < boundary - every and f["index"] % every == 0]
|
|
||||||
validation = [f for f in selected if f["index"] >= boundary and f["index"] % every == 0]
|
|
||||||
if len(training) < 2 or not validation or not any(o.get("box") for f in training for o in f["objects"]) or not any(o.get("box") for f in validation for o in f["objects"]):
|
|
||||||
reason = reason or "复核样本不足,训练段至少两个样本,末尾验证段至少一个;两段均需有正样本。请补充复核或减小训练抽样间隔"
|
|
||||||
if any(not (path.parent / f["image"]).is_file() for f in training + validation):
|
|
||||||
reason = reason or "训练样本的图像文件不存在"
|
|
||||||
if reason:
|
|
||||||
if path == current:
|
|
||||||
raise ValueError(f"{data['name']}:{reason}")
|
|
||||||
rejected.append(str(path))
|
|
||||||
emit(f"旧项目不符合训练要求,已自动从训练名单移除:{path}({reason})。继续使用其余项目训练,类别编号保留。")
|
|
||||||
continue
|
|
||||||
samples.append((path, data, training, validation))
|
|
||||||
if rejected:
|
|
||||||
registry = root / "recipe-training.json"
|
|
||||||
state = read_json(registry)
|
|
||||||
state["projects"] = [p for p in state["projects"] if p not in rejected]
|
|
||||||
for item in rejected:
|
|
||||||
state.get("labels", {}).pop(item, None)
|
|
||||||
save_json(registry, state)
|
|
||||||
output = root / "datasets" / ("dataset-" + uuid.uuid4().hex[:10])
|
|
||||||
output.mkdir(parents=True)
|
|
||||||
manifest = []
|
|
||||||
for number, (path, data, training, validation) in enumerate(samples):
|
|
||||||
class_ids = [classes.index(name) for name in project_labels(data)]
|
|
||||||
for split, frames in (("train", training), ("val", validation)):
|
|
||||||
(output / "images" / split).mkdir(parents=True, exist_ok=True)
|
|
||||||
(output / "labels" / split).mkdir(parents=True, exist_ok=True)
|
|
||||||
for frame in frames:
|
|
||||||
stem = f"{number:04d}_{frame['index']:06d}"
|
|
||||||
shutil.copy2(path.parent / frame["image"], output / "images" / split / (stem + ".jpg"))
|
|
||||||
label = ""
|
|
||||||
for item in frame["objects"]:
|
|
||||||
if item.get("box") is None or frame["status"] == "absent":
|
|
||||||
continue
|
|
||||||
x1, y1, x2, y2 = validate_box(item["box"], data["width"], data["height"])
|
|
||||||
label += str(classes.index(item["label"])) + " " + " ".join(f"{v:.8f}" for v in ((x1+x2)/2/data["width"], (y1+y2)/2/data["height"],
|
|
||||||
(x2-x1)/data["width"], (y2-y1)/data["height"])) + "\n"
|
|
||||||
(output / "labels" / split / (stem + ".txt")).write_text(label, encoding="utf-8")
|
|
||||||
manifest.append({"project": str(path), "classIds": class_ids, "classId": class_ids[0] if len(class_ids) == 1 else None, "train": [f["index"] for f in training], "val": [f["index"] for f in validation]})
|
|
||||||
yaml = f"path: {json.dumps(output.as_posix(), ensure_ascii=False)}\ntrain: images/train\nval: images/val\nnames:\n"
|
|
||||||
yaml += "".join(f" {i}: {json.dumps(name, ensure_ascii=False)}\n" for i, name in enumerate(classes))
|
|
||||||
(output / "data.yaml").write_text(yaml, encoding="utf-8")
|
|
||||||
save_json(output / "manifest.json", {"projects": manifest, "classes": classes, "gap": every})
|
|
||||||
save_json(root / "latest-dataset.json", {"yaml": str(output / "data.yaml")})
|
|
||||||
emit(f"配方数据导出完成 · {len(classes)} 类零件 / {len(samples)} 个视频", output=str(output), progress=1)
|
|
||||||
return output / "data.yaml"
|
|
||||||
|
|
||||||
|
|
||||||
# 执行训练并通过事件输出进度;独立工作进程的取消由 C# 桥接器终止进程树完成。
|
|
||||||
def train(request):
|
|
||||||
from ultralytics import YOLO
|
|
||||||
import torch
|
|
||||||
path, data = load_project(request["project"])
|
|
||||||
epochs = int(request.get("epochs", 50))
|
|
||||||
size = int(request.get("imageSize", 640))
|
|
||||||
batch = int(request.get("batch", 4))
|
|
||||||
if not 1 <= epochs <= 10000 or not 32 <= size <= 2048 or size % 32 or batch < 1:
|
|
||||||
raise ValueError("训练参数无效:尺寸需为32的倍数,轮数与批次需为正数")
|
|
||||||
yaml = export_dataset(request) # Fresh export prevents training with stale review changes.
|
|
||||||
root, _, classes = recipe_context(request)
|
|
||||||
latest = root / "latest-model.json"
|
|
||||||
initial = read_json(latest)["weights"] if latest.exists() else request.get("model", "yolo11n.pt")
|
|
||||||
emit(f"自动加载初始模型:{initial}")
|
|
||||||
model = YOLO(initial)
|
|
||||||
if model.task != "detect":
|
|
||||||
raise ValueError("当前项目导出矩形检测框,请选择 YOLO detect 模型(非 seg / pose / classify)")
|
|
||||||
reported_epoch = 0
|
|
||||||
history = []
|
|
||||||
def finite_metrics(values):
|
|
||||||
output = {}
|
|
||||||
for key, value in values.items():
|
|
||||||
try:
|
|
||||||
number = float(value)
|
|
||||||
if math.isfinite(number):
|
|
||||||
output[str(key)] = number
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
pass
|
|
||||||
return output
|
|
||||||
def started(trainer):
|
|
||||||
emit("训练已启动", event="training_started", runDirectory=str(trainer.save_dir), device=str(device), progress=0)
|
|
||||||
def epoch_end(trainer):
|
|
||||||
nonlocal reported_epoch
|
|
||||||
current = min(epochs, trainer.epoch + 1)
|
|
||||||
if current <= reported_epoch:
|
|
||||||
return
|
|
||||||
reported_epoch = current
|
|
||||||
metrics = finite_metrics(trainer.metrics or {})
|
|
||||||
if trainer.tloss is not None:
|
|
||||||
metrics.update(finite_metrics(trainer.label_loss_items(trainer.tloss, prefix="train")))
|
|
||||||
record = {"epoch": current, "epochs": epochs, "metrics": metrics}
|
|
||||||
history.append(record)
|
|
||||||
save_json(Path(trainer.save_dir) / "training-metrics.json", history)
|
|
||||||
emit(f"训练轮次 {current}/{epochs}", event="training_epoch", **record, progress=current / epochs)
|
|
||||||
model.add_callback("on_train_start", started)
|
|
||||||
model.add_callback("on_fit_epoch_end", epoch_end)
|
|
||||||
device = request.get("device", "auto")
|
|
||||||
device = (0 if torch.cuda.is_available() else "cpu") if device == "auto" else device
|
|
||||||
if device == "cuda":
|
|
||||||
device = "0"
|
|
||||||
output_directory = root / "runs"
|
|
||||||
output_directory.mkdir(parents=True, exist_ok=True)
|
|
||||||
model.train(data=str(yaml), epochs=epochs, imgsz=size, batch=batch, device=device,
|
|
||||||
workers=0, resume=False, project=str(output_directory), name="train-" + uuid.uuid4().hex[:8])
|
|
||||||
best = Path(model.trainer.best)
|
|
||||||
if not best.is_file():
|
|
||||||
raise RuntimeError("训练未生成 best.pt")
|
|
||||||
# Publish a versioned recipe-named checkpoint before atomically switching the latest pointer.
|
|
||||||
recipe_name = data.get("recipeName") or data["name"]
|
|
||||||
safe_name = "".join("_" if c in '<>:"/\\|?*' or ord(c) < 32 else c for c in recipe_name).strip(" .") or "recipe"
|
|
||||||
published = root / "models" / Path(model.trainer.save_dir).name / (safe_name + ".pt")
|
|
||||||
published.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
shutil.copy2(best, published)
|
|
||||||
emit("训练已结束,正在导出配方 ONNX…", event="onnx_export_started", weights=str(published),
|
|
||||||
runDirectory=str(model.trainer.save_dir))
|
|
||||||
try:
|
|
||||||
onnx = export_checkpoint_onnx(published, size)
|
|
||||||
except Exception as error:
|
|
||||||
raise RuntimeError(f"训练权重已保存到 {published};ONNX 导出失败,配方继续保留上一版模型:{error}") from error
|
|
||||||
summary = {"recipeName": recipe_name, "classes": classes, "weights": str(published), "dataset": str(yaml), "runDirectory": str(model.trainer.save_dir),
|
|
||||||
"metrics": finite_metrics(model.trainer.metrics or {}), "epochs": reported_epoch,
|
|
||||||
"imageSize": size, "device": str(device), "onnx": str(onnx)}
|
|
||||||
save_json(Path(model.trainer.save_dir) / "training-result.json", summary)
|
|
||||||
save_json(root / "latest-model.json", summary)
|
|
||||||
emit("训练完成,配方 ONNX 已自动导出", event="training_completed", **summary, output=str(onnx), progress=1)
|
|
||||||
|
|
||||||
|
|
||||||
def export_checkpoint_onnx(weights, size):
|
|
||||||
from ultralytics import YOLO
|
|
||||||
output = Path(YOLO(str(weights)).export(format="onnx", imgsz=size,
|
|
||||||
opset=17, dynamic=False, simplify=False, nms=False))
|
|
||||||
if not output.is_file():
|
|
||||||
raise RuntimeError("未生成 ONNX 文件")
|
|
||||||
return output.resolve()
|
|
||||||
|
|
||||||
|
|
||||||
def export_onnx(request):
|
|
||||||
root, _, _ = recipe_context(request)
|
|
||||||
summary = read_json(root / "latest-model.json")
|
|
||||||
# A manual re-export must retain the trained recipe's input size.
|
|
||||||
output = export_checkpoint_onnx(summary["weights"], int(summary.get("imageSize", request.get("imageSize", 640))))
|
|
||||||
summary["onnx"] = str(output)
|
|
||||||
save_json(Path(summary["runDirectory"]) / "training-result.json", summary)
|
|
||||||
save_json(root / "latest-model.json", summary)
|
|
||||||
emit("配方 ONNX 导出完成(检测框输出,不含 NMS)", onnx=str(output), output=str(output), progress=1)
|
|
||||||
|
|
||||||
|
|
||||||
def suggest(request):
|
|
||||||
path, data = load_project(request["project"])
|
|
||||||
frame = data["frames"][int(request["index"])]
|
|
||||||
label = request.get("label") or (project_labels(data)[0] if len(project_labels(data)) == 1 else "")
|
|
||||||
if not label:
|
|
||||||
raise ValueError("请先选择建议框对应的零件")
|
|
||||||
key = os.environ.get("PARTTRAINER_API_KEY", "")
|
|
||||||
if not key:
|
|
||||||
raise ValueError("请填写视觉 API Key(只保存在当前进程内)")
|
|
||||||
url = request["endpoint"].rstrip("/") + "/chat/completions"
|
|
||||||
if not url.startswith("https://") and not url.startswith(("http://localhost:", "http://127.0.0.1:")):
|
|
||||||
raise ValueError("远程视觉接口必须使用 HTTPS;本地服务可使用 HTTP")
|
|
||||||
# Resize to bound request size, request normalized coordinates so no resize ambiguity occurs.
|
|
||||||
import cv2
|
|
||||||
import numpy as np
|
|
||||||
image = cv2.imdecode(np.fromfile(str(path.parent / frame["image"]), dtype=np.uint8), cv2.IMREAD_COLOR)
|
|
||||||
if image is None:
|
|
||||||
raise ValueError("图像无法打开")
|
|
||||||
h, w = image.shape[:2]
|
|
||||||
scale = min(1, 1280 / max(h, w))
|
|
||||||
image = cv2.resize(image, (round(w*scale), round(h*scale)))
|
|
||||||
ok, buffer = cv2.imencode(".jpg", image)
|
|
||||||
if not ok:
|
|
||||||
raise ValueError("图像编码失败")
|
|
||||||
prompt = f"Locate the single main object described as: {label}. {request.get('description', '')} Return ONLY JSON: {{\"box\":[x1,y1,x2,y2]}} with coordinates normalized to 0..1. If absent, return {{\"box\":null}}."
|
|
||||||
payload = {"model": request["apiModel"], "messages": [{"role": "user", "content": [
|
|
||||||
{"type": "text", "text": prompt}, {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + base64.b64encode(buffer).decode()}}]}], "max_tokens": 300}
|
|
||||||
req = urllib.request.Request(url, data=json.dumps(payload).encode(), headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"})
|
|
||||||
# Do not forward the API key across redirects.
|
|
||||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
||||||
def redirect_request(self, *args, **kwargs):
|
|
||||||
return None
|
|
||||||
with urllib.request.build_opener(NoRedirect).open(req, timeout=120) as response:
|
|
||||||
reply = json.load(response)["choices"][0]["message"]["content"].strip()
|
|
||||||
if reply.startswith("```"):
|
|
||||||
reply = reply.split("\n", 1)[1].rsplit("```", 1)[0]
|
|
||||||
box = json.loads(reply)["box"]
|
|
||||||
if box is not None:
|
|
||||||
validate_box(box, 1, 1)
|
|
||||||
box = [box[0]*data["width"], box[1]*data["height"], box[2]*data["width"], box[3]*data["height"]]
|
|
||||||
# This becomes a conditioning frame only after the user approves it.
|
|
||||||
object_for(frame, label, create=True).update(box=box, status="auto", prompt=box is not None)
|
|
||||||
frame["status"] = "auto"
|
|
||||||
save_json(path, data)
|
|
||||||
emit("视觉模型已给出建议,请检查并确认当前帧", progress=1)
|
|
||||||
|
|
||||||
|
|
||||||
# 从命令行指定的 JSON 请求文件分派操作,错误经顶层异常处理报告给桌面端。
|
|
||||||
def main():
|
|
||||||
request = read_json(sys.argv[1])
|
|
||||||
actions = {"doctor": doctor, "extract": extract, "propagate": propagate, "export": export_dataset,
|
|
||||||
"train": train, "onnx": export_onnx, "suggest": suggest}
|
|
||||||
actions[request["action"]](request)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
try:
|
|
||||||
main()
|
|
||||||
except Exception as error:
|
|
||||||
emit(str(error), error=True)
|
|
||||||
traceback.print_exc(file=sys.stderr)
|
|
||||||
sys.exit(1)
|
|
||||||
Loading…
Reference in New Issue
Block a user