Integrate PartTrainer workflow into SopHelper

This commit is contained in:
sophelper 2026-11-07 09:09:04 +08:00
parent a72afee162
commit f1783f321d
30 changed files with 2483 additions and 3 deletions

8
.gitignore vendored
View File

@ -1,4 +1,4 @@
## Ignore Visual Studio temporary files, build results, and
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
@ -392,3 +392,9 @@ FodyWeavers.xsd
!/libs/MvCameraControl.Net.dll
/libs/cuda/
/models
# Training environments and generated data
/.venv/
/.cache/
/workspace/
*.pt

View File

@ -1,7 +1,7 @@
# SopHelper — 单相机 SOP 辅助
工位上接一个 UVC 或海康工业相机,程序按 YAML 配方定义的步骤顺序判定操作员动作:逐步打勾、
超时报违规、留日志和快照。只做一件事,不做大而全。
超时报违规、留日志和快照。侧栏的「零件标注与训练」集成 PartTrainer 的采集、标注与模型训练流程。
引擎逻辑移植自 [VisionInspectionSystem](https://github.com/TheDoorIsUnlocked/VisionInspectionSystem)(MIT)。
@ -106,6 +106,37 @@ dotnet run --project tests/ShutdownSmoke/ShutdownSmoke.csproj
dotnet run --project tests/ShutdownSmoke/ShutdownSmoke.csproj -- --hardware
```
## 零件标注与训练
侧栏「零件标注与训练」包含原 PartTrainer 的完整工作流:相机录像、导入视频与抽帧、手工画框、SAM2 双向传播、逐帧或一键复核、负样本与排除帧、YOLO 数据集导出、训练与 ONNX 导出、视频模型测试,以及可选视觉 API 建议框。切换到 SOP 页再返回会保留当前项目及任务。
首次使用 Python 功能,在 SopHelper 根目录执行:
```powershell
powershell -ExecutionPolicy Bypass -File tools/Setup-Python.ps1 -Sam2
# CPU 环境附加 -Cpu
```
程序优先使用本项目 `.venv/Scripts/python.exe`,也可在「设置」填写已有 PartTrainer 的 Python 完整路径来复用环境。相机预览和录像不需要 Python。设置保存在 `workspace/settings.json`,录像默认保存在 `workspace/recordings`;API Key 不保存到配置或日志。原 PartTrainer 的 `project.json` 可直接打开,项目中原有的绝对视频、权重路径需要仍然有效。集成后的源码、Python worker 和安装脚本均在本仓库内,构建与发布无需 PartTrainer 目录。
相机录像窗口以模态打开;SOP 正在运行或操作相机时会提示先停止,避免两个流程同时占用设备。关闭采集窗口会结束并封装录像。关闭主窗口时会取消后台 Python 任务、等待进程退出并释放相机;即使已切回 SOP 页面也会清理。
标注目前支持单目标、单类别矩形框。导出只包含已复核正样本和明确标记的无目标帧,按时间划分训练与验证并保留间隔。单段视频的指标用于验证流程,实际效果需使用独立现场视频评估。
训练后点击「导出最新模型为 ONNX」,在 SOP 配方编辑器「检测模型」选择导出的 ONNX;类别表可留空以读取模型元数据,也可提供对应类别表。导出采用固定尺寸、opset 17、无内置 NMS。原 PartTrainer 项目保留,可继续独立运行。
Python 依赖中的 Ultralytics 使用 AGPL-3.0 / 商业许可;SAM2 使用其上游许可。部署时需遵守所选依赖与模型的许可。
集成回归检查:
```powershell
dotnet run --project tests/Training.Smoke
dotnet run --project tests/Training.UiSmoke
dotnet run --project tests/Training.CameraSmoke
dotnet run --project tests/Training.ShellSmoke
.venv/Scripts/python.exe -X utf8 -m unittest discover -s tests -p test_worker.py -v
```
## 配方
`configs/sop/*.yaml`,写好的例子见 `configs/sop/demo.yaml`。

View File

@ -22,6 +22,7 @@ public partial class App
{
private ICameraService? _camera;
private DetectionPipeline? _pipeline;
private Engine.Training.WorkerClient? _trainingWorker;
/// <summary>
/// 注册应用程序所需的类型和服务
@ -58,7 +59,10 @@ public partial class App
_ = containerRegistry.RegisterSingleton<SopEngine>();
// ViewModel 工厂默认走容器解析,带构造注入的 ViewModel 必须先注册
_ = containerRegistry.Register<SopPageViewModel>();
_ = containerRegistry.RegisterSingleton<SopPageViewModel>();
_trainingWorker = new Engine.Training.WorkerClient();
containerRegistry.RegisterInstance(_trainingWorker);
containerRegistry.RegisterSingleton<Training.MainViewModel>();
// 配方编辑器弹窗(SOP 页「编辑」「新建」按钮弹出)
containerRegistry.RegisterDialog<RecipeEditor, RecipeEditorViewModel>("RecipeEditorDialog");
@ -101,6 +105,7 @@ public partial class App
{
try
{
_trainingWorker?.Dispose();
// Dispose 等待采集线程退出、归还缓冲并关闭设备,然后才能释放推理模型。
try { _camera?.Dispose(); }
catch (Exception ex) { Log(ex, "Exit.Camera"); }

View File

@ -33,4 +33,9 @@
<Content Include="..\..\configs\**\*.*" Link="configs\%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<Content Include="../../tools/worker.py" Link="tools/worker.py" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
<Content Include="../../tools/Setup-Python.ps1" Link="tools/Setup-Python.ps1" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
<Content Include="../../tools/requirements.txt" Link="tools/requirements.txt" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,67 @@
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace SopHelper.Training;
/// <summary>Aspect-fit preview with original-image coordinates, including letterbox offsets.</summary>
public sealed class AnnotationCanvas : FrameworkElement
{
public static readonly DependencyProperty SourceProperty = DependencyProperty.Register(nameof(Source), typeof(BitmapSource), typeof(AnnotationCanvas), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty BoxProperty = DependencyProperty.Register(nameof(Box), typeof(double[]), typeof(AnnotationCanvas), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
public BitmapSource? Source { get => (BitmapSource?)GetValue(SourceProperty); set => SetValue(SourceProperty, value); }
public double[]? Box { get => (double[]?)GetValue(BoxProperty); set => SetValue(BoxProperty, value); }
public event Action<double[]>? BoxDrawn;
private Point? _start;
private Point _end;
public AnnotationCanvas() { ClipToBounds = true; Cursor = Cursors.Cross; Focusable = true; }
private Rect ImageRect
{
get
{
if (Source == null) return Rect.Empty;
var scale = Math.Min(ActualWidth / Source.PixelWidth, ActualHeight / Source.PixelHeight);
var w = Source.PixelWidth * scale; var h = Source.PixelHeight * scale;
return new Rect((ActualWidth - w) / 2, (ActualHeight - h) / 2, w, h);
}
}
protected override void OnRender(DrawingContext dc)
{
dc.DrawRectangle(Brushes.Transparent, null, new Rect(RenderSize));
var image = ImageRect;
if (Source == null || image.IsEmpty) return;
dc.DrawImage(Source, image);
var pen = new Pen(new SolidColorBrush(Color.FromRgb(0, 220, 220)), 2);
if (Box is { Length: 4 } b)
{
var scale = image.Width / Source.PixelWidth;
dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(30, 0, 220, 220)), pen,
new Rect(image.X + b[0]*scale, image.Y + b[1]*scale, (b[2]-b[0])*scale, (b[3]-b[1])*scale));
}
if (_start is { } start) dc.DrawRectangle(null, new Pen(Brushes.Yellow, 2), new Rect(start, _end));
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
if (!IsEnabled || Source == null || !ImageRect.Contains(e.GetPosition(this))) return;
Focus(); _start = _end = e.GetPosition(this); CaptureMouse(); InvalidateVisual(); e.Handled = true;
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (_start == 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 OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
if (_start is not { } start || Source == null) return;
var rectangle = new Rect(start, _end); var image = ImageRect;
_start = null; ReleaseMouseCapture(); InvalidateVisual();
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)]);
}
protected override void OnLostMouseCapture(MouseEventArgs e) { _start = null; InvalidateVisual(); base.OnLostMouseCapture(e); }
}

View File

@ -0,0 +1,288 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Microsoft.Win32;
using OpenCvSharp;
using SopHelper.Engine.Camera;
using Prism.Commands;
using Prism.Mvvm;
namespace SopHelper.Training;
public sealed class CameraViewModel : BindableBase
{
private readonly ICameraService _camera;
private readonly VideoRecorder _recorder = new();
private readonly object _frames = new();
private readonly Dispatcher _dispatcher;
private readonly DispatcherTimer _timer;
private readonly string _settingsPath;
private readonly Stopwatch _previewClock = Stopwatch.StartNew();
private Mat? _latest;
private int _previewPending;
private int _generation;
private long _lastFrameTick;
private volatile bool _closing;
private bool _busy, _previewing, _recording;
private string _status = "刷新设备列表,选择相机后开启预览";
private string _directory;
private string _lastRecording = "";
private string _recordingInfo = "未录像";
private CameraInfo? _selected;
private BitmapSource? _preview;
private Task _operation = Task.CompletedTask;
private Task? _shutdown;
private readonly List<DelegateCommand> _commands = [];
public ObservableCollection<CameraInfo> Cameras { get; } = [];
public CameraInfo? SelectedCamera { get => _selected; set { SetProperty(ref _selected, value); UpdateCommands(); } }
public BitmapSource? Preview { get => _preview; private set => SetProperty(ref _preview, value); }
public string Status { get => _status; private set => SetProperty(ref _status, value); }
public bool IsBusy { get => _busy; private set { SetProperty(ref _busy, value); StateChanged(); } }
public bool IsPreviewing { get => _previewing; private set { SetProperty(ref _previewing, value); StateChanged(); } }
public bool IsRecording { get => _recording; private set { SetProperty(ref _recording, value); StateChanged(); } }
public bool CanChooseCamera => !IsBusy && !IsPreviewing && !_closing;
public bool CanChangeDirectory => !IsBusy && !IsRecording && !_closing;
public string PreviewButtonText => IsPreviewing ? "关闭相机" : "开启相机预览";
public string RecordButtonText => IsRecording ? "停止录像" : "开始录像";
public string RecordingInfo { get => _recordingInfo; private set => SetProperty(ref _recordingInfo, value); }
public string SaveDirectory { get => _directory; set => SetProperty(ref _directory, value); }
public string LastRecording { get => _lastRecording; private set { SetProperty(ref _lastRecording, value); UpdateCommands(); } }
public double RecordingFps { get; set; } = 30;
public DelegateCommand RefreshCommand { get; }
public DelegateCommand PreviewCommand { get; }
public DelegateCommand RecordCommand { get; }
public DelegateCommand BrowseCommand { get; }
public DelegateCommand RevealCommand { get; }
public CameraViewModel(ICameraService camera, string root)
{
_camera = camera; _dispatcher = Application.Current.Dispatcher;
_directory = Path.Combine(root, "workspace", "recordings");
_settingsPath = Path.Combine(root, "workspace", "camera-settings.json");
try
{
if (File.Exists(_settingsPath))
{
using var json = JsonDocument.Parse(File.ReadAllText(_settingsPath));
SaveDirectory = json.RootElement.GetProperty("directory").GetString() ?? _directory;
}
}
catch (Exception e) { Status = "录像目录配置读取失败:" + e.Message; }
RefreshCommand = Command(RefreshAsync, () => CanChooseCamera);
PreviewCommand = Command(TogglePreviewAsync, () => !IsBusy && !_closing && (IsPreviewing || SelectedCamera != null));
RecordCommand = Command(ToggleRecordingAsync, () => !IsBusy && !_closing && (IsRecording || (IsPreviewing && Preview != null && HasRecentFrame)));
BrowseCommand = Command(() =>
{
var picker = new OpenFolderDialog { Title = "选择录像保存目录" };
if (Directory.Exists(SaveDirectory)) picker.InitialDirectory = SaveDirectory;
if (picker.ShowDialog() == true) { SaveDirectory = picker.FolderName; SaveSettings(); }
return Task.CompletedTask;
}, () => CanChangeDirectory);
RevealCommand = Command(() =>
{
if (!string.IsNullOrEmpty(LastRecording) && File.Exists(LastRecording))
{
var info = new ProcessStartInfo("explorer.exe") { UseShellExecute = true };
info.ArgumentList.Add("/select," + LastRecording); Process.Start(info);
}
else
{
Directory.CreateDirectory(SaveDirectory);
var info = new ProcessStartInfo("explorer.exe") { UseShellExecute = true };
info.ArgumentList.Add(Path.GetFullPath(SaveDirectory)); Process.Start(info);
}
return Task.CompletedTask;
}, () => !IsBusy && !_closing);
_camera.FrameArrived += OnFrame;
_camera.ConnectionChanged += OnConnection;
_camera.Error += OnError;
_timer = new DispatcherTimer(TimeSpan.FromMilliseconds(250), DispatcherPriority.Background, (_, _) => Tick(), _dispatcher);
_timer.Start();
}
private DelegateCommand Command(Func<Task> action, Func<bool> canExecute)
{
var command = new DelegateCommand(() => _operation = PerformAsync(action), canExecute);
_commands.Add(command); return command;
}
private async Task PerformAsync(Func<Task> action)
{
if (IsBusy || _closing) return;
IsBusy = true;
try { await action(); }
catch (Exception e) { Status = e.Message; }
finally { IsBusy = false; }
}
private void UpdateCommands() { foreach (var command in _commands) command.RaiseCanExecuteChanged(); }
private void StateChanged()
{
RaisePropertyChanged(nameof(CanChooseCamera)); RaisePropertyChanged(nameof(CanChangeDirectory));
RaisePropertyChanged(nameof(PreviewButtonText)); RaisePropertyChanged(nameof(RecordButtonText)); UpdateCommands();
}
private async Task RefreshAsync()
{
Status = "正在枚举 UVC / 海康相机…";
var devices = await _camera.EnumerateAsync();
if (_closing) return;
Cameras.Clear(); foreach (var device in devices) Cameras.Add(device);
SelectedCamera = Cameras.FirstOrDefault();
Status = Cameras.Count == 0 ? "未找到相机,请检查连接;海康设备需要 MVS x64 运行时" : $"找到 {Cameras.Count} 台相机";
}
private async Task TogglePreviewAsync()
{
if (IsPreviewing)
{
StopRecording();
await Task.Run(_camera.Disconnect);
ClearPreview(); IsPreviewing = false; Status = "相机已关闭";
return;
}
var selected = SelectedCamera ?? throw new InvalidOperationException("请选择相机");
Status = "正在连接 " + selected.Name;
if (!await _camera.ConnectAsync(selected)) throw new IOException("相机连接失败,请检查设备是否被其他程序占用");
if (_closing) return;
if (!await _camera.StartAsync())
{
await Task.Run(_camera.Disconnect);
throw new IOException("相机已连接,但采集启动失败");
}
IsPreviewing = true; Status = "相机预览中,可开始录像";
}
private Task ToggleRecordingAsync()
{
if (IsRecording) { StopRecording(); return Task.CompletedTask; }
if (string.IsNullOrWhiteSpace(SaveDirectory)) throw new ArgumentException("请选择录像保存目录");
var directory = Path.GetFullPath(SaveDirectory.Trim());
SaveDirectory = directory; SaveSettings();
lock (_frames)
{
if (_latest == null || !_camera.IsGrabbing) throw new InvalidOperationException("尚未收到相机画面,请先开启预览");
if (Stopwatch.GetElapsedTime(_lastFrameTick).TotalSeconds > 2) throw new IOException("超过2秒未收到相机画面,请重新连接后再录像");
LastRecording = _recorder.Start(directory, _latest, RecordingFps);
}
IsRecording = true; Status = "正在录像,点击“停止录像”保存文件"; Tick();
return Task.CompletedTask;
}
private void StopRecording()
{
RecordingResult? result;
lock (_frames) result = _recorder.Stop();
IsRecording = false;
if (result != null)
{
LastRecording = result.Path;
RecordingInfo = $"已保存 · {result.Duration.TotalSeconds:F1} 秒 · {result.Frames} 帧";
Status = "录像已保存,可在主窗口导入视频继续标注";
}
}
private void OnFrame(CameraFrame frame)
{
if (_closing) return;
BitmapSource? preview = null;
string? recordingError = null;
var generation = Volatile.Read(ref _generation);
lock (_frames)
{
if (_closing) return;
Interlocked.Exchange(ref _lastFrameTick, Stopwatch.GetTimestamp());
if (_latest == null) _latest = frame.Bgr.Clone(); else frame.Bgr.CopyTo(_latest);
try { _recorder.Write(frame.Bgr); }
catch (Exception e) { recordingError = "录像中断:" + e.Message + ";已写入内容保存在 " + _recorder.CurrentPath; }
if (_previewClock.ElapsedMilliseconds >= 66 && Interlocked.CompareExchange(ref _previewPending, 1, 0) == 0)
{
try
{
var stride = checked((int)frame.Bgr.Step());
preview = BitmapSource.Create(frame.Bgr.Width, frame.Bgr.Height, 96, 96, PixelFormats.Bgr24,
null, frame.Bgr.Data, checked(stride * frame.Bgr.Height), stride);
preview.Freeze(); _previewClock.Restart();
}
catch { Interlocked.Exchange(ref _previewPending, 0); throw; }
}
}
if (recordingError != null)
{
var error = recordingError;
Post(() => { IsRecording = false; Status = error; RecordingInfo = "录像中断,请检查日志提示"; });
}
if (preview != null)
{
var bitmap = preview;
Post(() =>
{
try
{
if (generation == Volatile.Read(ref _generation)) { Preview = bitmap; UpdateCommands(); }
}
finally { Interlocked.Exchange(ref _previewPending, 0); }
});
}
}
private void OnConnection(bool connected)
{
if (!connected) Post(() =>
{
if (_camera.IsConnected) return; // Ignore a queued disconnect from the previous connection.
StopRecording(); IsPreviewing = false; ClearPreview();
});
}
private void OnError(string message) => Post(() => Status = message);
private void Post(Action action)
{
if (!_closing && !_dispatcher.HasShutdownStarted)
_dispatcher.BeginInvoke(() => { if (!_closing) action(); }, DispatcherPriority.Background);
}
private void Tick()
{
if (_closing) return;
if (IsRecording)
{
if (Stopwatch.GetElapsedTime(Interlocked.Read(ref _lastFrameTick)).TotalSeconds > 2)
{
StopRecording(); Status = "超过2秒未收到相机画面,录像已结束,请检查相机连接";
}
else if (!_recorder.IsRecording) IsRecording = false;
else RecordingInfo = $"● 正在录像 {_recorder.Elapsed:hh\\:mm\\:ss} · {RecordingFps:F0} fps";
}
if (IsPreviewing && !_camera.IsGrabbing && !IsBusy)
{
StopRecording(); IsPreviewing = false; ClearPreview(); Status = "相机采集已中断,请重新连接";
}
}
private bool HasRecentFrame => Interlocked.Read(ref _lastFrameTick) != 0 &&
Stopwatch.GetElapsedTime(Interlocked.Read(ref _lastFrameTick)).TotalSeconds <= 2;
private void ClearPreview()
{
Interlocked.Increment(ref _generation);
lock (_frames) { _latest?.Dispose(); _latest = null; }
Preview = null;
}
private void SaveSettings()
{
Directory.CreateDirectory(Path.GetDirectoryName(_settingsPath)!);
File.WriteAllText(_settingsPath, JsonSerializer.Serialize(new { directory = SaveDirectory }));
}
public Task ShutdownAsync() => _shutdown ??= ShutdownCoreAsync();
private async Task ShutdownCoreAsync()
{
_closing = true; _timer.Stop(); StateChanged();
await _operation;
try { await Task.Run(_camera.Dispose); }
finally
{
try { StopRecording(); }
finally
{
ClearPreview();
_camera.FrameArrived -= OnFrame; _camera.ConnectionChanged -= OnConnection; _camera.Error -= OnError;
IsPreviewing = false;
}
}
}
}

View File

@ -0,0 +1,39 @@
<Window x:Class="SopHelper.Training.CameraWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="SopHelper · 相机与录像" Width="1080" Height="800" MinWidth="840" MinHeight="650" WindowStartupLocation="CenterOwner">
<Window.Resources><ResourceDictionary Source="/SopHelper;component/Training/Styles.xaml"/></Window.Resources>
<Grid Margin="18">
<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>
<TextBlock Text="相机与录像" FontSize="22" FontWeight="Bold" Foreground="{StaticResource Accent}" Margin="0,0,0,16"/>
<Grid Grid.Row="1" Margin="0,0,0,10">
<Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="Auto"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
<ComboBox ItemsSource="{Binding Cameras}" SelectedItem="{Binding SelectedCamera}" IsEnabled="{Binding CanChooseCamera}" Margin="0,0,10,6" MinHeight="36">
<ComboBox.ItemTemplate><DataTemplate><TextBlock Text="{Binding Name}"/></DataTemplate></ComboBox.ItemTemplate>
</ComboBox>
<Button Grid.Column="1" Content="刷新相机" Command="{Binding RefreshCommand}"/>
<Button Grid.Column="2" Content="{Binding PreviewButtonText}" Command="{Binding PreviewCommand}"/>
</Grid>
<Border Grid.Row="2" Background="#080E14" BorderBrush="{StaticResource Line}" BorderThickness="1" CornerRadius="6">
<Grid>
<TextBlock Text="开启相机后在此显示实时画面" HorizontalAlignment="Center" Foreground="{StaticResource Dim}"/>
<Image Source="{Binding Preview}" Stretch="Uniform"/>
<Border HorizontalAlignment="Left" VerticalAlignment="Top" Margin="12" Padding="10,5" Background="#CC101820" CornerRadius="4"><TextBlock Text="{Binding RecordingInfo}"><TextBlock.Style><Style TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}"><Setter Property="Foreground" Value="{StaticResource Dim}"/><Style.Triggers><DataTrigger Binding="{Binding IsRecording}" Value="True"><Setter Property="Foreground" Value="#F0533C"/></DataTrigger></Style.Triggers></Style></TextBlock.Style></TextBlock></Border>
</Grid>
</Border>
<StackPanel Grid.Row="3" Margin="0,14,0,0">
<TextBlock Text="录像保存目录"/>
<Grid>
<Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="Auto"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
<TextBox Text="{Binding SaveDirectory, UpdateSourceTrigger=PropertyChanged}" IsEnabled="{Binding CanChangeDirectory}" Margin="0,6,10,8"/>
<Button Grid.Column="1" Content="选择目录…" Command="{Binding BrowseCommand}" Margin="0,6,6,8"/>
<Button Grid.Column="2" Content="打开保存位置" Command="{Binding RevealCommand}" Margin="0,6,0,8"/>
</Grid>
<DockPanel>
<Button DockPanel.Dock="Left" Content="{Binding RecordButtonText}" Command="{Binding RecordCommand}" BorderBrush="{StaticResource Accent}" MinWidth="130"/>
<TextBlock Text="AVI / MJPEG · 30 fps · 原始画面,不含标注和界面" Foreground="{StaticResource Dim}" Margin="12,0,0,6"/>
</DockPanel>
<TextBlock Text="{Binding LastRecording}" TextTrimming="CharacterEllipsis" ToolTip="{Binding LastRecording}" Foreground="{StaticResource Dim}" Margin="0,0,0,8"/>
</StackPanel>
<TextBlock Grid.Row="4" Text="{Binding Status}" TextWrapping="Wrap" Margin="0,8,0,0"/>
</Grid>
</Window>

View File

@ -0,0 +1,27 @@
using System.ComponentModel;
using System.Windows;
namespace SopHelper.Training;
public partial class CameraWindow : Window
{
public CameraViewModel Model { get; }
private bool _closedSafely;
private bool _closeRequested;
public CameraWindow(CameraViewModel model)
{
InitializeComponent(); Model = model; DataContext = model;
}
protected override async void OnClosing(CancelEventArgs e)
{
if (_closedSafely) { base.OnClosing(e); return; }
e.Cancel = true;
base.OnClosing(e);
if (_closeRequested) return;
_closeRequested = true;
IsEnabled = false;
try { await Model.ShutdownAsync(); }
catch (Exception error) { MessageBox.Show(this, "关闭相机时出错:" + error.Message, "相机与录像"); }
_ = Dispatcher.BeginInvoke(() => { _closedSafely = true; Close(); });
}
}

View File

@ -0,0 +1,367 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using System.Windows;
using System.Windows.Media.Imaging;
using Microsoft.Win32;
using SopHelper.Engine.Training;
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 double _progress;
private string _status = "新建项目:导入视频,在任意清晰帧拖动画框";
private string _logs = "";
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); }
public string TrainingRunDirectory { get => _trainingRunDirectory; private set => SetProperty(ref _trainingRunDirectory, value); }
public string TrainingOutputDirectory { get; set; } = "";
public string Root { get; }
internal WorkerClient Worker => _worker;
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;
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); }
public double[]? CurrentBox => _selected?.Box;
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));
}
}
// Configuration is saved locally, except the API key which is passed only through the worker environment.
public string Python { get; set; } = "python";
public string Label { get; set; } = "零件";
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 { get; set; } = "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 DoctorCommand { get; }
public DelegateCommand PropagateCommand { get; }
public DelegateCommand ExportCommand { get; }
public DelegateCommand TrainCommand { get; }
public DelegateCommand PickTrainingModelCommand { get; }
public DelegateCommand PickTrainingOutputCommand { 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 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;
var directory = new DirectoryInfo(AppContext.BaseDirectory);
while (directory.Parent != null && !File.Exists(Path.Combine(directory.FullName, "SopHelper.slnx"))) directory = directory.Parent;
Root = File.Exists(Path.Combine(directory.FullName, "SopHelper.slnx")) ? directory.FullName : AppContext.BaseDirectory;
var localPython = Path.Combine(Root, ".venv", "Scripts", "python.exe");
if (File.Exists(localPython)) Python = localPython;
LoadSettings();
ImportCommand = Command(Import);
OpenCommand = Command(() =>
{
var dialog = new OpenFileDialog { Filter = "标注项目|project.json" };
if (dialog.ShowDialog() == true) Load(dialog.FileName);
});
DoctorCommand = Command(async () => await Run(new { action = "doctor" }, reload: false));
PropagateCommand = Command(async () => { SaveLabel(); await Run(new { action = "propagate", project = RequireProject().FilePath, checkpoint = Checkpoint, config = SamConfig, device = Device }); });
ExportCommand = Command(async () => { SaveLabel(); await Run(Request("export")); });
TrainCommand = Command(async () => { SaveLabel(); await Run(Request("train")); });
PickTrainingModelCommand = Command(() =>
{
var dialog = new OpenFileDialog { Filter = "YOLO模型|*.pt;*.yaml;*.yml" };
if (dialog.ShowDialog() == true) { Model = dialog.FileName; RaisePropertyChanged(nameof(Model)); }
});
PickTrainingOutputCommand = Command(() =>
{
var dialog = new OpenFolderDialog { Title = "选择训练结果保存目录" };
if (dialog.ShowDialog() == true) { TrainingOutputDirectory = dialog.FolderName; RaisePropertyChanged(nameof(TrainingOutputDirectory)); }
});
OpenTrainingResultsCommand = Command(() =>
{
var directory = TrainingRunDirectory;
if (!Directory.Exists(directory)) throw new DirectoryNotFoundException("尚无训练结果目录,请先完成一次训练");
Process.Start(new ProcessStartInfo("explorer.exe") { ArgumentList = { directory }, UseShellExecute = true });
});
OnnxCommand = Command(async () => await Run(Request("onnx")));
SuggestCommand = Command(async () =>
{
SaveLabel();
if (SelectedFrame == null) throw new InvalidOperationException("请先选择帧");
await Run(new { action = "suggest", project = RequireProject().FilePath, index = SelectedFrame.Index,
endpoint = Endpoint, apiModel = ApiModel, description = Description }, apiKey: ReadApiKey?.Invoke());
});
ApproveCommand = Command(() => Update("reviewed"));
ApproveAllCommand = Command(ApproveAll);
AbsentCommand = Command(() => Update("absent"));
ExcludeCommand = Command(() => Update("excluded"));
PreviousCommand = Command(() => Move(-1));
NextCommand = Command(() => Move(1));
CancelCommand = new DelegateCommand(() => _cancellation?.Cancel());
RevealCommand = Command(() => Process.Start(new ProcessStartInfo("explorer.exe") { ArgumentList = { _project?.DirectoryPath ?? Root }, UseShellExecute = true }));
}
private DelegateCommand Command(Action action)
{
var command = new DelegateCommand(() => { try { action(); } catch (Exception e) { Status = e.Message; Append(e.Message); } }, () => !IsBusy);
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); }
}, () => !IsBusy);
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 = Model, device = Device,
outputDirectory = TrainingOutputDirectory };
private TrainingProject RequireProject() => _project ?? throw new InvalidOperationException("请先导入视频或打开项目");
private void SaveLabel()
{
var project = RequireProject();
if (string.IsNullOrWhiteSpace(Label)) throw new ArgumentException("请填写零件类别名称");
project.Name = Label.Trim(); project.Save();
}
private async void Import()
{
try
{
var video = new OpenFileDialog { Filter = "视频|*.mp4;*.avi;*.mov;*.mkv;*.wmv|所有文件|*.*" };
if (video.ShowDialog() != true) return;
var folder = new OpenFolderDialog { Title = "选择项目保存的父文件夹(会自动新建子文件夹)" };
if (folder.ShowDialog() != true) return;
if (string.IsNullOrWhiteSpace(Label)) throw new ArgumentException("请填写零件类别名称");
var output = Path.Combine(folder.FolderName, "part-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + "-" + Guid.NewGuid().ToString("N")[..4]);
if (await Run(new { action = "extract", video = video.FileName, output, name = Label.Trim(), stride = ExtractStride, maxFrames = MaxFrames }, reload: false))
Load(Path.Combine(output, "project.json"));
}
catch (Exception e) { Status = e.Message; Append(e.Message); }
}
public void Load(string path, int index = 0)
{
_project = TrainingProject.Load(path);
Label = _project.Name; RaisePropertyChanged(nameof(Label));
_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
{
_project.ValidateBox(box); SelectedFrame.Box = box; SelectedFrame.Prompt = true;
SelectedFrame.Status = "reviewed"; _project.Save(); Refresh();
Status = "关键帧已保存;可再选其他角度画框,或开始 SAM2 传播";
}
catch (Exception e) { Status = e.Message; }
}
private void Update(string status)
{
if (SelectedFrame == null) return;
if (status == "reviewed" && SelectedFrame.Box == null) throw new InvalidOperationException("该帧没有目标框,请画框或标记无目标");
SelectedFrame.Status = status;
if (status != "reviewed") { SelectedFrame.Box = null; SelectedFrame.Prompt = false; }
RequireProject().Save(); Refresh();
Status = "当前帧已保存";
}
private void ApproveAll()
{
var project = RequireProject();
var pending = project.Frames.Where(frame => frame.Status == "auto" && frame.Box != null).ToList();
// Validate the whole batch before changing any annotation status.
foreach (var frame in pending) project.ValidateBox(frame.Box!);
if (pending.Count == 0) { Status = "没有带目标框的待复核帧"; return; }
var selectedIndex = SelectedFrame?.Index ?? 0;
foreach (var frame in pending) frame.Status = "reviewed";
try { project.Save(); }
catch
{
foreach (var frame in pending) frame.Status = "auto";
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));
}
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)
{
Application.Current.Dispatcher.Invoke(() =>
{
Logs += line + Environment.NewLine;
if (Logs.Length > 40000) Logs = Logs[^30000..];
});
}
private async Task<bool> Run(object request, bool reload = true, string? apiKey = null)
{
if (IsBusy) return false;
IsTraining = JsonSerializer.SerializeToElement(request).GetProperty("action").GetString() == "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;
try
{
SaveSettings();
await _worker.RunAsync(Python.Trim(), Path.Combine(Root, "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);
Application.Current.Dispatcher.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("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);
Progress = 100; return true;
}
catch (OperationCanceledException) { 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
{
if (reload && path != null)
{
try { Load(path, index); } catch (Exception e) { Append("重新读取项目失败:" + e.Message); }
}
_cancellation.Dispose(); _cancellation = null; IsBusy = false; IsTraining = false;
_completion.TrySetResult();
}
}
public void Cancel() => _cancellation?.Cancel();
public async Task StopAsync()
{
Cancel();
if (_completion != null) await _completion.Task;
}
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 = ""; TrainingRunDirectory = ""; TrainingMetrics = "尚无训练指标";
var file = Path.Combine(RequireProject().DirectoryPath, "latest-model.json");
if (!File.Exists(file)) return;
try
{
using var result = JsonDocument.Parse(File.ReadAllText(file));
LatestWeights = result.RootElement.GetProperty("weights").GetString() ?? "";
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()
{
Directory.CreateDirectory(Path.Combine(Root, "workspace"));
File.WriteAllText(Path.Combine(Root, "workspace", "settings.json"), JsonSerializer.Serialize(new
{ Python, Checkpoint, SamConfig, Device, ExportEvery, Epochs, Batch, ImageSize, Model, TrainingOutputDirectory, Endpoint, ApiModel, Description, ExtractStride, MaxFrames }));
}
private void LoadSettings()
{
var path = Path.Combine(Root, "workspace", "settings.json");
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?.CanWrite == true && property.PropertyType == typeof(string)) property.SetValue(this, item.Value.GetString());
else if (property?.CanWrite == true && property.PropertyType == typeof(int)) property.SetValue(this, item.Value.GetInt32());
}
}
catch (Exception) { Status = "设置文件不可读,已使用默认配置"; }
}
}

View File

@ -0,0 +1,114 @@
using System.IO;
using System.Text.Json;
using System.Windows;
using System.Windows.Media.Imaging;
using Microsoft.Win32;
using SopHelper.Engine.Training;
using Prism.Commands;
using Prism.Mvvm;
namespace SopHelper.Training;
public sealed class ModelTestViewModel : BindableBase
{
private readonly string _root;
private readonly string _python;
private readonly WorkerClient _worker;
private CancellationTokenSource? _stop;
private Task _running = Task.CompletedTask;
private bool _busy;
private string _video = "", _model = "", _status = "选择视频和检测模型,点击开始";
private string _detections = "尚无检测结果", _position = "", _logs = "";
private BitmapImage? _preview;
private double _progress;
public bool IsBusy { get => _busy; private set { SetProperty(ref _busy, value); RaisePropertyChanged(nameof(IsIdle)); UpdateCommands(); } }
public bool IsIdle => !IsBusy;
public string VideoPath { get => _video; set { SetProperty(ref _video, value); UpdateCommands(); } }
public string ModelPath { get => _model; set { SetProperty(ref _model, value); UpdateCommands(); } }
public double Confidence { get; set; } = 0.25;
public string Device { get; set; } = "auto";
public int ImageSize { get; set; } = 640;
public string Status { get => _status; private set => SetProperty(ref _status, value); }
public string Detections { get => _detections; private set => SetProperty(ref _detections, value); }
public string Position { get => _position; private set => SetProperty(ref _position, value); }
public string Logs { get => _logs; private set => SetProperty(ref _logs, value); }
public BitmapImage? Preview { get => _preview; private set => SetProperty(ref _preview, value); }
public double Progress { get => _progress; private set => SetProperty(ref _progress, value); }
public DelegateCommand ChooseVideoCommand { get; }
public DelegateCommand ChooseModelCommand { get; }
public DelegateCommand StartCommand { get; }
public DelegateCommand StopCommand { get; }
public ModelTestViewModel(string root, string python, WorkerClient? worker = null)
{
_root = root; _python = python; _worker = worker ?? new WorkerClient();
ChooseVideoCommand = new DelegateCommand(() =>
{
var picker = new OpenFileDialog { Filter = "视频|*.mp4;*.avi;*.mov;*.mkv;*.wmv|所有文件|*.*" };
if (picker.ShowDialog() == true) VideoPath = picker.FileName;
}, () => IsIdle);
ChooseModelCommand = new DelegateCommand(() =>
{
var picker = new OpenFileDialog { Filter = "YOLO检测模型|*.pt;*.onnx" };
if (picker.ShowDialog() == true) ModelPath = picker.FileName;
}, () => IsIdle);
StartCommand = new DelegateCommand(() => _running = PlayAsync(), () => IsIdle && File.Exists(VideoPath) && File.Exists(ModelPath));
StopCommand = new DelegateCommand(() => _stop?.Cancel(), () => IsBusy);
}
private void UpdateCommands()
{
ChooseVideoCommand?.RaiseCanExecuteChanged(); ChooseModelCommand?.RaiseCanExecuteChanged();
StartCommand?.RaiseCanExecuteChanged(); StopCommand?.RaiseCanExecuteChanged();
}
private async Task PlayAsync()
{
if (IsBusy) return;
IsBusy = true; Preview = null; Progress = 0; Position = ""; Detections = "等待检测画面";
Status = "正在加载模型…"; Logs = "";
using var stop = new CancellationTokenSource(); _stop = stop;
string? lastError = null;
try
{
await _worker.RunAsync(_python, Path.Combine(_root,"tools","worker.py"), new
{ action = "test_video", video = VideoPath, model = ModelPath, confidence = Confidence, device = Device, imageSize = ImageSize }, line =>
{
using var json = Parse(line);
var item = json?.RootElement;
Application.Current.Dispatcher.Invoke(() =>
{
if (item is { ValueKind: JsonValueKind.Object } data && data.TryGetProperty("event", out var kind) && kind.GetString() == "test_frame")
{
try
{
using var stream = new MemoryStream(Convert.FromBase64String(data.GetProperty("image").GetString()!));
var bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream; bitmap.EndInit(); bitmap.Freeze(); Preview = bitmap;
var frame = data.GetProperty("frame").GetInt32();
var total = data.GetProperty("totalFrames").GetInt32();
var seconds = data.GetProperty("seconds").GetDouble();
Position = $"{seconds:F1} / {data.GetProperty("duration").GetDouble():F1} 秒 · 帧 {frame}/{total} · {data.GetProperty("processingFps").GetDouble():F1} fps";
Progress = total > 0 ? Math.Clamp(frame * 100.0 / total,0,100) : 0;
var targets = data.GetProperty("detections").EnumerateArray().ToList();
Detections = targets.Count == 0 ? "当前帧未检测到目标" : string.Join(Environment.NewLine, targets.Select(d => $"{d.GetProperty("label").GetString()} {d.GetProperty("confidence").GetDouble():P1}"));
Status = $"正在播放检测 · {targets.Count} 个目标";
}
catch (Exception e) { lastError = "检测画面读取失败:" + e.Message; stop.Cancel(); }
return;
}
var message = item is { ValueKind: JsonValueKind.Object } obj && obj.TryGetProperty("message",out var m) ? m.GetString() ?? line : line;
if (item is { ValueKind: JsonValueKind.Object } error && error.TryGetProperty("error",out var flag) && flag.ValueKind == JsonValueKind.True) lastError = message;
Status = message; Logs += message + Environment.NewLine;
if (Logs.Length > 15000) Logs = Logs[^12000..];
});
}, stop.Token);
}
catch (OperationCanceledException) { Status = lastError ?? "已停止播放检测"; }
catch (Exception e) { Status = lastError ?? e.Message; Logs += Status + Environment.NewLine; }
finally { _stop = null; IsBusy = false; }
}
private static JsonDocument? Parse(string line)
{
try { return JsonDocument.Parse(line); } catch (JsonException) { return null; }
}
public async Task StopAsync() { _stop?.Cancel(); await _running; }
}

View File

@ -0,0 +1,27 @@
<Window x:Class="SopHelper.Training.ModelTestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="SopHelper · 测试模型" Width="1200" Height="820" MinWidth="960" MinHeight="680" WindowStartupLocation="CenterOwner">
<Window.Resources><ResourceDictionary Source="/SopHelper;component/Training/Styles.xaml"/></Window.Resources>
<Grid Margin="18">
<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/><RowDefinition Height="80"/></Grid.RowDefinitions>
<TextBlock Text="测试模型" FontSize="22" FontWeight="Bold" Foreground="{StaticResource Accent}" Margin="0,0,0,15"/>
<StackPanel Grid.Row="1">
<Grid IsEnabled="{Binding IsIdle}"><Grid.ColumnDefinitions><ColumnDefinition Width="Auto"/><ColumnDefinition Width="*"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition/><RowDefinition/></Grid.RowDefinitions>
<TextBlock Text="视频" Margin="0,0,12,0"/><TextBox Grid.Column="1" Text="{Binding VideoPath, UpdateSourceTrigger=PropertyChanged}"/><Button Grid.Column="2" Content="选择视频…" Command="{Binding ChooseVideoCommand}" Margin="10,4,0,10"/>
<TextBlock Grid.Row="1" Text="模型" Margin="0,0,12,0"/><TextBox Grid.Row="1" Grid.Column="1" Text="{Binding ModelPath, UpdateSourceTrigger=PropertyChanged}"/><Button Grid.Row="1" Grid.Column="2" Content="选择模型…" Command="{Binding ChooseModelCommand}" Margin="10,4,0,10"/>
</Grid>
<WrapPanel>
<TextBlock Text="置信度(0–1)" Margin="0,0,8,6"/><TextBox Text="{Binding Confidence}" Width="65" IsEnabled="{Binding IsIdle}"/>
<TextBlock Text="设备" Margin="16,0,8,6"/><TextBox Text="{Binding Device}" Width="70" IsEnabled="{Binding IsIdle}" ToolTip="auto、cpu或GPU编号0"/>
<Button Content="开始" Command="{Binding StartCommand}" BorderBrush="{StaticResource Accent}" Margin="16,0,6,6"/><Button Content="停止" Command="{Binding StopCommand}"/>
<TextBlock Text="逐帧播放检测画面,无音频;推理较慢时播放会相应变慢。" Foreground="{StaticResource Dim}" Margin="12,0,0,6"/>
</WrapPanel>
</StackPanel>
<Grid Grid.Row="2" Margin="0,6,0,10"><Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="14"/><ColumnDefinition Width="200"/></Grid.ColumnDefinitions>
<Border Background="#080E14" BorderBrush="{StaticResource Line}" BorderThickness="1" CornerRadius="6"><Image Source="{Binding Preview}" Stretch="Uniform"/></Border>
<DockPanel Grid.Column="2"><TextBlock DockPanel.Dock="Top" Text="当前帧检测目标" FontWeight="Bold" Margin="0,0,0,10"/><ScrollViewer VerticalScrollBarVisibility="Auto"><TextBlock Text="{Binding Detections}" TextWrapping="Wrap" VerticalAlignment="Top"/></ScrollViewer></DockPanel>
</Grid>
<StackPanel Grid.Row="3"><ProgressBar Height="6" Value="{Binding Progress, Mode=OneWay}" Foreground="{StaticResource Accent}" Background="{StaticResource Line}"/><TextBlock Text="{Binding Position}" Margin="0,8,0,5"/><TextBlock Text="{Binding Status}" TextWrapping="Wrap" Margin="0,0,0,8"/></StackPanel>
<TextBox Grid.Row="4" Text="{Binding Logs, Mode=OneWay}" IsReadOnly="True" VerticalScrollBarVisibility="Auto" TextWrapping="Wrap"/>
</Grid>
</Window>

View File

@ -0,0 +1,23 @@
using System.ComponentModel;
using System.Windows;
namespace SopHelper.Training;
public partial class ModelTestWindow : Window
{
public ModelTestViewModel Model { get; }
private bool _closing, _closedSafely;
public ModelTestWindow(ModelTestViewModel model)
{
InitializeComponent(); Model = model; DataContext = model;
}
protected override async void OnClosing(CancelEventArgs e)
{
if (_closedSafely) { base.OnClosing(e); return; }
e.Cancel = true; base.OnClosing(e);
if (_closing) return;
_closing = true; IsEnabled = false;
await Model.StopAsync();
_ = Dispatcher.BeginInvoke(() => { _closedSafely = true; Close(); });
}
}

View File

@ -0,0 +1,32 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="Bg" Color="#101820"/>
<SolidColorBrush x:Key="Panel" Color="#16222E"/>
<SolidColorBrush x:Key="Line" Color="#2C4257"/>
<SolidColorBrush x:Key="Fg" Color="#DCEBF5"/>
<SolidColorBrush x:Key="Dim" Color="#8FAFC4"/>
<SolidColorBrush x:Key="Accent" Color="#00B8D4"/>
<Style TargetType="Window"><Setter Property="FontFamily" Value="Microsoft YaHei"/><Setter Property="Background" Value="{StaticResource Bg}"/><Setter Property="Foreground" Value="{StaticResource Fg}"/></Style>
<Style TargetType="TextBlock"><Setter Property="Foreground" Value="{StaticResource Fg}"/><Setter Property="VerticalAlignment" Value="Center"/><Setter Property="FontSize" Value="13"/></Style>
<Style x:Key="Hint" TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}"><Setter Property="Foreground" Value="{StaticResource Dim}"/><Setter Property="TextWrapping" Value="Wrap"/><Setter Property="Margin" Value="0,6,0,12"/><Setter Property="LineHeight" Value="21"/></Style>
<Style TargetType="Button">
<Setter Property="Foreground" Value="{StaticResource Fg}"/><Setter Property="Background" Value="{StaticResource Panel}"/><Setter Property="BorderBrush" Value="{StaticResource Line}"/><Setter Property="Padding" Value="12,8"/><Setter Property="Margin" Value="0,0,6,6"/><Setter Property="Cursor" Value="Hand"/>
<Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Button"><Border x:Name="body" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1" CornerRadius="5" Padding="{TemplateBinding Padding}"><ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/></Border><ControlTemplate.Triggers><Trigger Property="IsMouseOver" Value="True"><Setter TargetName="body" Property="BorderBrush" Value="{StaticResource Accent}"/></Trigger><Trigger Property="IsEnabled" Value="False"><Setter Property="Opacity" Value="0.35"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter>
</Style>
<Style TargetType="TextBox"><Setter Property="Foreground" Value="{StaticResource Fg}"/><Setter Property="Background" Value="#101820"/><Setter Property="BorderBrush" Value="{StaticResource Line}"/><Setter Property="Padding" Value="7"/><Setter Property="Margin" Value="0,4,0,10"/><Setter Property="CaretBrush" Value="{StaticResource Accent}"/></Style>
<Style TargetType="PasswordBox"><Setter Property="Foreground" Value="{StaticResource Fg}"/><Setter Property="Background" Value="#101820"/><Setter Property="BorderBrush" Value="{StaticResource Line}"/><Setter Property="Padding" Value="7"/><Setter Property="Margin" Value="0,4,0,10"/></Style>
<Style TargetType="TabControl"><Setter Property="Background" Value="{StaticResource Panel}"/><Setter Property="BorderBrush" Value="{StaticResource Line}"/><Setter Property="Padding" Value="12"/></Style>
<Style TargetType="TabItem"><Setter Property="Foreground" Value="{StaticResource Dim}"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="TabItem"><Border x:Name="tab" Padding="14,10" Background="#101820"><ContentPresenter ContentSource="Header"/></Border><ControlTemplate.Triggers><Trigger Property="IsSelected" Value="True"><Setter Property="Foreground" Value="{StaticResource Accent}"/><Setter TargetName="tab" Property="Background" Value="#16222E"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style>
<Style TargetType="ListBox"><Setter Property="Background" Value="#101820"/><Setter Property="Foreground" Value="{StaticResource Fg}"/><Setter Property="BorderBrush" Value="{StaticResource Line}"/><Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/></Style>
<Style TargetType="ListBoxItem"><Setter Property="Padding" Value="10,8"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="ListBoxItem"><Border x:Name="item" Background="Transparent" Padding="{TemplateBinding Padding}"><ContentPresenter/></Border><ControlTemplate.Triggers><Trigger Property="IsSelected" Value="True"><Setter TargetName="item" Property="Background" Value="#204B5C"/></Trigger><Trigger Property="IsMouseOver" Value="True"><Setter Property="Foreground" Value="{StaticResource Accent}"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style>
<Style TargetType="ComboBox">
<Setter Property="Foreground" Value="{StaticResource Fg}"/>
<Setter Property="Template"><Setter.Value><ControlTemplate TargetType="ComboBox"><Grid>
<ToggleButton Focusable="False" ClickMode="Press" IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}">
<ToggleButton.Template><ControlTemplate TargetType="ToggleButton"><Border Background="{StaticResource Panel}" BorderBrush="{StaticResource Line}" BorderThickness="1" CornerRadius="4"><Path HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,10,0" Data="M 0 0 L 8 0 L 4 5 Z" Fill="{StaticResource Dim}"/></Border></ControlTemplate></ToggleButton.Template>
</ToggleButton>
<ContentPresenter Margin="10,0,28,0" VerticalAlignment="Center" Content="{TemplateBinding SelectionBoxItem}" ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" IsHitTestVisible="False"/>
<Popup x:Name="PART_Popup" IsOpen="{TemplateBinding IsDropDownOpen}" Placement="Bottom" AllowsTransparency="True" Focusable="False"><Border Background="{StaticResource Panel}" BorderBrush="{StaticResource Line}" BorderThickness="1" MinWidth="{Binding ActualWidth, RelativeSource={RelativeSource TemplatedParent}}"><ScrollViewer MaxHeight="240"><ItemsPresenter/></ScrollViewer></Border></Popup>
</Grid><ControlTemplate.Triggers><Trigger Property="IsEnabled" Value="False"><Setter Property="Opacity" Value="0.4"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter>
</Style>
<Style TargetType="ComboBoxItem"><Setter Property="Foreground" Value="{StaticResource Fg}"/><Setter Property="Padding" Value="10,8"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="ComboBoxItem"><Border x:Name="row" Background="Transparent" Padding="{TemplateBinding Padding}"><ContentPresenter/></Border><ControlTemplate.Triggers><Trigger Property="IsHighlighted" Value="True"><Setter TargetName="row" Property="Background" Value="#204B5C"/></Trigger><Trigger Property="IsSelected" Value="True"><Setter TargetName="row" Property="Background" Value="#204B5C"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style>
</ResourceDictionary>

View File

@ -0,0 +1,78 @@
<UserControl x:Class="SopHelper.Training.TrainingPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SopHelper.Training"
>
<UserControl.Resources><ResourceDictionary Source="/SopHelper;component/Training/Styles.xaml"/></UserControl.Resources>
<ScrollViewer Margin="12" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
<Grid Height="{Binding ViewportHeight, RelativeSource={RelativeSource AncestorType=ScrollViewer}}" MinWidth="1080" MinHeight="720">
<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="176"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>
<DockPanel Margin="0,0,0,14">
<StackPanel DockPanel.Dock="Left" Margin="0,0,28,0"><TextBlock Text="零件标注与训练" FontSize="23" FontWeight="Bold" Foreground="{StaticResource Accent}"/><TextBlock Text="视频 → 标注 → 复核 → YOLO" Foreground="{StaticResource Dim}"/></StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Center"><Button Content="测试模型" Click="OpenModelTestClicked"/><Button Content="相机与录像" Click="OpenCameraClicked"/><Button Content="导入视频" Command="{Binding ImportCommand}"/><Button Content="打开项目" Command="{Binding OpenCommand}"/><Button Content="项目文件夹" Command="{Binding RevealCommand}"/><Button Content="取消任务" Command="{Binding CancelCommand}" IsEnabled="{Binding IsBusy}"/></StackPanel>
</DockPanel>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions><ColumnDefinition Width="220"/><ColumnDefinition Width="12"/><ColumnDefinition Width="*"/><ColumnDefinition Width="12"/><ColumnDefinition Width="330"/></Grid.ColumnDefinitions>
<DockPanel>
<StackPanel DockPanel.Dock="Top" Margin="0,0,0,10"><TextBlock Text="视频帧" FontSize="16" FontWeight="Bold"/><TextBlock Text="{Binding Summary}" Style="{StaticResource Hint}"/></StackPanel>
<ListBox ItemsSource="{Binding Frames}" SelectedItem="{Binding SelectedFrame}" IsEnabled="{Binding IsIdle}" VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling"><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">
<local:AnnotationCanvas x:Name="Canvas" Source="{Binding Preview}" Box="{Binding CurrentBox}" IsEnabled="{Binding IsIdle}"/>
</Border>
<WrapPanel Grid.Row="2" Margin="0,12,0,0"><Button Content="← 上一帧" Command="{Binding PreviousCommand}"/><Button Content="下一帧 →" Command="{Binding NextCommand}"/><Button Content="确认当前框" Command="{Binding ApproveCommand}"/><Button Content="一键复核" Command="{Binding ApproveAllCommand}" ToolTip="确认本项目中所有带目标框的待复核帧,并立即保存"/><Button Content="无目标" Command="{Binding AbsentCommand}"/><Button Content="排除此帧" Command="{Binding ExcludeCommand}"/></WrapPanel>
<TextBlock Grid.Row="3" Style="{StaticResource Hint}" Text="拖动画框或修正,自动保存为关键帧。← → 切帧,Enter 确认当前框并进入下一帧。"/>
</Grid>
<TabControl Grid.Column="4" IsEnabled="{Binding IsIdle}">
<TabItem Header="标注"><ScrollViewer VerticalScrollBarVisibility="Auto"><StackPanel>
<TextBlock Text="01 导入旋转视频" FontWeight="Bold" Foreground="{StaticResource Accent}"/>
<TextBlock Text="零件类别名称" Margin="0,12,0,0"/><TextBox Text="{Binding Label, UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Text="抽帧间隔(原视频帧数)"/><TextBox Text="{Binding ExtractStride}"/>
<TextBlock Text="最多导入帧数"/><TextBox Text="{Binding MaxFrames}"/>
<TextBlock Style="{StaticResource Hint}" Text="默认最多600帧;长视频会自动增大间隔覆盖全片。快速旋转建议分成短片导入。"/>
<TextBlock Text="02 画框并自动传播" FontWeight="Bold" Foreground="{StaticResource Accent}" Margin="0,10,0,8"/>
<Button Content="开始 SAM2 传播" Command="{Binding PropagateCommand}" BorderBrush="{StaticResource Accent}"/>
<TextBlock Style="{StaticResource Hint}" Text="先在清晰帧画一个框。旋转幅度大时,可在多个角度补框后再运行。传播保留已复核帧。"/>
<TextBlock Text="03 人工复核" FontWeight="Bold" Foreground="{StaticResource Accent}"/>
<TextBlock Style="{StaticResource Hint}" Text="逐帧确认目标框;框偏了直接重画。无目标用于负样本,排除帧不参与训练。只导出已复核数据。"/>
</StackPanel></ScrollViewer></TabItem>
<TabItem Header="训练"><ScrollViewer VerticalScrollBarVisibility="Auto"><StackPanel>
<TextBlock Text="YOLO 目标检测训练" FontSize="16" FontWeight="Bold"/>
<TextBlock Style="{StaticResource Hint}" Text="按时间分段:前段训练、末尾20%验证,边界留出间隔。正式评估请另拍独立测试视频。"/>
<TextBlock Text="训练抽样间隔(导入后的帧数)"/><TextBox Text="{Binding ExportEvery}"/>
<TextBlock Text="YOLO 初始模型 / 本地 .pt 路径"/><TextBox Text="{Binding Model}"/>
<TextBlock Text="训练轮数"/><TextBox Text="{Binding Epochs}"/>
<TextBlock Text="图像尺寸(32的倍数)"/><TextBox Text="{Binding ImageSize}"/>
<TextBlock Text="批次大小"/><TextBox Text="{Binding Batch}"/>
<Button Content="导出 YOLO 数据集" Command="{Binding ExportCommand}"/>
<Button Content="开始训练" Command="{Binding TrainCommand}" BorderBrush="{StaticResource Accent}"/>
<Button Content="导出最新模型为 ONNX" Command="{Binding OnnxCommand}"/>
<TextBlock Style="{StaticResource Hint}" Text="每次训练重新导出当前复核数据。best.pt、ONNX 和训练指标保存在项目 runs 文件夹。默认 yolo11n,检测框格式便于接入 SopHelper,仍需现场验证。"/>
</StackPanel></ScrollViewer></TabItem>
<TabItem Header="设置"><ScrollViewer VerticalScrollBarVisibility="Auto"><StackPanel>
<TextBlock Text="Python 运行环境" FontWeight="Bold"/>
<TextBox Text="{Binding Python}" ToolTip="Python 可执行文件完整路径"/>
<Button Content="检查环境与 CUDA" Command="{Binding DoctorCommand}"/>
<TextBlock Text="设备:auto / cpu / cuda(训练可填0)"/><TextBox Text="{Binding Device}"/>
<TextBlock Text="SAM2 checkpoint(留空自动下载 tiny)"/><TextBox Text="{Binding Checkpoint}"/>
<TextBlock Text="SAM2 配置(仅本地 checkpoint 使用)"/><TextBox Text="{Binding SamConfig}"/>
<TextBlock Text="可选:视觉大模型建议框" FontWeight="Bold" Margin="0,12,0,0"/>
<TextBlock Style="{StaticResource Hint}" Text="兼容 chat/completions 的视觉接口。点击时会上传当前帧到下方地址;结果需人工确认,再用于 SAM2 传播。"/>
<TextBlock Text="API Base URL(包含 /v1,不含 /chat/completions)"/><TextBox Text="{Binding Endpoint}"/>
<TextBlock Text="视觉模型名称"/><TextBox Text="{Binding ApiModel}"/>
<TextBlock Text="API Key(仅本次运行,不写入项目)"/><PasswordBox x:Name="ApiKey"/>
<TextBlock Text="零件外观描述"/><TextBox Text="{Binding Description}" 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" 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>

View File

@ -0,0 +1,94 @@
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using SopHelper.Core.Prism;
using SopHelper.Engine.Camera;
using SopHelper.VVMs.SopPage;
namespace SopHelper.Training;
[NavigationPage(ViewName = nameof(TrainingPage), DisplayName = "零件标注与训练", Index = 1)]
public partial class TrainingPage : UserControl
{
private readonly MainViewModel _model;
private readonly SopPageViewModel? _sop;
private CameraWindow? _cameraWindow;
private ModelTestWindow? _testWindow;
private Window? _host;
private bool _closing;
private bool _closedSafely;
public TrainingPage(MainViewModel model, SopPageViewModel? sop)
{
InitializeComponent();
_model = model; _sop = sop; DataContext = model;
Canvas.BoxDrawn += model.DrawBox;
model.ReadApiKey = () => ApiKey.Password;
Loaded += (_, _) =>
{
// Keep this handler when navigating away: background work still belongs to the shell.
if (_host != null || Window.GetWindow(this) is not { } host) return;
_host = host; host.Closing += HostClosing;
};
PreviewKeyDown += (_, e) =>
{
if (model.IsBusy || Keyboard.FocusedElement is TextBoxBase or PasswordBox) 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.SelectedFrame?.Box != null)
{
model.ApproveCommand.Execute(); model.NextCommand.Execute(); e.Handled = true;
}
};
}
private void OpenModelTestClicked(object sender, RoutedEventArgs e)
{
if (_testWindow != null) { _testWindow.Activate(); return; }
var test = new ModelTestViewModel(_model.Root, _model.Python, _model.Worker) { Device = _model.Device, ImageSize = _model.ImageSize };
if (System.IO.File.Exists(_model.Project?.Video)) test.VideoPath = _model.Project.Video;
if (System.IO.File.Exists(_model.LatestWeights)) test.ModelPath = _model.LatestWeights;
else if (System.IO.File.Exists(_model.Model)) test.ModelPath = _model.Model;
_testWindow = new ModelTestWindow(test) { Owner = Window.GetWindow(this) };
_testWindow.Closed += (_, _) => _testWindow = null;
_testWindow.Show();
}
private void OpenCameraClicked(object sender, RoutedEventArgs e)
{
if (_sop is { CanSelectCamera: false } || _sop is { IsConnected: true })
{
_model.Status = "请先停止 SOP 采集并等待相机操作完成,再打开录像";
return;
}
_cameraWindow = new CameraWindow(new CameraViewModel(new CameraService(), _model.Root)) { Owner = Window.GetWindow(this) };
// A modal capture session prevents SOP or recipe calibration from opening the same device.
try { _cameraWindow.ShowDialog(); }
finally { _cameraWindow = null; }
}
public async Task ShutdownAsync()
{
await _model.StopAsync();
if (_testWindow != null) await _testWindow.Model.StopAsync();
if (_cameraWindow != null) await _cameraWindow.Model.ShutdownAsync();
}
private async void HostClosing(object? sender, CancelEventArgs e)
{
if (_closedSafely) return;
e.Cancel = true;
if (_closing) return;
_closing = true;
_host!.IsEnabled = false;
try { await ShutdownAsync(); }
catch (Exception error) { MessageBox.Show(_host, "关闭训练任务时出错:" + error.Message, "SopHelper"); }
_closedSafely = true;
// Even an idle workspace can complete synchronously inside the first Closing event.
_ = Dispatcher.BeginInvoke(() => _host.Close());
}
private void LogChanged(object sender, TextChangedEventArgs e) => ((TextBox)sender).ScrollToEnd();
}

View File

@ -0,0 +1,110 @@
using System.Diagnostics;
using OpenCvSharp;
namespace SopHelper.Engine.Camera;
public sealed record RecordingResult(string Path, long Frames, double Fps)
{
public TimeSpan Duration => TimeSpan.FromSeconds(Frames / Fps);
}
/// <summary>Thread-safe, bounded-memory MJPEG recording with wall-clock frame pacing.</summary>
public sealed class VideoRecorder : IDisposable
{
private readonly object _gate = new();
private readonly Stopwatch _clock = new();
private VideoWriter? _writer;
private Mat? _previous;
private string _path = "";
private long _frames;
private double _fps;
private Size _size;
public bool IsRecording { get { lock (_gate) return _writer != null; } }
public TimeSpan Elapsed { get { lock (_gate) return _writer != null ? _clock.Elapsed : TimeSpan.Zero; } }
public string CurrentPath { get { lock (_gate) return _path; } }
public string Start(string directory, Mat initialFrame, double fps = 30)
{
lock (_gate)
{
if (_writer != null) throw new InvalidOperationException("正在录像,请先停止");
if (!double.IsFinite(fps) || fps < 1 || fps > 120) throw new ArgumentException("录像帧率需在1–120之间");
ValidateFrame(initialFrame);
// AVI codecs use even dimensions; fail explicitly rather than silently crop the image.
if (initialFrame.Width % 2 != 0 || initialFrame.Height % 2 != 0)
throw new ArgumentException("录像画面宽高需为偶数,请调整相机分辨率");
directory = Path.GetFullPath(directory);
Directory.CreateDirectory(directory);
var path = Path.Combine(directory, $"part-{DateTime.Now:yyyyMMdd-HHmmss-fff}-{Guid.NewGuid():N}.avi");
var writer = new VideoWriter();
Mat? previous = null;
try
{
if (!writer.Open(path, FourCC.MJPG, fps, initialFrame.Size()))
throw new IOException("录像编码器无法创建文件,请检查保存目录与磁盘空间");
previous = initialFrame.Clone();
writer.Write(initialFrame);
_size = initialFrame.Size(); _fps = fps; _path = path; _frames = 1;
_previous = previous; _writer = writer; _clock.Restart();
return path;
}
catch
{
previous?.Dispose(); writer.Dispose();
if (File.Exists(path)) File.Delete(path);
throw;
}
}
}
public void Write(Mat frame)
{
lock (_gate)
{
if (_writer == null) return;
try
{
ValidateFrame(frame);
if (frame.Size() != _size) throw new IOException("相机分辨率发生变化,录像已停止");
var target = (long)Math.Floor(_clock.Elapsed.TotalSeconds * _fps);
if (target - _frames > _fps * 2) throw new IOException("相机帧中断超过2秒,录像已停止");
// Repeat the previous frame for slow cameras; skip excess frames for fast cameras.
while (_frames < target) { _writer.Write(_previous!); _frames++; }
if (_frames <= target) { _writer.Write(frame); _frames++; }
frame.CopyTo(_previous!);
}
catch { StopCore(flushTail: false); throw; }
}
}
public RecordingResult? Stop()
{
lock (_gate) return StopCore(flushTail: true);
}
private RecordingResult? StopCore(bool flushTail)
{
if (_writer == null) return null;
var writer = _writer;
_writer = null;
try
{
// Finalize at the wall-clock stop time, including the interval after the last camera frame.
var target = (long)Math.Ceiling(_clock.Elapsed.TotalSeconds * _fps);
if (flushTail && target - _frames <= _fps * 2)
while (_frames < target) { writer.Write(_previous!); _frames++; }
return new RecordingResult(_path, _frames, _fps);
}
finally
{
_clock.Stop();
try { writer.Dispose(); }
finally { _previous?.Dispose(); _previous = null; }
}
}
private static void ValidateFrame(Mat frame)
{
if (frame.Empty() || frame.Type() != MatType.CV_8UC3)
throw new ArgumentException("录像需要非空的8位三通道BGR图像");
}
public void Dispose() => Stop();
}

View File

@ -0,0 +1,62 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace SopHelper.Engine.Training;
public sealed class FrameAnnotation
{
public int Index { get; set; }
public int SourceIndex { get; set; }
public string Image { get; set; } = "";
public double[]? Box { get; set; }
public string Status { get; set; } = "unlabeled";
public bool Prompt { get; set; }
[JsonIgnore] public string Display => $"{Index + 1:0000} · {Status switch { "reviewed" => "已复核", "auto" => "待复核", "absent" => "无目标", "excluded" => "已排除", _ => "未标注" }}{(Prompt ? " · 关键帧" : "")}";
}
public sealed class TrainingProject
{
public string Name { 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)
{
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.Box is { } box) project.ValidateBox(box);
}
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);
}
}

View File

@ -0,0 +1,74 @@
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;
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) { }
}
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); }
}
}

View File

@ -0,0 +1,191 @@
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using OpenCvSharp;
using SopHelper.Training;
using SopHelper.Engine.Camera;
internal static class Program
{
[STAThread]
public static int Main(string[] args)
{
var root = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../../workspace/camera-smoke-" + Guid.NewGuid().ToString("N")));
Directory.CreateDirectory(root);
var app = new SopHelper.App(); app.InitializeComponent();
app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(app.Dispatcher));
try
{
TestRecorder(root);
TestViewModel(root);
TestCloseWhileConnecting(root);
TestStalledCamera(root);
Console.WriteLine("PASS: recording and camera lifecycle checks; artifacts: " + root);
return 0;
}
catch (Exception e) { Console.Error.WriteLine(e); return 1; }
}
private static void Require(bool condition, string error) { if (!condition) throw new Exception(error); }
private static void PumpUntil(Func<bool> ready, int timeout = 5000)
{
var watch = Stopwatch.StartNew();
while (!ready())
{
if (watch.ElapsedMilliseconds > timeout) throw new TimeoutException("Dispatcher test timed out");
Application.Current.Dispatcher.Invoke(() => { }, DispatcherPriority.ApplicationIdle);
Thread.Sleep(10);
}
Application.Current.Dispatcher.Invoke(() => { }, DispatcherPriority.ApplicationIdle);
}
private static void TestRecorder(string root)
{
using var recorder = new VideoRecorder();
using var frame = new Mat(120, 160, MatType.CV_8UC3, new Scalar(30,50,80));
var watch = Stopwatch.StartNew();
var path = recorder.Start(Path.Combine(root, "中文录像目录"), frame);
watch.Restart();
for (var i = 0; i < 10; i++)
{
Thread.Sleep(100); frame.SetTo(new Scalar(30+i*10,50,80)); recorder.Write(frame);
}
var result = recorder.Stop()!;
Require(!recorder.IsRecording && recorder.Stop() == null, "Stop must be idempotent");
Require(Math.Abs(result.Duration.TotalSeconds - watch.Elapsed.TotalSeconds) < 0.2, "Recording duration differs from wall clock");
using (var capture = new VideoCapture(path))
using (var decoded = new Mat())
{
Require(capture.IsOpened() && capture.Read(decoded), "AVI could not be decoded");
Require(decoded.Width == 160 && decoded.Height == 120, "Video resolution changed");
Require(Cv2.Mean(decoded).Val0 > 20, "Video pixels missing");
Require(Math.Abs(capture.Get(VideoCaptureProperties.Fps) - 30) < 0.01, "Unexpected recording FPS");
Require((long)capture.Get(VideoCaptureProperties.FrameCount) == result.Frames, "AVI frame count mismatch");
}
var second = recorder.Start(root, frame); recorder.Stop();
Require(second != path && File.Exists(path) && File.Exists(second), "New recording overwrote the previous file");
recorder.Start(root, frame);
using var changed = new Mat(80, 160, MatType.CV_8UC3, Scalar.Black);
try { recorder.Write(changed); throw new Exception("Resolution change accepted"); }
catch (IOException) { }
Require(!recorder.IsRecording, "Failed writer was not finalized");
using var odd = new Mat(121,161,MatType.CV_8UC3,Scalar.Black);
try { recorder.Start(root, odd); throw new Exception("Odd size accepted"); }
catch (ArgumentException) { }
var file = Path.Combine(root, "not-a-directory"); File.WriteAllText(file, "test");
try { recorder.Start(file, frame); throw new Exception("File accepted as directory"); }
catch (IOException) { }
Require(!recorder.IsRecording, "Failed start changed recording state");
Console.WriteLine($"PASS: real MJPEG encode/decode, Chinese directory, {result.Frames} frames / {result.Duration.TotalSeconds:F2}s, pacing, repeated recordings, failure cleanup");
}
private static void TestViewModel(string root)
{
var fake = new FakeCamera();
var model = new CameraViewModel(fake, root);
Require(!model.RecordCommand.CanExecute(), "Recording enabled without camera");
model.RefreshCommand.Execute(); PumpUntil(() => !model.IsBusy);
Require(model.Cameras.Count == 1 && model.SelectedCamera != null, "Camera list failed");
model.PreviewCommand.Execute(); PumpUntil(() => !model.IsBusy && model.Preview != null);
Require(model.IsPreviewing, "Live preview failed");
model.SaveDirectory = Path.Combine(root,"自选保存位置");
model.RecordCommand.Execute(); PumpUntil(() => !model.IsBusy && model.IsRecording);
Require(!model.CanChooseCamera && !model.CanChangeDirectory && !model.RefreshCommand.CanExecute(), "Controls should be locked while recording");
Thread.Sleep(300);
model.RecordCommand.Execute(); PumpUntil(() => !model.IsBusy && !model.IsRecording);
Require(model.IsPreviewing && model.CanChangeDirectory, "Stop recording should preserve preview and unlock the directory");
var firstRecording = model.LastRecording;
model.RecordCommand.Execute(); PumpUntil(() => !model.IsBusy && model.IsRecording);
Require(model.LastRecording != firstRecording, "Second recording should use a new filename");
Thread.Sleep(300);
var window = new CameraWindow(model);
Render(window, Path.Combine(root, "camera-preview.png"));
var shutdown = model.ShutdownAsync(); PumpUntil(() => shutdown.IsCompleted); shutdown.GetAwaiter().GetResult();
Require(fake.Disposed && !model.IsRecording && !model.IsPreviewing, "Closing did not release camera/recording");
using (var capture = new VideoCapture(model.LastRecording)) Require(capture.IsOpened() && capture.Get(VideoCaptureProperties.FrameCount) > 0, "Close did not finalize AVI");
var closed = false; window.Closed += (_, _) => closed = true;
window.Close(); PumpUntil(() => closed);
var secondFake = new FakeCamera();
var reopened = new CameraViewModel(secondFake, root);
Require(reopened.SaveDirectory == model.SaveDirectory, "Selected recording directory not persisted");
var task = reopened.ShutdownAsync(); PumpUntil(() => task.IsCompleted); task.GetAwaiter().GetResult();
Console.WriteLine("PASS: WPF live preview, directory persistence, record state, closing while recording, preview rendering");
}
private static void TestCloseWhileConnecting(string root)
{
var fake = new FakeCamera { ConnectDelay = 200 };
var model = new CameraViewModel(fake, root) { SelectedCamera = new CameraInfo { Name = "Test" } };
model.PreviewCommand.Execute();
var close = model.ShutdownAsync(); PumpUntil(() => close.IsCompleted); close.GetAwaiter().GetResult();
Require(fake.Disposed && fake.Starts == 0 && !fake.IsGrabbing, "Pending connect reopened camera after close");
Console.WriteLine("PASS: close waits for pending connection and prevents late acquisition");
}
private static void TestStalledCamera(string root)
{
var fake = new FakeCamera();
var model = new CameraViewModel(fake, root) { SelectedCamera = new CameraInfo { Name = "Test" } };
model.PreviewCommand.Execute(); PumpUntil(() => !model.IsBusy && model.Preview != null);
model.RecordCommand.Execute(); PumpUntil(() => model.IsRecording && !model.IsBusy);
fake.PauseFrames = true;
PumpUntil(() => !model.IsRecording, 4000);
Require(!model.RecordCommand.CanExecute(), "Recording enabled on stale preview");
var close = model.ShutdownAsync(); PumpUntil(() => close.IsCompleted); close.GetAwaiter().GetResult();
using var capture = new VideoCapture(model.LastRecording);
Require(capture.IsOpened(), "Stall did not finalize recording");
Console.WriteLine("PASS: stalled camera automatically stops and finalizes recording, stale preview cannot start a new recording");
}
private static void Render(CameraWindow window, string path)
{
var content = (FrameworkElement)window.Content; window.Content = null;
content.DataContext = window.Model; content.Margin = new Thickness(0);
content.Width = 1044; content.Height = 744;
content.Measure(new System.Windows.Size(1044,744)); content.Arrange(new System.Windows.Rect(0,0,1044,744));
content.Dispatcher.Invoke(() => { }, DispatcherPriority.ApplicationIdle); content.UpdateLayout();
var bitmap = new RenderTargetBitmap(1044,744,96,96,PixelFormats.Pbgra32); bitmap.Render(content);
var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap));
using var stream = File.Create(path); encoder.Save(stream);
}
}
internal sealed class FakeCamera : ICameraService
{
private CancellationTokenSource? _stop;
private Task? _loop;
public bool IsConnected { get; private set; }
public bool IsGrabbing { get; private set; }
public bool Disposed { get; private set; }
public int ConnectDelay { get; init; }
public int Starts { get; private set; }
public volatile bool PauseFrames;
public event Action<CameraFrame>? FrameArrived;
public event Action<bool>? ConnectionChanged;
public event Action<string>? Error { add { } remove { } }
public Task<List<CameraInfo>> EnumerateAsync() => Task.FromResult(new List<CameraInfo> { new() { Name = "模拟 UVC 相机 · 160×120" } });
public async Task<bool> ConnectAsync(CameraInfo info)
{
if (ConnectDelay > 0) await Task.Delay(ConnectDelay);
IsConnected = true; ConnectionChanged?.Invoke(true); return true;
}
public Task<bool> StartAsync()
{
Starts++; IsGrabbing = true; _stop = new CancellationTokenSource();
var token = _stop.Token;
_loop = Task.Run(() =>
{
long index = 0;
while (!token.IsCancellationRequested)
{
if (PauseFrames) { Thread.Sleep(33); continue; }
var image = new Mat(120,160,MatType.CV_8UC3,new Scalar(40,60,80));
Cv2.Rectangle(image, new OpenCvSharp.Rect(30,25,90,60), new Scalar(170,190,210), -1);
using var frame = new CameraFrame { Bgr = image, FrameId = index++, Timestamp = DateTime.Now };
FrameArrived?.Invoke(frame); Thread.Sleep(33);
}
});
return Task.FromResult(true);
}
public void Stop() { _stop?.Cancel(); _loop?.GetAwaiter().GetResult(); _stop?.Dispose(); _stop = null; _loop = null; IsGrabbing = false; }
public void Disconnect() { Stop(); IsConnected = false; ConnectionChanged?.Invoke(false); }
public void Dispose() { Disconnect(); Disposed = true; }
}

View File

@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0-windows</TargetFramework><UseWPF>true</UseWPF><PlatformTarget>x64</PlatformTarget><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
<ItemGroup><ProjectReference Include="../../src/SopHelper.App/SopHelper.App.csproj"/></ItemGroup>
</Project>

View File

@ -0,0 +1,77 @@
using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using Prism.Ioc;
using Prism.Navigation.Regions;
using SopHelper.Models;
using SopHelper.Training;
internal static class Program
{
[STAThread]
private static int Main(string[] args)
{
var app = new ShellProbe(args.Contains("--idle"));
app.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("/SopHelper;component/Themes/Styles.xaml", UriKind.Relative) });
return app.Run();
}
}
internal sealed class ShellProbe(bool idle) : SopHelper.App
{
private MainViewModel? _trainer;
protected override void OnInitialized()
{
base.OnInitialized();
Dispatcher.BeginInvoke(async () =>
{
try
{
var navigation = Container.Resolve<NavigationModel>();
var regions = Container.Resolve<IRegionManager>();
if (!navigation.Pages.Any(p => p.ViewName == nameof(TrainingPage))) throw new Exception("Training navigation missing");
navigation.SelectedIndex = 1;
await Dispatcher.InvokeAsync(() => { }, System.Windows.Threading.DispatcherPriority.ApplicationIdle);
var page = regions.Regions[NavigationModel.ContentRegion].ActiveViews.OfType<TrainingPage>().Single();
_trainer = (MainViewModel)page.DataContext;
if (_trainer.Root != Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../..")))
throw new Exception("Training root does not resolve to SopHelper repository");
if (!File.Exists(Path.Combine(_trainer.Root, "tools", "worker.py"))) throw new Exception("Worker missing");
_trainer.Label = "导航状态检查";
navigation.SelectedIndex = 0;
navigation.SelectedIndex = 1;
var restored = regions.Regions[NavigationModel.ContentRegion].ActiveViews.OfType<TrainingPage>().Single();
if (!ReferenceEquals(page, restored) || ((MainViewModel)restored.DataContext).Label != "导航状态检查")
throw new Exception("Navigation lost training state");
MainWindow.UpdateLayout();
var image = new RenderTargetBitmap((int)MainWindow.ActualWidth, (int)MainWindow.ActualHeight, 96, 96, PixelFormats.Pbgra32);
image.Render(MainWindow);
var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(image));
using (var output = File.Create(Path.Combine(Path.GetTempPath(), "sophelper-training-shell.png"))) encoder.Save(output);
Console.WriteLine("PASS: actual Prism shell, navigation registration, DI, repository root, page state retained, shell render");
// Start a real background worker, navigate away, then close the shell.
if (!idle) _trainer.DoctorCommand.Execute();
navigation.SelectedIndex = 0;
MainWindow.Close();
}
catch (Exception error)
{
Console.Error.WriteLine(error);
Shutdown(1);
}
});
}
protected override void OnExit(ExitEventArgs e)
{
if (_trainer?.IsBusy == true)
{
Console.Error.WriteLine("FAIL: shell exited before training worker stopped");
e.ApplicationExitCode = 1;
}
else Console.WriteLine("PASS: shell close after navigating away waits for worker cancellation");
base.OnExit(e);
}
}

View File

@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0-windows</TargetFramework><UseWPF>true</UseWPF><PlatformTarget>x64</PlatformTarget><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
<ItemGroup><ProjectReference Include="../../src/SopHelper.App/SopHelper.App.csproj"/></ItemGroup>
</Project>

View File

@ -0,0 +1,45 @@
using SopHelper.Engine.Training;
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].Prompt || loaded.Frames[0].Box![2] != 100) throw new Exception("Project round trip 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");
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); }

View File

@ -0,0 +1 @@
<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.Engine/SopHelper.Engine.csproj"/></ItemGroup></Project>

View File

@ -0,0 +1,112 @@
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using SopHelper.Training;
using SopHelper.Engine.Training;
internal static class Program
{
[STAThread]
public static int Main(string[] args)
{
var app = new SopHelper.App(); app.InitializeComponent();
var model = new MainViewModel(new WorkerClient());
if (args.Length > 0) model.Load(Path.GetFullPath(args[0]));
var window = new TrainingPage(model, null);
var content = (FrameworkElement)window.Content;
window.Content = null;
content.DataContext = model;
content.Margin = new Thickness(0);
content.Width = 1404; content.Height = 844;
content.Measure(new Size(1404, 844)); content.Arrange(new Rect(0, 0, 1404, 844)); content.UpdateLayout();
content.Dispatcher.Invoke(() => { }, System.Windows.Threading.DispatcherPriority.ApplicationIdle);
content.UpdateLayout();
if (content.ActualWidth < 1000) throw new Exception("Layout failed");
var image = new RenderTargetBitmap(1440, 880, 96, 96, PixelFormats.Pbgra32);
var visual = new DrawingVisual();
using (var drawing = visual.RenderOpen()) drawing.DrawRectangle(new SolidColorBrush(Color.FromRgb(16,24,32)), null, new Rect(0,0,1440,880));
image.Render(visual); image.Render(content);
var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(image));
var output = args.Length > 1 ? args[1] : Path.Combine(Path.GetTempPath(), "parttrainer-ui.png");
using (var stream = File.Create(output)) encoder.Save(stream);
Console.WriteLine("PASS: WPF resources, view model, preview layout rendered to " + output);
if (model.Project != null)
{
model.DrawBox([1,1,Math.Min(100,model.Project.Width), Math.Min(100,model.Project.Height)]);
if (model.SelectedFrame?.Prompt != true || model.SelectedFrame.Status != "reviewed") throw new Exception("Manual seed not saved");
model.ExcludeCommand.Execute();
if (model.SelectedFrame?.Box != null || model.SelectedFrame?.Prompt != false) throw new Exception("Exclusion failed");
model.NextCommand.Execute();
Console.WriteLine("PASS: manual correction persistence, exclusion, frame navigation");
}
TestApproveAll();
return 0;
}
private static void TestApproveAll()
{
var root = Path.Combine(Path.GetTempPath(), "parttrainer-review-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(root);
try
{
var bitmap = BitmapSource.Create(100,80,96,96,PixelFormats.Bgr24,null,new byte[100*80*3],300);
var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap));
using (var image = File.Create(Path.Combine(root,"frame.png"))) encoder.Save(image);
var states = new[] { "auto", "auto", "excluded", "reviewed", "auto", "unlabeled" };
var project = new TrainingProject { FilePath = Path.Combine(root,"project.json"), Width = 100, Height = 80 };
for (var index = 0; index < states.Length; index++)
project.Frames.Add(new FrameAnnotation { Index = index, Image = "frame.png", Status = states[index],
Box = index == 1 ? null : [10,10,50,50], Prompt = index == 4 });
project.Save();
var weights = Path.Combine(root,"runs","test","weights","best.pt");
File.WriteAllText(Path.Combine(root,"latest-model.json"), System.Text.Json.JsonSerializer.Serialize(new
{ weights, runDirectory = Path.Combine(root,"runs","test"), metrics = new Dictionary<string,double> { ["metrics/mAP50(B)"] = 0.75 } }));
var model = new MainViewModel(new WorkerClient()); model.Load(project.FilePath,1);
if (model.LatestWeights != weights || !model.TrainingMetrics.Contains("0.7500")) throw new Exception("Training result did not reload");
TestModelPlayback(root,model.Python);
model.ApproveAllCommand.Execute();
var saved = TrainingProject.Load(project.FilePath);
var expected = new[] { "reviewed", "auto", "excluded", "reviewed", "reviewed", "unlabeled" };
if (!saved.Frames.Select(f => f.Status).SequenceEqual(expected)) throw new Exception("Batch review changed incorrect frames");
if (saved.Frames[0].Prompt || !saved.Frames[4].Prompt) throw new Exception("Batch review changed keyframe flags");
if (model.SelectedFrame?.Index != 1 || model.Frames[0].Display.Contains("待复核")) throw new Exception("Batch review did not refresh selection/list");
model.ApproveAllCommand.Execute();
if (model.Status != "没有带目标框的待复核帧") throw new Exception("Repeated batch review did not handle empty batch");
Console.WriteLine("PASS: batch review persistence, pending boxes only, negative/excluded/unlabeled preservation, keyframe preservation, selection refresh, repeated click");
}
finally { Directory.Delete(root,true); }
}
private static void TestModelPlayback(string root,string python)
{
System.Threading.SynchronizationContext.SetSynchronizationContext(new System.Windows.Threading.DispatcherSynchronizationContext(Application.Current.Dispatcher));
Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
Directory.CreateDirectory(Path.Combine(root,"tools"));
var image = Convert.ToBase64String(File.ReadAllBytes(Path.Combine(root,"frame.png")));
var payload = System.Text.Json.JsonSerializer.Serialize(new { message="检测画面", @event="test_frame", image,
frame=1,totalFrames=10,seconds=0.1,duration=1,processingFps=10, detections=new[] {new {label="零件",confidence=0.9}} });
File.WriteAllText(Path.Combine(root,"tools","worker.py"), "import time\nprint(" + System.Text.Json.JsonSerializer.Serialize(payload) + ",flush=True)\ntime.sleep(30)\n");
var test = new ModelTestViewModel(root,python) { VideoPath=Path.Combine(root,"frame.png"), ModelPath=Path.Combine(root,"frame.png") };
var window = new ModelTestWindow(test);
test.StartCommand.Execute();
var watch = System.Diagnostics.Stopwatch.StartNew();
void PumpUntil(Func<bool> ready)
{
while (!ready())
{
if (watch.Elapsed.TotalSeconds>15) throw new Exception("Playback test timed out: " + test.Status + test.Logs);
Application.Current.Dispatcher.Invoke(()=>{},System.Windows.Threading.DispatcherPriority.ApplicationIdle); Thread.Sleep(10);
}
}
PumpUntil(()=>test.Preview!=null || !test.IsBusy);
if (test.Preview==null || !test.Detections.Contains("90") || test.StartCommand.CanExecute()) throw new Exception("Playback state/targets missing: " + test.Status);
var view = (FrameworkElement)window.Content; window.Content=null; view.DataContext=test; view.Margin=new Thickness(0);
view.Width=1164;view.Height=760;view.Measure(new Size(1164,760));view.Arrange(new Rect(0,0,1164,760));view.UpdateLayout();
var rendered=new RenderTargetBitmap(1164,760,96,96,PixelFormats.Pbgra32); rendered.Render(view);
var encoder=new PngBitmapEncoder();encoder.Frames.Add(BitmapFrame.Create(rendered));
using(var file=File.Create(Path.Combine(Path.GetTempPath(),"parttrainer-model-test.png"))) encoder.Save(file);
test.StopCommand.Execute();PumpUntil(()=>!test.IsBusy);
if(!test.StartCommand.CanExecute() || test.StopCommand.CanExecute()) throw new Exception("Playback stop did not restore controls");
var closed=false;window.Closed+=(_,_)=>closed=true;window.Close();PumpUntil(()=>closed);
Console.WriteLine("PASS: model testing window, streamed image/targets, start/stop controls, worker cancellation, window cleanup");
}
}

View File

@ -0,0 +1 @@
<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0-windows</TargetFramework><UseWPF>true</UseWPF><PlatformTarget>x64</PlatformTarget><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup><ItemGroup><ProjectReference Include="../../src/SopHelper.App/SopHelper.App.csproj"/></ItemGroup></Project>

87
tests/test_worker.py Normal file
View File

@ -0,0 +1,87 @@
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")
self.assertNotIn(0, manifest["train"])
self.assertNotIn(5, manifest["train"])
self.assertGreater(min(manifest["val"]) - max(manifest["train"]), 5)
self.assertEqual((yaml.parent / "labels/train/000010.txt").read_text(), "")
values = (yaml.parent / "labels/train/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["box"], [10,16,80,72])
self.assertEqual(result["status"], "auto")
self.assertTrue(result["prompt"])
self.assertNotIn("local-test-secret", self.project.read_text(encoding="utf-8"))
if __name__ == "__main__":
unittest.main()

26
tools/Setup-Python.ps1 Normal file
View File

@ -0,0 +1,26 @@
param([switch]$Sam2, [switch]$Cpu)
$ErrorActionPreference = 'Stop'
$projectRoot = Split-Path $PSScriptRoot -Parent
$env:PIP_CACHE_DIR = Join-Path $projectRoot '.cache/pip'
$pythonPath = Join-Path $projectRoot '.venv/Scripts/python.exe'
function Invoke-Checked([string]$Program, [string[]]$Arguments) {
& $Program @Arguments
if ($LASTEXITCODE -ne 0) { throw "执行失败: $Program $($Arguments -join ' ')" }
}
if (!(Test-Path -LiteralPath $pythonPath)) {
Invoke-Checked 'python' @('-m', 'venv', (Join-Path $projectRoot '.venv'))
}
Invoke-Checked $pythonPath @('-m', 'pip', 'install', '--upgrade', 'pip')
if ($Cpu) {
Invoke-Checked $pythonPath @('-m', 'pip', 'install', 'torch', 'torchvision', '--index-url', 'https://download.pytorch.org/whl/cpu')
} else {
Invoke-Checked $pythonPath @('-m', 'pip', 'install', 'torch', 'torchvision', '--index-url', 'https://download.pytorch.org/whl/cu128')
}
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')
}
Write-Host "完成。界面 Python 路径填写: $pythonPath"

7
tools/requirements.txt Normal file
View File

@ -0,0 +1,7 @@
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

476
tools/worker.py Normal file
View File

@ -0,0 +1,476 @@
"""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 time
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"
def emit(message, **values):
print(json.dumps({"message": message, **values}, ensure_ascii=False), flush=True)
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()
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("项目没有有效的视频帧")
for frame in data["frames"]:
image = (path.parent / frame["image"]).resolve()
if not image.is_relative_to(path.parent):
raise ValueError("帧路径超出项目目录")
if frame.get("box") is not None:
validate_box(frame["box"], data["width"], data["height"])
return path, data
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")):
raise RuntimeError("运行 tools/Setup-Python.ps1 安装基础依赖;SAM2 需加 -Sam2")
if not modules["sam2"]:
emit("尚未安装 SAM2;手动标注、导出、训练仍可用,自动传播需安装 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:
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 = {"name": request.get("name", "零件"), "video": str(video), "fps": fps if math.isfinite(fps) else 0,
"width": 0, "height": 0, "stride": stride, "frames": []}
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,
"box": None, "status": "unlabeled", "prompt": False})
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)
emit(f"导入完成:{len(data['frames'])} 帧,原视频每 {stride} 帧采样一次", progress=1)
except BaseException:
shutil.rmtree(staging, ignore_errors=True)
raise
finally:
cap.release()
def propagate(request):
import numpy as np
import torch
from sam2.build_sam import build_sam2_video_predictor
path, data = load_project(request["project"])
prompts = [f for f in data["frames"] if f.get("prompt") and f.get("box") and f["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 in prompts:
predictor.add_new_points_or_box(state, frame_idx=frame["index"], obj_id=1, box=np.array(frame["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]
if frame["status"] in ("reviewed", "absent", "excluded"):
continue
mask = (logits[0, 0] > 0).cpu().numpy()
ys, xs = np.where(mask)
frame["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.
frame["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("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 export_dataset(request):
path, data = load_project(request["project"])
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 之间")
selected = [f for f in data["frames"] if f["status"] in ("reviewed", "absent")]
if any(f["status"] == "reviewed" and not f.get("box") for f in selected):
raise ValueError("已复核的正样本缺少标注框")
# Hold out one contiguous time segment, with a gap around the boundary.
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(f.get("box") for f in training) or not any(f.get("box") for f in validation):
raise ValueError("复核样本不足:训练段至少两个样本,末尾验证段至少一个;两段均需有正样本。可减小训练抽样间隔")
output = path.parent / "datasets" / ("dataset-" + uuid.uuid4().hex[:10])
output.mkdir(parents=True)
for split, frames in (("train", training), ("val", validation)):
(output / "images" / split).mkdir(parents=True)
(output / "labels" / split).mkdir(parents=True)
for frame in frames:
stem = f"{frame['index']:06d}"
shutil.copy2(path.parent / frame["image"], output / "images" / split / (stem + ".jpg"))
label = ""
if frame.get("box") is not None and frame["status"] != "absent":
x1, y1, x2, y2 = validate_box(frame["box"], data["width"], data["height"])
label = "0 " + " ".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")
# JSON-quoted scalars are valid YAML and safely handle user-entered class names and Windows paths.
yaml = f"path: {json.dumps(output.as_posix(), ensure_ascii=False)}\ntrain: images/train\nval: images/val\nnames:\n 0: {json.dumps(data['name'], ensure_ascii=False)}\n"
(output / "data.yaml").write_text(yaml, encoding="utf-8")
save_json(output / "manifest.json", {"project": str(path), "train": [f["index"] for f in training], "val": [f["index"] for f in validation], "gap": every})
save_json(path.parent / "latest-dataset.json", {"yaml": str(output / "data.yaml")})
emit(f"导出完成 · 训练 {len(training)} / 验证 {len(validation)}", output=str(output), progress=1)
return output / "data.yaml"
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.
model = YOLO(request.get("model", "yolo11n.pt"))
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 = str(request.get("outputDirectory", "")).strip()
output_directory = Path(output_directory).resolve() if output_directory else path.parent / "runs"
output_directory.mkdir(parents=True, exist_ok=True)
model.train(data=str(yaml), epochs=epochs, imgsz=size, batch=batch, device=device,
workers=0, project=str(output_directory), name="train-" + uuid.uuid4().hex[:8])
best = Path(model.trainer.best)
if not best.is_file():
raise RuntimeError("训练未生成 best.pt")
summary = {"weights": str(best), "dataset": str(yaml), "runDirectory": str(model.trainer.save_dir),
"metrics": finite_metrics(model.trainer.metrics or {}), "epochs": reported_epoch,
"imageSize": size, "device": str(device)}
save_json(Path(model.trainer.save_dir) / "training-result.json", summary)
save_json(path.parent / "latest-model.json", summary)
emit("训练完成", event="training_completed", **summary, output=str(best), progress=1)
def export_onnx(request):
from ultralytics import YOLO
path, _ = load_project(request["project"])
weights = read_json(path.parent / "latest-model.json")["weights"]
output = YOLO(weights).export(format="onnx", imgsz=int(request.get("imageSize", 640)),
opset=17, dynamic=False, simplify=False, nms=False)
emit("ONNX 导出完成(检测框输出,不含 NMS)", output=str(output), progress=1)
def suggest(request):
path, data = load_project(request["project"])
frame = data["frames"][int(request["index"])]
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: {data['name']}. {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.
frame.update(box=box, status="auto", prompt=box is not None)
save_json(path, data)
emit("视觉模型已给出建议,请检查并确认当前帧", progress=1)
def test_video(request):
import cv2
import numpy as np
import torch
from PIL import Image, ImageDraw, ImageFont
from ultralytics import YOLO
video = Path(request["video"]).resolve()
checkpoint = Path(request["model"]).resolve()
if not video.is_file() or not checkpoint.is_file():
raise ValueError("请选择存在的视频和模型文件")
if checkpoint.suffix.lower() not in (".pt", ".onnx"):
raise ValueError("测试模型需为 .pt 或 .onnx 文件")
confidence = float(request.get("confidence", 0.25))
if not math.isfinite(confidence) or not 0 < confidence <= 1:
raise ValueError("置信度需大于0且不超过1")
device = str(request.get("device", "auto")).strip()
device = ("0" if torch.cuda.is_available() else "cpu") if device == "auto" else device
if device == "cuda":
device = "0"
size = int(request.get("imageSize", 640))
if size < 32 or size > 2048 or size % 32:
raise ValueError("检测图像尺寸需为32的倍数,范围32–2048")
if checkpoint.suffix.lower() == ".onnx":
import onnx
shape = onnx.load(str(checkpoint)).graph.input[0].type.tensor_type.shape.dim
if len(shape) == 4 and shape[2].dim_value > 0 and shape[3].dim_value > 0:
size = (shape[2].dim_value, shape[3].dim_value)
model = YOLO(str(checkpoint), task="detect")
if model.task != "detect":
raise ValueError("请选择YOLO目标检测模型")
font_path = Path(os.environ.get("WINDIR", "C:/Windows")) / "Fonts" / "msyh.ttc"
font = ImageFont.truetype(str(font_path), 20) if font_path.is_file() else ImageFont.load_default()
cap = cv2.VideoCapture(str(video))
try:
if not cap.isOpened():
raise ValueError("视频无法打开")
fps = cap.get(cv2.CAP_PROP_FPS)
fps = fps if math.isfinite(fps) and fps > 0 else 25
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
index = 0
playback_start = None
processing_start = time.monotonic()
emit("模型已加载,开始播放检测", event="test_started", fps=fps, totalFrames=total)
while True:
ok, frame = cap.read()
if not ok:
break
prediction = model.predict(frame, conf=confidence, imgsz=size, device=device, verbose=False, max_det=100)[0]
detections = []
if prediction.boxes is not None:
for box, score, category in zip(prediction.boxes.xyxy.cpu().tolist(), prediction.boxes.conf.cpu().tolist(), prediction.boxes.cls.cpu().tolist()):
detections.append({"box": box, "confidence": score, "label": prediction.names[int(category)]})
# Use a system font directly: Chinese labels work without downloading annotation fonts.
painted = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(painted)
for detection in detections:
x1,y1,x2,y2 = detection["box"]
draw.rectangle((x1,y1,x2,y2), outline=(0,230,170), width=2)
draw.text((x1,max(0,y1-24)), f"{detection['label']} {detection['confidence']:.0%}", fill=(0,230,170), font=font)
annotated = cv2.cvtColor(np.asarray(painted), cv2.COLOR_RGB2BGR)
h, w = annotated.shape[:2]
scale = min(1, 1280 / max(h, w))
if scale < 1:
annotated = cv2.resize(annotated, (round(w*scale), round(h*scale)))
success, jpeg = cv2.imencode(".jpg", annotated, [cv2.IMWRITE_JPEG_QUALITY, 85])
if not success:
raise IOError("检测画面编码失败")
# Never run faster than the source video. Slow inference plays every frame at its achievable speed.
if playback_start is None:
playback_start = time.monotonic()
delay = index / fps - (time.monotonic() - playback_start)
if delay > 0:
time.sleep(delay)
index += 1
emit("检测画面", event="test_frame", image=base64.b64encode(jpeg).decode("ascii"),
frame=index, totalFrames=total, seconds=index/fps, duration=total/fps,
processingFps=index/max(time.monotonic()-processing_start,0.001), detections=detections)
if index == 0:
raise ValueError("视频没有可解码的画面")
emit("视频检测播放完成", event="test_completed", frames=index)
finally:
cap.release()
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, "test_video": test_video}
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)