精简主界面运行控件并增加标准SOP视频播放

This commit is contained in:
tfarcraw 2026-11-20 10:03:34 +08:00
parent b2e411aab2
commit c84a12beb0
6 changed files with 189 additions and 22 deletions

View File

@ -32,7 +32,7 @@ pwsh -File tools/Start-HandAiD3.ps1
Windows DirectShow 设置分辨率时可能把 MJPG 重置为 YUY2,因此程序在分辨率和帧率设置后再应用视频格式;Linux V4L2 保持先设置格式。2026-11-18 在 USB Camera(0c45:636d)上验证:原顺序在 640×480 和 800×600 下均约 15fps,修复后通过实际 UvcCameraService 采集均约 30fps,格式回读为 MJPG,手动曝光回读 15.625ms。设置接口返回成功和驱动回读 30fps 均不能代替实际采集计数。
SOP 流程视频可在配方编辑器中录制和播放,独立保存在该配方的 `sop_stand` 目录。配方选择和相机选择会记忆;恢复选择不会自动开始采集。
SOP 流程视频可在配方编辑器中录制和播放,独立保存在该配方的 `sop_stand` 目录。主界面的“播放标准 SOP”可独立打开当前已应用配方的视频,支持播放和拖动进度,不影响相机采集。配方选择和相机选择会记忆;恢复选择不会自动开始采集。
“Agent助手”接收本地标准视频路径,通过工具自主查看不同时间点、继续检查细节,再生成步骤草稿。模型需支持 Chat Completions 工具调用和图片输入,不需要上传完整视频。每次工具读取上限默认 3 张,可修改并记住。草稿包含时间段、参考画面、步骤说明和手部规则,修改后追加到配方,最后手动保存。接口地址、模型名、密钥及生成参数自动保存,下次启动恢复;模型列表可自动获取。运行时仍由 djev 确认步骤完成。详细限制与配置见 [HAND_AI.md](HAND_AI.md)。
@ -57,7 +57,7 @@ pwsh -File tools/Publish-Avalonia.ps1
`--import-recipes 原数据根目录` 可以导入已有配方,`--check-standalone` / `--check-runtime` 检查本地手部模型和使用模拟 AI 的步骤门控,`--check-gpu` 额外要求手部推理使用 GPU;这些本地诊断不代表真实 D3 接口联调成功。
主界面每个步骤显示正常次数和异常次数:正常完成计入正常,异常跳过计入异常;按配方保存在 `workspace/step-counts.json`,复位、停止、重新应用配方或重启软件均保留;仅点击“重置步骤”后的“重置计数”按钮,才会清零当前已应用配方的计数,不影响步骤进度及其他配方。
主界面每个步骤显示正常次数和异常次数:正常完成计入正常,异常跳过计入异常;按配方保存在 `workspace/step-counts.json`,复位、停止、重新应用配方或重启软件均保留;仅点击“重置计数”按钮,才会清零当前已应用配方的计数,不影响步骤进度及其他配方。
## 验证

View File

