持久保存步骤累计次数并增加手动重置计数按钮

This commit is contained in:
tfarcraw 2026-11-20 09:52:43 +08:00
parent 716077061b
commit b2e411aab2
7 changed files with 158 additions and 2 deletions

View File

@ -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`,复位、停止、重新应用配方或重启软件均保留;仅点击“重置步骤”后的“重置计数”按钮,才会清零当前已应用配方的计数,不影响步骤进度及其他配方。
## 验证

View File

@ -0,0 +1,51 @@
using System.IO;
using System.Text.Json;
using SopHelper.Engine.Sop;
using SopHelper.Presentation;
namespace SopHelper.Models;
/// <summary>按配方持久保存步骤累计结果,独立于运行参数和配方编辑。</summary>
public sealed class StepCountsStore(string root) : IStepCountStore
{
private static readonly object FileGate = new();
public static StepCountsStore Current => new(DesktopPlatform.WorkspaceRoot);
public string FilePath => Path.Combine(root, "workspace", "step-counts.json");
private Dictionary<string, Dictionary<int, StepRunCounts>> Read()
{
if (!File.Exists(FilePath)) return new(StringComparer.OrdinalIgnoreCase);
var all = JsonSerializer.Deserialize<Dictionary<string, Dictionary<int, StepRunCounts>>>(File.ReadAllText(FilePath))
?? throw new InvalidDataException("累计次数文件内容为空");
if (all.Values.Any(steps => steps is null || steps.Any(pair => pair.Key <= 0
|| pair.Value.NormalCount < 0 || pair.Value.AbnormalCount < 0)))
throw new InvalidDataException("累计次数文件包含无效步骤或负数");
return new(all, StringComparer.OrdinalIgnoreCase);
}
public IReadOnlyDictionary<int, StepRunCounts> Load(string recipeName)
{
lock (FileGate) return Read().GetValueOrDefault(recipeName) ?? [];
}
public void Save(string recipeName, IReadOnlyDictionary<int, StepRunCounts> counts)
{
lock (FileGate)
{
var all = Read();
all[recipeName] = new(counts);
Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);
var temporary = FilePath + ".tmp";
try
{
using (var stream = new FileStream(temporary, FileMode.Create, FileAccess.Write, FileShare.None))
{
JsonSerializer.Serialize(stream, all, new JsonSerializerOptions { WriteIndented = true });
stream.Flush(flushToDisk: true);
}
File.Move(temporary, FilePath, overwrite: true);
}
finally { if (File.Exists(temporary)) File.Delete(temporary); }
}
}
}

View File

@ -94,6 +94,7 @@
<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="清零当前已应用配方的正常次数和异常次数,保留步骤进度和其他配方计数" />
</WrapPanel>
<Border Grid.Row="2" Margin="0,10,0,0" Classes="panel">
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">

View File

@ -102,6 +102,7 @@ public class SopPageViewModel : ViewModelBase
_camera = camera;
_pipeline = pipeline;
_engine = engine;
_engine.StepCountStore ??= SopHelper.Models.StepCountsStore.Current;
_engine.VisionDecisionClient ??= new ConfiguredVisionDecisionClient(VisionHttp);
_pipeline.ShouldDetectHands = () => _engine.RequiresHandDetection;
_dialogs = dialogs;
@ -138,6 +139,7 @@ public class SopPageViewModel : ViewModelBase
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);
ApplyRecipeCommand = new DelegateCommand(ApplyRecipe, () => CanSelectCamera && !string.IsNullOrWhiteSpace(SelectedRecipe));
SnapshotCommand = new DelegateCommand(Snapshot, () => _lastFrame is not null);
EditRecipeCommand = new DelegateCommand(EditRecipe, CanEditRecipe);
@ -348,6 +350,7 @@ public class SopPageViewModel : ViewModelBase
/// <summary>复位</summary>
public DelegateCommand ResetCommand { get; private set; } = null!;
public DelegateCommand ResetCountsCommand { get; private set; } = null!;
public DelegateCommand DeleteRecipeCommand { get; private set; } = null!;
/// <summary>应用配方</summary>
@ -402,6 +405,7 @@ public class SopPageViewModel : ViewModelBase
StartStopCommand?.RaiseCanExecuteChanged();
TogglePauseCommand?.RaiseCanExecuteChanged();
ResetCommand?.RaiseCanExecuteChanged();
ResetCountsCommand?.RaiseCanExecuteChanged();
ApplyRecipeCommand?.RaiseCanExecuteChanged();
SnapshotCommand?.RaiseCanExecuteChanged();
EditRecipeCommand?.RaiseCanExecuteChanged();
@ -592,6 +596,7 @@ public class SopPageViewModel : ViewModelBase
_engine.Load(new SopConfig());
ClearProcessImages();
StepCards.Clear(); Rois.Clear(); HandResult = null; _lastFrame = null;
ResetCountsCommand?.RaiseCanExecuteChanged();
ActiveRecipe = "未应用配方";
RaisePropertyChanged(nameof(InferenceBackendText));
RaiseCommands();
@ -852,6 +857,8 @@ public class SopPageViewModel : ViewModelBase
StepCards.Add(card);
}
ResetCountsCommand.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 });
@ -999,6 +1006,22 @@ public class SopPageViewModel : ViewModelBase
}
}
private void ResetCounts()
{
if (StepCards.Count == 0) return;
try
{
_engine.ResetStepCounts();
foreach (var card in StepCards) UpdateStepCounts(card, _engine.Statistics);
Log("info", "已重置当前配方的累计次数:" + ActiveRecipe);
}
catch (Exception error)
{
StatusText = "重置计数失败,累计次数已保留";
Log("warn", "重置计数失败:" + error.Message);
}
}
private static void UpdateStepCounts(StepCard card, SopRunStatistics statistics)
{
var counts = statistics.GetStepCounts(card.StepId);

View File

@ -79,15 +79,33 @@ public partial class SopEngine
public event Action<bool>? RoundFinished;
private readonly Dictionary<string, SopRunStatistics> _statistics = new(StringComparer.OrdinalIgnoreCase);
public SopRunStatistics Statistics { get; private set; } = new();
public IStepCountStore? StepCountStore { get; set; }
public SopRunStatistics GetStatistics(string recipeName)
{
lock (_statistics)
{
if (!_statistics.TryGetValue(recipeName, out var statistics))
_statistics[recipeName] = statistics = new SopRunStatistics();
{
statistics = new SopRunStatistics();
if (StepCountStore is { } store)
{
statistics.RestoreStepCounts(store.Load(recipeName));
statistics.StepCountsChanged += counts =>
{
try { store.Save(recipeName, counts); }
catch (Exception error) { Log("warn", "累计次数保存失败:" + error.Message); }
};
}
_statistics[recipeName] = statistics;
}
return statistics;
}
}
/// <summary>仅手动清零当前配方的步骤计数;先保存成功,再更新内存。</summary>
public void ResetStepCounts()
{
Statistics.ResetStepCounts(() => StepCountStore?.Save(_config.Sop.Name, new Dictionary<int, StepRunCounts>()));
}
private DateTime _stepEnteredAt = DateTime.Now;
/// <summary>当前运行状态</summary>

View File

@ -2,6 +2,12 @@ namespace SopHelper.Engine.Sop;
public readonly record struct StepRunCounts(long NormalCount, long AbnormalCount);
public interface IStepCountStore
{
IReadOnlyDictionary<int, StepRunCounts> Load(string recipeName);
void Save(string recipeName, IReadOnlyDictionary<int, StepRunCounts> counts);
}
/// <summary>Session statistics for one recipe; elapsed times exclude pauses.</summary>
public sealed class SopRunStatistics(TimeProvider? timeProvider = null)
{
@ -21,6 +27,23 @@ public sealed class SopRunStatistics(TimeProvider? timeProvider = null)
{
lock (_gate) return _stepCounts.GetValueOrDefault(stepId);
}
internal event Action<IReadOnlyDictionary<int, StepRunCounts>>? StepCountsChanged;
internal void RestoreStepCounts(IReadOnlyDictionary<int, StepRunCounts> counts)
{
lock (_gate)
{
_stepCounts.Clear();
foreach (var (id, value) in counts) _stepCounts[id] = value;
}
}
internal void ResetStepCounts(Action persistReset)
{
lock (_gate)
{
persistReset();
_stepCounts.Clear();
}
}
internal void RecordStepResult(int stepId, bool normal)
{
lock (_gate)
@ -28,6 +51,7 @@ public sealed class SopRunStatistics(TimeProvider? timeProvider = null)
var counts = _stepCounts.GetValueOrDefault(stepId);
_stepCounts[stepId] = normal ? counts with { NormalCount = counts.NormalCount + 1 }
: counts with { AbnormalCount = counts.AbnormalCount + 1 };
StepCountsChanged?.Invoke(new Dictionary<int, StepRunCounts>(_stepCounts));
}
}
private TimeSpan RunningElapsed => _running ? _clock.GetElapsedTime(_since) : TimeSpan.Zero;

View File

@ -711,6 +711,18 @@ internal static class Smoke
decision.Result.SetResult(new(true,.99,"确认完成"));
for(var i=0;i<10&&engine.State!=SopHelper.Engine.Sop.EngineState.Completed;i++)await Emit();
Counts(2,0,0,2,"Later rounds accumulate each final step result exactly once");
var countStore=new StepCountsStore(store.Root);
var savedCounts=countStore.Load(name);
Check(savedCounts[1].NormalCount==2&&savedCounts[2].AbnormalCount==2,"Each final result is persisted before application exit");
void AfterRestart(Action<SopPageViewModel> check)
{
using var camera=new FakeCamera{Devices=[]};
using var pipeline=new SopHelper.Engine.Pipeline.DetectionPipeline(camera);
var fresh=new SopPageViewModel(camera,pipeline,new SopHelper.Engine.Sop.SopEngine(),app.Container.Resolve<IDialogService>());
try{check(fresh);}finally{fresh.Destroy();}
}
AfterRestart(fresh=>Check(fresh.ActiveRecipe==name+".yaml"&&fresh.StepCards[0].NormalCount==2&&fresh.StepCards[1].AbnormalCount==2,
"A fresh engine and view model restore persisted counts at startup"));
var view=window.GetVisualDescendants().OfType<SopPage>().Single();
var texts=view.GetVisualDescendants().OfType<TextBlock>().Select(t=>t.Text).ToArray();
Check(!texts.Contains("违规 Top3")&&!texts.Contains("完成次数")&&!texts.Contains("平均用时"),"Removed summary and violation panels are absent");
@ -720,6 +732,33 @@ internal static class Smoke
var screenshots=Path.GetFullPath(Path.Combine("..","scratch","screenshots"));Directory.CreateDirectory(screenshots);
using(var rendered=new RenderTargetBitmap(new PixelSize((int)window.Bounds.Width,(int)window.Bounds.Height)))
{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");
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);
resetButton.Command!.Execute(resetButton.CommandParameter);
Counts(0,0,0,0,"Manual reset clears counts for the applied recipe even with a pending selection");
Check(engine.State==stateBefore&&model.IsRunning&&model.StepCards[0].ElapsedText==elapsedBefore
&&ReferenceEquals(model.StepCards[0].CompletionImage,imageBefore),"Resetting counts preserves run state, step times and images");
Check(countStore.Load("其他配方")[1]==new SopHelper.Engine.Sop.StepRunCounts(7,4),"Manual reset preserves other recipes' persisted counts");
model.SelectedRecipe=name+".yaml";
AfterRestart(fresh=>Check(fresh.StepCards.All(c=>c.NormalCount==0&&c.AbnormalCount==0),"Manual reset remains zero after a fresh startup"));
decision=new UiVisionDecision();engine.VisionDecisionClient=decision;engine.Start();
for(var i=0;i<10&&!decision.Called.Task.IsCompleted;i++)await Emit();
decision.Result.SetResult(new(true,.99,"确认完成"));
for(var i=0;i<10&&engine.State!=SopHelper.Engine.Sop.EngineState.Completed;i++)await Emit();
Counts(1,0,0,1,"New results accumulate normally after manual reset");
Directory.CreateDirectory(countStore.FilePath+".tmp");
try
{
model.ResetCountsCommand.Execute();
Counts(1,0,0,1,"A failed reset write preserves the in-memory counts");
Check(countStore.Load(name)[1].NormalCount==1&&model.StatusText.Contains("重置计数失败"),"A failed reset preserves stored counts and reports the error");
}
finally{Directory.Delete(countStore.FilePath+".tmp");}
engine.Stop();model.IsRunning=false;
}