diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs index e050b02..3fd10a5 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/EditorNodes.cs @@ -424,6 +424,11 @@ public class RecipeNode : EditorNode StandardDurationMs = step.StandardDurationMs, SaveCompletionImage = step.SaveCompletionImage, CompletionImageDirectory = step.CompletionImageDirectory, + AiConfirmation = step.AiConfirmation is null ? null : new AiConfirmation + { + Criteria = step.AiConfirmation.Criteria, MinConfidence = step.AiConfirmation.MinConfidence, + RetryDelayMs = step.AiConfirmation.RetryDelayMs, TimeoutSeconds = step.AiConfirmation.TimeoutSeconds, + }, }; foreach (var item in step.MustKeep) stepNode.MustKeep.Items.Add(new TextItem { Text = item, RemoveCommand = stepNode.MustKeep.RemoveCommand }); @@ -480,6 +485,11 @@ public class RecipeNode : EditorNode StandardDurationMs = step.StandardDurationMs, SaveCompletionImage = step.SaveCompletionImage, CompletionImageDirectory = step.CompletionImageDirectory, + AiConfirmation = step.RequireAiConfirmation ? new AiConfirmation + { + Criteria = step.AiCriteria, MinConfidence = step.AiMinConfidence, + RetryDelayMs = step.AiRetryDelayMs, TimeoutSeconds = step.AiTimeoutSeconds, + } : null, }; def.MustKeep.AddRange(step.MustKeep.Items.Select(i => i.Text).Where(s => !string.IsNullOrWhiteSpace(s))); @@ -771,6 +781,26 @@ public class RegionNode : EditorNode /// public class StepNode : EditorNode { + private bool _requireAiConfirmation; + private string _aiCriteria = ""; + private double _aiMinConfidence = 0.85; + private int _aiRetryDelayMs = 3000, _aiTimeoutSeconds = 30; + public bool RequireAiConfirmation { get => _requireAiConfirmation; set => SetProperty(ref _requireAiConfirmation, value); } + public string AiCriteria { get => _aiCriteria; set => SetProperty(ref _aiCriteria, value); } + public double AiMinConfidence { get => _aiMinConfidence; set => SetProperty(ref _aiMinConfidence, value); } + public int AiRetryDelayMs { get => _aiRetryDelayMs; set => SetProperty(ref _aiRetryDelayMs, value); } + public int AiTimeoutSeconds { get => _aiTimeoutSeconds; set => SetProperty(ref _aiTimeoutSeconds, value); } + public AiConfirmation? AiConfirmation + { + set + { + RequireAiConfirmation = value is not null; + if (value is null) return; + AiCriteria = value.Criteria; AiMinConfidence = value.MinConfidence; + AiRetryDelayMs = value.RetryDelayMs; AiTimeoutSeconds = value.TimeoutSeconds; + } + } + private int _id; private string _name = ""; private string _description = ""; diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml index 93d1f37..c97204d 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml @@ -148,6 +148,20 @@ + + + + + + + + + + + + + + diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs index d55bab9..c206e73 100644 --- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs +++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs @@ -23,6 +23,7 @@ namespace SopHelper.VVMs.SopPage; /// public class SopPageViewModel : ViewModelBase { + private static readonly System.Net.Http.HttpClient VisionHttp = new() { Timeout = System.Threading.Timeout.InfiniteTimeSpan }; private const int MaxLogLines = 300; private const int MaxTopViolations = 3; @@ -101,6 +102,7 @@ public class SopPageViewModel : ViewModelBase _camera = camera; _pipeline = pipeline; _engine = engine; + _engine.VisionDecisionClient ??= new ChatCompletionsVisionClient(VisionHttp); _pipeline.ShouldDetectHands = () => _engine.RequiresHandDetection; _dialogs = dialogs; _dispatcher = Dispatcher.CurrentDispatcher; @@ -802,6 +804,16 @@ public class SopPageViewModel : ViewModelBase private void LoadTrainedRecipeModel(SopConfig config) { + var needsObjects = config.Sop.Steps.Any(s => s.Detection?.Method?.ToLowerInvariant() is + ConditionMethod.ObjectPresent or ConditionMethod.ObjectInZone or ConditionMethod.HandNearObject + || s.MustKeep.Count > 0 || s.RequiredObjects.Count > 0); + if (!needsObjects) + { + config.Sop.Model = null; + config.Warnings.Clear(); SopConfigLoader.Validate(config); + Log("info", "当前配方仅使用手部/计时和可选 AI 确认,不加载 YOLO 模型"); + return; + } var recipeName = Path.GetFileNameWithoutExtension(SelectedRecipe); var directory = DesktopPlatform.Recipes.DirectoryFor(recipeName!); config.Sop.Model = SopHelper.Engine.Training.RecipeModelResolver.Load(directory, recipeName!, out var status); @@ -880,7 +892,11 @@ public class SopPageViewModel : ViewModelBase _lastFrame = result; } - _engine.ProcessFrame(result); + _engine.ProcessFrame(result, () => + { + if (_judgementFrame is not { } frame) return []; + return Cv2.ImEncode(".jpg", frame, out var jpeg) ? jpeg : []; + }); // 每帧均更新,无检测结果时清除上一帧的手部标记和目标框。 HandResult = result; @@ -945,7 +961,10 @@ public class SopPageViewModel : ViewModelBase card.IsMet = snapshot.IsMet; card.Message = snapshot.Message; if (snapshot.Elapsed is { } elapsed) card.ElapsedText = FormatDuration(elapsed); - if (snapshot.IsMet && card.CompletionImage is null && _judgementFrame is { } frame) + using var aiEvidence = snapshot.IsMet && snapshot.EvidenceJpeg is { } jpeg + ? Cv2.ImDecode(jpeg, ImreadModes.Color) : null; + var frame = aiEvidence ?? _judgementFrame; + if (snapshot.IsMet && card.CompletionImage is null && frame is not null && !frame.Empty()) { card.CompletionImage = BitmapSource.Create(frame.Width, frame.Height, 96, 96, PixelFormats.Bgr24, null, frame.Data, checked((int)(frame.Step() * frame.Height)), checked((int)frame.Step())); diff --git a/tests/Avalonia.Smoke/Program.cs b/tests/Avalonia.Smoke/Program.cs index d2d3844..99699af 100644 --- a/tests/Avalonia.Smoke/Program.cs +++ b/tests/Avalonia.Smoke/Program.cs @@ -24,12 +24,14 @@ using Avalonia.Input; internal static class Smoke { private static int _exit=1; + private static bool _visionOnly; private static bool _processImagesOnly; private static bool _recipeSelectionOnly; private static readonly FakeCamera Camera=new(); [STAThread] public static int Main(string[] args) { + _visionOnly=args.Contains("--vision-only"); _processImagesOnly=args.Contains("--process-images-only"); _recipeSelectionOnly=args.Contains("--recipe-selection-only"); var previousRoot=Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT"); @@ -77,6 +79,7 @@ internal static class Smoke window.WindowState=WindowState.Normal;window.Width=1180;window.Height=820; await Task.Delay(150); var sop=app.Container.Resolve(); + if(_visionOnly){await CheckVisionConfirmation(app,sop);_exit=0;return;} var sopView=window.GetVisualDescendants().OfType().Single(); Check(!sopView.GetVisualDescendants().Any(c=>c is ComboBox or Slider),"Operator page contains no camera, recipe or parameter editors"); Check(sop.ActiveRecipe=="未应用配方","No recipe is reported active before applying"); @@ -762,6 +765,62 @@ internal static class Smoke } } + private static async Task CheckVisionConfirmation(App app,SopPageViewModel sop) + { + var store=new RecipeWorkspace(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT")!); + var name="手部AI验证";var file=name+".yaml"; + var config=new SopHelper.Engine.Sop.SopConfig();config.Sop.Name=name; + config.Sop.Settings.AutoResetOnComplete=false; + config.Sop.Regions["work"]=new(){X1=0,Y1=0,X2=64,Y2=48}; + config.Sop.Steps.Add(new(){Id=1,Name="装配",Detection=new(){Method="hand_in_region",Region="work",StableFrames=1}, + AiConfirmation=new(){Criteria="红色零件安装到位",MinConfidence=.9,RetryDelayMs=4500,TimeoutSeconds=20}}); + var roundTrip=RecipeNode.From(config,file,false).ToConfig(); + var ai=roundTrip.Sop.Steps[0].AiConfirmation; + Check(ai is {Criteria:"红色零件安装到位",MinConfidence:.9,RetryDelayMs:4500,TimeoutSeconds:20},"AI settings survive editor mapping"); + Directory.CreateDirectory(store.DirectoryFor(name));SopHelper.Engine.Sop.SopConfigLoader.Save(roundTrip,store.ConfigPath(name)); + var editorVm=new RecipeEditorViewModel(); + editorVm.OnDialogOpened(new DialogParameters{{"directory",store.RecipesDirectory},{"path",store.ConfigPath(name)},{"config",roundTrip},{"new",false}}); + var editor=new RecipeEditor{DataContext=editorVm}; + var dialog=new Window{Content=editor,Width=1040,Height=900};dialog.Show();await Task.Delay(80); + try + { + var toggle=editor.GetVisualDescendants().OfType().Single(c=>c.Content?.ToString()=="手部动作触发后由 AI 确认完成"); + Check(toggle.IsChecked==true,"Editor exposes AI confirmation switch"); + toggle.IsChecked=false;await Task.Delay(20); + Check(editorVm.Recipe.ToConfig().Sop.Steps[0].AiConfirmation is null,"Disabling AI restores direct condition evaluation"); + toggle.IsChecked=true;await Task.Delay(20); + Check(editorVm.Recipe.ToConfig().Sop.Steps[0].AiConfirmation?.Criteria==ai!.Criteria,"Re-enabling AI retains completion criteria"); + Save(dialog,"hand-ai-confirmation-settings"); + } + finally{await editorVm.ShutdownAsync();dialog.Close();} + sop.Recipes.Add(file);sop.SelectedRecipe=file;sop.ApplyRecipeCommand.Execute(); + var engine=app.Container.Resolve(); + Check(engine.Config.Sop.Model is null,"Pure hand/AI recipe skips YOLO loading"); + var fake=new UiVisionDecision();engine.VisionDecisionClient=fake; + var receive=typeof(SopPageViewModel).GetMethod("OnResultFrame",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!; + async Task Emit(Scalar color) + { + using(var frame=new Mat(48,64,MatType.CV_8UC3,color)) + receive.Invoke(sop,[new SopHelper.Engine.Common.FrameResult{FrameId=7,Timestamp=DateTime.Now,Size=(64,48),Hands=[new(){Rect=new(20,20,10,10)}]},frame]); + await Task.Delay(40); + } + try + { + sop.IsRunning=true;engine.Start(); + await Emit(new Scalar(0,0,240)); + await fake.Called.Task.WaitAsync(TimeSpan.FromSeconds(5)); + Check(!sop.StepCards[0].HasCompletionImage&&engine.State==SopHelper.Engine.Sop.EngineState.Running,"Hand action alone does not complete a step"); + fake.Result.SetResult(new(true,.98,"红色零件已安装到位")); + for(int i=0;i<100&&engine.State!=SopHelper.Engine.Sop.EngineState.Completed;i++)await Emit(new Scalar(240,0,0)); + Check(engine.State==SopHelper.Engine.Sop.EngineState.Completed&&sop.StepCards[0].HasCompletionImage,"AI confirmation advances actual runtime UI"); + await (Task)typeof(SopPageViewModel).GetField("_completionImageSaves",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!.GetValue(sop)!; + var saved=Directory.GetFiles(Path.Combine(store.DirectoryFor(name),"completion-images"),"*.png").Single(); + using var evidence=Cv2.ImRead(saved);var pixel=evidence.At(0,0); + Check(pixel.Item2>230&&pixel.Item0<10,"Saved image is red AI input, not blue frame at response arrival"); + } + finally{sop.IsRunning=false;engine.Stop();} + } + private static void Save(Window window,string name) { window.UpdateLayout(); @@ -788,3 +847,11 @@ internal sealed class FakeCamera : ICameraService FrameArrived?.Invoke(frame); } } + +internal sealed class UiVisionDecision : SopHelper.Engine.Sop.IVisionDecisionClient +{ + public TaskCompletionSource Called {get;}=new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource Result {get;}=new(TaskCreationOptions.RunContinuationsAsynchronously); + public Task DecideAsync(SopHelper.Engine.Sop.VisionDecisionRequest request,CancellationToken token) + {Called.TrySetResult();return Result.Task;} +}