@ -80,21 +80,18 @@
<TextBlock Text="帧率" />
<TextBlock Grid.Column="1" Text="{Binding FpsText}" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" />
</Grid>
<Grid x:Name="RunStatisticsPanel" ColumnDefinitions="Auto,*,Auto,*" RowDefinitions="Auto,Auto" Margin="0,10,0,0">
<TextBlock Text="流程计时" Margin="0,0,8,6" />
<Grid x:Name="RunStatisticsPanel" ColumnDefinitions="Auto,*,Auto,*" Margin="0,10,0,0">
<TextBlock Text="流程计时" Margin="0,0,8,0" />
<TextBlock Grid.Column="1" Text="{Binding FlowElapsedText}" />
<TextBlock Grid.Column="2" Text="步骤计时" Margin="8,0,8,6" />
<TextBlock Grid.Column="3" Text="{Binding StepElapsedText}" />
<TextBlock Grid.Row="1" Text="标准用时" Margin="0,0,8,0" />
<TextBlock Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="3" Text="{Binding StandardDurationText}" />
<TextBlock Grid.Column="2" Text="标准用时" Margin="8,0,8,0" />
<TextBlock Grid.Column="3" Text="{Binding StandardDurationText}" />
</Grid>
</StackPanel>
</Border>
<WrapPanel Grid.Row="1" Margin="0,10,0,0" HorizontalAlignment="Left">
<Button Content="开始 / 停止" Command="{Binding StartStopCommand}" />
<Button Content="暂停" Margin="6,0,0,0" Command="{Binding TogglePauseCommand}" />
<Button Content="重置步骤" Margin="6,0,0,0" Command="{Binding ResetCommand}" />
<Button x:Name="ResetCountsButton" Content="重置计数" Margin="6,0,0,0" Command="{Binding ResetCountsCommand}" ToolTip.Tip="清零当前已应用配方的正常次数和异常次数,保留步骤进度和其他配方计数" />
<Button x:Name="PlayStandardSopButton" Content="播放标准 SOP" Margin="6,0,0,0" Command="{Binding PlayStandardSopCommand}" ToolTip.Tip="播放当前已应用配方的标准视频;没有视频时请先在配方中录制或导入" />
</WrapPanel>
<Border Grid.Row="2" Margin="0,10,0,0" Classes="panel">
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">

View File

