接入手部与AI确认配方编辑及原判定帧留存
This commit is contained in:
parent
ab82926af6
commit
4a26894ce1
@ -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
|
||||
/// </summary>
|
||||
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 = "";
|
||||
|
||||
@ -148,6 +148,20 @@
|
||||
<TextBlock Text="说明" Classes="Field" />
|
||||
<TextBox Grid.Column="1" Text="{Binding Description, Mode=TwoWay}" />
|
||||
</Grid>
|
||||
<CheckBox Content="手部动作触发后由 AI 确认完成" IsChecked="{Binding RequireAiConfirmation, Mode=TwoWay}" Margin="0,10,0,4" />
|
||||
<StackPanel IsVisible="{Binding RequireAiConfirmation}" Spacing="6">
|
||||
<TextBlock Text="选择手在区域内或手从起点移到终点作为取图触发条件。" TextWrapping="Wrap" />
|
||||
<TextBlock Text="AI 完成判据(明确描述图片上应看到的结果)" />
|
||||
<TextBox Text="{Binding AiCriteria, Mode=TwoWay}" AcceptsReturn="True" TextWrapping="Wrap" MinHeight="64" />
|
||||
<Grid ColumnDefinitions="*,*" RowDefinitions="Auto,Auto,Auto,Auto">
|
||||
<TextBlock Text="最低置信度(0–1)" VerticalAlignment="Center" />
|
||||
<NumericUpDown Grid.Column="1" Value="{Binding AiMinConfidence, Mode=TwoWay}" Minimum="0" Maximum="1" Increment="0.05" FormatString="0.00" />
|
||||
<TextBlock Grid.Row="1" Text="重试间隔(毫秒)" VerticalAlignment="Center" />
|
||||
<NumericUpDown Grid.Row="1" Grid.Column="1" Value="{Binding AiRetryDelayMs, Mode=TwoWay}" Minimum="500" Maximum="600000" Increment="500" />
|
||||
<TextBlock Grid.Row="2" Text="请求超时(秒)" VerticalAlignment="Center" />
|
||||
<NumericUpDown Grid.Row="2" Grid.Column="1" Value="{Binding AiTimeoutSeconds, Mode=TwoWay}" Minimum="1" Maximum="300" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
<CheckBox Content="保存结束图" IsChecked="{Binding SaveCompletionImage, Mode=TwoWay}" Margin="0,8,0,4" />
|
||||
<StackPanel IsEnabled="{Binding SaveCompletionImage}">
|
||||
<TextBlock Text="步骤完成时保存一帧 PNG;目录留空时保存到当前配方的 completion-images 文件夹。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" />
|
||||
|
||||
@ -23,6 +23,7 @@ namespace SopHelper.VVMs.SopPage;
|
||||
/// </summary>
|
||||
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()));
|
||||
|
||||
@ -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<SopPageViewModel>();
|
||||
if(_visionOnly){await CheckVisionConfirmation(app,sop);_exit=0;return;}
|
||||
var sopView=window.GetVisualDescendants().OfType<SopPage>().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<CheckBox>().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<SopHelper.Engine.Sop.SopEngine>();
|
||||
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<Vec3b>(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<SopHelper.Engine.Sop.VisionDecisionResult> Result {get;}=new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public Task<SopHelper.Engine.Sop.VisionDecisionResult> DecideAsync(SopHelper.Engine.Sop.VisionDecisionRequest request,CancellationToken token)
|
||||
{Called.TrySetResult();return Result.Task;}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user