Remove model testing feature from SopHelper

This commit is contained in:
sophelper 2026-11-07 13:20:58 +08:00
parent f1783f321d
commit a708a71f7a
9 changed files with 3 additions and 301 deletions

View File

@ -108,7 +108,7 @@ dotnet run --project tests/ShutdownSmoke/ShutdownSmoke.csproj -- --hardware
## 零件标注与训练
侧栏「零件标注与训练」包含原 PartTrainer 的完整工作流:相机录像、导入视频与抽帧、手工画框、SAM2 双向传播、逐帧或一键复核、负样本与排除帧、YOLO 数据集导出、训练与 ONNX 导出、视频模型测试,以及可选视觉 API 建议框。切换到 SOP 页再返回会保留当前项目及任务。
侧栏「零件标注与训练」包含以下工作流:相机录像、导入视频与抽帧、手工画框、SAM2 双向传播、逐帧或一键复核、负样本与排除帧、YOLO 数据集导出、训练与 ONNX 导出,以及可选视觉 API 建议框。切换到 SOP 页再返回会保留当前项目及任务。
首次使用 Python 功能,在 SopHelper 根目录执行:

View File

@ -35,7 +35,6 @@ public sealed class MainViewModel : BindableBase
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()); } }

View File

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

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

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

@ -8,7 +8,7 @@
<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>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Center"><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>

View File

@ -15,7 +15,6 @@ 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;
@ -44,18 +43,6 @@ public partial class TrainingPage : UserControl
};
}
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 })
@ -72,7 +59,6 @@ public partial class TrainingPage : UserControl
public async Task ShutdownAsync()
{
await _model.StopAsync();
if (_testWindow != null) await _testWindow.Model.StopAsync();
if (_cameraWindow != null) await _cameraWindow.Model.ShutdownAsync();
}

View File

@ -63,7 +63,6 @@ internal static class Program
{ 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" };
@ -76,37 +75,4 @@ internal static class Program
}
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

@ -12,7 +12,6 @@ import os
from pathlib import Path
import shutil
import sys
import time
import tempfile
import traceback
import urllib.request
@ -376,94 +375,10 @@ def suggest(request):
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}
"train": train, "onnx": export_onnx, "suggest": suggest}
actions[request["action"]](request)