@ -137,9 +137,8 @@ public class SopPageViewModel : ViewModelBase
ConfigureCameraCommand = new DelegateCommand(async () => await ConfigureCameraAsync(), () => CanSelectCamera && SelectedCamera is not null);
RefreshCamerasCommand = new DelegateCommand(async () => await RefreshCamerasAsync(), () => CanSelectCamera);
StartStopCommand = new DelegateCommand(async () => await StartStopAsync(), CanStart);
TogglePauseCommand = new DelegateCommand(_engine.TogglePause, () => IsRunning);
ResetCommand = new DelegateCommand(_engine.Reset, () => IsRunning);
ResetCountsCommand = new DelegateCommand(ResetCounts, () => StepCards.Count > 0);
PlayStandardSopCommand = new DelegateCommand(PlayStandardSop, () => StandardSopVideoPath is { } path && File.Exists(path));
ApplyRecipeCommand = new DelegateCommand(ApplyRecipe, () => CanSelectCamera && !string.IsNullOrWhiteSpace(SelectedRecipe));
SnapshotCommand = new DelegateCommand(Snapshot, () => _lastFrame is not null);
EditRecipeCommand = new DelegateCommand(EditRecipe, CanEditRecipe);
@ -345,12 +344,8 @@ public class SopPageViewModel : ViewModelBase
/// <summary>开始 / 停止</summary>
public DelegateCommand StartStopCommand { get; private set; } = null!;
/// <summary>暂停 / 继续</summary>
public DelegateCommand TogglePauseCommand { get; private set; } = null!;
/// <summary>复位</summary>
public DelegateCommand ResetCommand { get; private set; } = null!;
public DelegateCommand ResetCountsCommand { get; private set; } = null!;
public DelegateCommand PlayStandardSopCommand { get; private set; } = null!;
public DelegateCommand DeleteRecipeCommand { get; private set; } = null!;
/// <summary>应用配方</summary>
@ -403,9 +398,8 @@ public class SopPageViewModel : ViewModelBase
ConfigureCameraCommand?.RaiseCanExecuteChanged();
RefreshCamerasCommand?.RaiseCanExecuteChanged();
StartStopCommand?.RaiseCanExecuteChanged();
TogglePauseCommand?.RaiseCanExecuteChanged();
ResetCommand?.RaiseCanExecuteChanged();
ResetCountsCommand?.RaiseCanExecuteChanged();
PlayStandardSopCommand?.RaiseCanExecuteChanged();
ApplyRecipeCommand?.RaiseCanExecuteChanged();
SnapshotCommand?.RaiseCanExecuteChanged();
EditRecipeCommand?.RaiseCanExecuteChanged();
@ -462,6 +456,7 @@ public class SopPageViewModel : ViewModelBase
public override void Destroy()
{
_statisticsTimer.Stop();
_standardSopWindow?.Close();
_engine.Stop();
_engine.RoundFinished -= OnRoundFinished;
_camera.FrameArrived -= OnCameraFrame;
@ -597,6 +592,7 @@ public class SopPageViewModel : ViewModelBase
ClearProcessImages();
StepCards.Clear(); Rois.Clear(); HandResult = null; _lastFrame = null;
ResetCountsCommand?.RaiseCanExecuteChanged();
PlayStandardSopCommand?.RaiseCanExecuteChanged();
ActiveRecipe = "未应用配方";
RaisePropertyChanged(nameof(InferenceBackendText));
RaiseCommands();
@ -858,6 +854,7 @@ public class SopPageViewModel : ViewModelBase
}
ResetCountsCommand.RaiseCanExecuteChanged();
PlayStandardSopCommand.RaiseCanExecuteChanged();
foreach (var (name, def) in config.Sop.Regions)
Rois.Add(new RoiItem { Name = name, X = def.X1, Y = def.Y1, W = def.X2 - def.X1, H = def.Y2 - def.Y1, ColorHex = def.Color });
@ -1006,6 +1003,29 @@ public class SopPageViewModel : ViewModelBase
}
}
private StandardSopWindow? _standardSopWindow;
private string? StandardSopVideoPath => string.IsNullOrWhiteSpace(ActiveRecipe) || ActiveRecipe == "未应用配方" ? null
: Path.Combine(DesktopPlatform.Recipes.DirectoryFor(Path.GetFileNameWithoutExtension(ActiveRecipe)), "sop_stand", "sop.avi");
private void PlayStandardSop()
{
if (StandardSopVideoPath is not { } path || !File.Exists(path))
{
Log("warn", "当前配方没有标准 SOP 视频,请先录制或导入视频");
PlayStandardSopCommand.RaiseCanExecuteChanged();
return;
}
if (_standardSopWindow is { IsVisible: true } existing && existing.VideoPath == path)
{
existing.Activate();
return;
}
_standardSopWindow?.Close();
var window = _standardSopWindow = new StandardSopWindow(path, Path.GetFileNameWithoutExtension(ActiveRecipe));
window.Closed += (_, _) => { if (ReferenceEquals(_standardSopWindow, window)) _standardSopWindow = null; };
window.Show(DesktopPlatform.Owner);
}
private void ResetCounts()
{
if (StepCards.Count == 0) return;

View File

@ -0,0 +1,18 @@
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SopHelper.VVMs.SopPage.StandardSopWindow" Title="标准 SOP"
Width="900" Height="640" MinWidth="600" MinHeight="400" Background="{StaticResource Bg}" WindowStartupLocation="CenterOwner">
<Grid Margin="16" RowDefinitions="Auto,*,Auto,Auto">
<TextBlock x:Name="RecipeTitle" Classes="Title" Margin="0,0,0,12" />
<Border Grid.Row="1" Classes="panel" Background="#080E14" Padding="0">
<Image Source="{Binding Frame}" Stretch="Uniform" />
</Border>
<Grid Grid.Row="2" ColumnDefinitions="Auto,*,Auto,Auto" Margin="0,12,0,0">
<Button x:Name="PlaybackToggleButton" Content="播放" Click="TogglePlayback" />
<Slider x:Name="PlaybackSeekSlider" Grid.Column="1" Minimum="0" Maximum="100" Value="{Binding Progress, Mode=TwoWay}"
IsEnabled="{Binding IsLoaded}" VerticalAlignment="Center" Margin="12,0" />
<TextBlock Grid.Column="2" Text="{Binding TimeText}" Margin="0,0,12,0" />
<Button Grid.Column="3" Content="关闭" Click="ClosePlayback" />
</Grid>
<TextBlock x:Name="PlaybackErrorText" Grid.Row="3" TextWrapping="Wrap" Foreground="{StaticResource Ng}" Margin="0,8,0,0" />
</Grid>
</Window>

View File

@ -0,0 +1,63 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
using SopHelper.Training;
namespace SopHelper.VVMs.SopPage;
public partial class StandardSopWindow : Window
{
public string VideoPath { get; }
public RecordedVideoPlayback Playback { get; } = new();
private Task _playOperation = Task.CompletedTask;
private bool _closeRequested, _closedSafely;
public StandardSopWindow(string videoPath, string recipeName)
{
InitializeComponent();
VideoPath = videoPath;
Title = "标准 SOP · " + recipeName;
RecipeTitle.Text = recipeName + " · 标准 SOP";
DataContext = Playback;
Playback.Failed += message => PlaybackErrorText.Text = message;
Playback.PropertyChanged += (_, e) =>
{
if (e.PropertyName is nameof(Playback.IsPlaying) or nameof(Playback.IsAtEnd))
PlaybackToggleButton.Content = Playback.IsPlaying ? "暂停播放" : Playback.IsAtEnd ? "重新播放" : "播放";
};
Opened += (_, _) => _playOperation = PlayAsync();
Closing += OnSafeClosing;
}
private async Task PlayAsync()
{
PlaybackToggleButton.IsEnabled = false;
PlaybackErrorText.Text = "";
try { await Playback.PlayAsync(VideoPath); }
catch (Exception error)
{
await Playback.StopAsync();
PlaybackErrorText.Text = "标准 SOP 视频无法播放:" + error.Message;
}
finally { if (!_closeRequested) PlaybackToggleButton.IsEnabled = true; }
}
private void TogglePlayback(object? sender, RoutedEventArgs e)
{
if (_closeRequested) return;
if (Playback.IsPlaying) Playback.Pause();
else _playOperation = PlayAsync();
}
private void ClosePlayback(object? sender, RoutedEventArgs e) => Close();
private async void OnSafeClosing(object? sender, WindowClosingEventArgs e)
{
if (_closedSafely) return;
e.Cancel = true;
if (_closeRequested) return;
_closeRequested = true;
PlaybackToggleButton.IsEnabled = false;
try { await _playOperation; await Playback.StopAsync(); }
finally { _closedSafely = true; Close(); }
}
}

View File

@ -87,6 +87,8 @@ internal static class Smoke
var userCameraBefore=File.Exists(userCameraPath)?File.ReadAllBytes(userCameraPath):null;
await Task.Delay(150);
var app=(App)Application.Current!;var window=lifetime.MainWindow!;
if(Environment.GetCommandLineArgs().Contains("--standard-sop-only"))
{ await CheckStandardSopPlayback(app,window,lifetime);_exit=0;return; }
if(Environment.GetCommandLineArgs().Contains("--step-counts-only"))
{ await CheckStepCounts(app,window);_exit=0;return; }
if(Environment.GetCommandLineArgs().Contains("--startup-recipe-only"))
@ -662,6 +664,73 @@ internal static class Smoke
}
finally{sop.IsRunning=false;sop.ApplyRecipeCommand.Execute();}
}
private static async Task CheckStandardSopPlayback(App app,Window window,IClassicDesktopStyleApplicationLifetime lifetime)
{
var model=app.Container.Resolve<SopPageViewModel>();
var engine=app.Container.Resolve<SopHelper.Engine.Sop.SopEngine>();
var view=window.GetVisualDescendants().OfType<SopPage>().Single();
var texts=view.GetVisualDescendants().OfType<TextBlock>().Select(t=>t.Text).ToArray();
Check(!texts.Contains("步骤计时")&&texts.Contains("流程计时")&&texts.Contains("标准用时"),"Header retains flow and standard times without step timing");
var buttons=view.GetVisualDescendants().OfType<Button>().ToArray();
Check(!buttons.Any(b=>b.Content?.ToString() is "暂停" or "重置步骤")
&&buttons.Any(b=>b.Content?.ToString()=="重置计数"),"Main run controls remove pause and step reset while keeping count reset");
var play=view.FindControl<Button>("PlayStandardSopButton")!;
Check(!play.IsEffectivelyEnabled,"Standard SOP playback is unavailable when no standard video exists");
var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!);
var path=Path.Combine(store.DirectoryFor(Path.GetFileNameWithoutExtension(model.ActiveRecipe)),"sop_stand","sop.avi");
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
using(var writer=new VideoWriter(path,FourCC.MJPG,10,new OpenCvSharp.Size(160,120)))
{
Check(writer.IsOpened(),"Standard SOP playback fixture opens");
for(var i=0;i<40;i++)
{
using var frame=new Mat(120,160,MatType.CV_8UC3,new Scalar(40+i*3,70,120));
Cv2.PutText(frame,"SOP "+i,new OpenCvSharp.Point(15,65),HersheyFonts.HersheySimplex,.6,new Scalar(255,255,255),1);
writer.Write(frame);
}
}
model.ApplyRecipeCommand.Execute();await Task.Delay(30);
Check(play.IsEffectivelyEnabled,"Applying a recipe with a saved standard video enables playback");
model.StartStopCommand.Execute();for(var i=0;i<100&&!model.IsRunning;i++)await Task.Delay(20);
Check(model.IsRunning&&Camera.IsGrabbing,"Acquisition can run alongside standard video playback");
var cameraConnections=Camera.ConnectCount;var state=engine.State;
play.Command!.Execute(play.CommandParameter);await Task.Delay(30);
var player=lifetime.Windows.OfType<StandardSopWindow>().Single();
for(var i=0;i<100&&player.Playback.Frame is null;i++)await Task.Delay(20);
Check(player.VideoPath==path&&player.Playback.IsLoaded&&player.Playback.Frame is not null,"Playback opens and decodes the applied recipe's standard video");
play.Command.Execute(play.CommandParameter);
Check(lifetime.Windows.OfType<StandardSopWindow>().Count()==1,"Repeated playback clicks reuse the existing player");
Check(model.IsRunning&&Camera.IsGrabbing&&Camera.ConnectCount==cameraConnections&&engine.State==state,"Opening standard SOP playback preserves acquisition and engine state");
var toggle=player.FindControl<Button>("PlaybackToggleButton")!;
toggle.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
Check(!player.Playback.IsPlaying,"Standard video supports pausing independently of acquisition");
player.FindControl<Slider>("PlaybackSeekSlider")!.Value=60;
for(var i=0;i<100&&(player.Playback.IsSeeking||player.Playback.DisplayedSeconds<2);i++)await Task.Delay(20);
Check(player.Playback.DisplayedSeconds>=2&&!player.Playback.IsPlaying,"Standard video supports seeking while paused");
var screenshots=Path.GetFullPath(Path.Combine("..","scratch","screenshots"));Directory.CreateDirectory(screenshots);
using(var rendered=new RenderTargetBitmap(new PixelSize((int)player.Bounds.Width,(int)player.Bounds.Height)))
{rendered.Render(player);rendered.Save(Path.Combine(screenshots,"standard-sop-playback.png"));}
toggle.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));await Task.Delay(40);
Check(player.Playback.IsPlaying,"Standard video resumes from the selected position");
player.Close();for(var i=0;i<100&&player.IsVisible;i++)await Task.Delay(20);
Check(!player.IsVisible&&!player.Playback.IsLoaded&&Camera.IsGrabbing,"Closing playback releases the video and preserves acquisition");
using(var exclusive=new FileStream(path,FileMode.Open,FileAccess.ReadWrite,FileShare.None))Check(exclusive.Length>0,"Video file is unlocked after the player closes");
play.Command.Execute(play.CommandParameter);
var quick=lifetime.Windows.OfType<StandardSopWindow>().Single();quick.Close();
for(var i=0;i<100&&quick.IsVisible;i++)await Task.Delay(20);
Check(!quick.IsVisible&&!quick.Playback.IsLoaded,"Closing during video opening also releases playback resources");
window.WindowState=WindowState.Normal;window.Width=1180;window.Height=820;await Task.Delay(50);window.UpdateLayout();
using(var rendered=new RenderTargetBitmap(new PixelSize((int)window.Bounds.Width,(int)window.Bounds.Height)))
{rendered.Render(window);rendered.Save(Path.Combine(screenshots,"standard-sop-main.png"));}
File.WriteAllText(path,"damaged-video");play.Command.Execute(play.CommandParameter);
var damaged=lifetime.Windows.OfType<StandardSopWindow>().Single();
for(var i=0;i<100&&string.IsNullOrWhiteSpace(damaged.FindControl<TextBlock>("PlaybackErrorText")!.Text);i++)await Task.Delay(20);
Check(damaged.FindControl<TextBlock>("PlaybackErrorText")!.Text?.Contains("无法播放")==true&&!damaged.Playback.IsLoaded,"Damaged standard video reports a playback error without loading a capture");
damaged.Close();for(var i=0;i<100&&damaged.IsVisible;i++)await Task.Delay(20);
Check(model.IsRunning&&Camera.IsGrabbing&&Camera.ConnectCount==cameraConnections,"Playback errors do not change the running camera");
model.StartStopCommand.Execute();for(var i=0;i<100&&model.IsRunning;i++)await Task.Delay(20);
}
private static async Task CheckStepCounts(App app,Window window)
{
var model=app.Container.Resolve<SopPageViewModel>();
@ -734,8 +803,8 @@ internal static class Smoke
{rendered.Render(window);rendered.Save(Path.Combine(screenshots,"step-result-counts.png"));}
var resetButton=view.FindControl<Button>("ResetCountsButton")!;
var buttons=resetButton.GetVisualParent()!.GetVisualChildren().OfType<Button>().ToList();
Check(buttons.IndexOf(resetButton)==buttons.FindIndex(b=>b.Content?.ToString()=="重置步骤")+1,
"Reset counts button follows reset steps");
Check(buttons.Contains(resetButton)&&!buttons.Any(b=>b.Content?.ToString() is "暂停" or "重置步骤"),
"Reset counts remains available without the removed run controls");
countStore.Save("其他配方",new Dictionary<int,SopHelper.Engine.Sop.StepRunCounts>{{1,new(7,4)}});
var stateBefore=engine.State;var elapsedBefore=model.StepCards[0].ElapsedText;var imageBefore=model.StepCards[0].CompletionImage;
model.SelectedRecipe="demo.yaml";await Task.Delay(120);
@ -796,7 +865,7 @@ internal static class Smoke
Check(sop.StepCards.All(c=>System.Text.RegularExpressions.Regex.IsMatch(c.ElapsedText,@"^\d{2,}:\d{2}:\d{2}$")),"Completed step cards display elapsed times to whole seconds");
var panel=window.GetVisualDescendants().OfType<Grid>().Single(c=>c.Name=="RunStatisticsPanel");
var texts=panel.GetVisualDescendants().OfType<TextBlock>().Select(t=>t.Text).ToArray();
Check(texts.Contains("流程计时")&&texts.Contains("步骤计时")&&texts.Contains("标准用时")&&!texts.Contains("完成次数")&&!texts.Contains("平均用时"),"Operator page renders timing fields without the removed summary counts");
Check(texts.Contains("流程计时")&&!texts.Contains("步骤计时")&&texts.Contains("标准用时")&&!texts.Contains("完成次数")&&!texts.Contains("平均用时"),"Operator page renders timing fields without the removed summary counts");
Save(window,"runtime-statistics");
engine.Reset();await Task.Delay(120);
Check(sop.CompletedCount==11&&sop.StepCards.All(c=>c.ElapsedText=="00:00:00"||c.StepId==1),"Reset begins new step timing while preserving completed count and history");