Port the full Windows workflow to one shared Avalonia desktop application

This commit is contained in:
sophelper 2026-11-08 19:55:05 +08:00
parent 528d286b8f
commit ae79ff3a98
44 changed files with 5233 additions and 0 deletions

6
SopHelper.Avalonia.slnx Normal file
View File

@ -0,0 +1,6 @@
<Solution>
<Folder Name="/src/">
<Project Path="src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj" />
<Project Path="src/SopHelper.Avalonia/SopHelper.Avalonia.csproj" />
</Folder>
</Solution>

View File

@ -0,0 +1,9 @@
<prism:PrismApplication xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/" x:Class="SopHelper.App" RequestedThemeVariant="Dark">
<Application.Styles>
<FluentTheme>
<FluentTheme.Palettes><ColorPaletteResources x:Key="Dark" Accent="#00B8D4" /></FluentTheme.Palettes>
</FluentTheme>
<StyleInclude Source="avares://SopHelper.Avalonia/Themes/Styles.axaml" />
</Application.Styles>
</prism:PrismApplication>

View File

@ -0,0 +1,76 @@
using System.Reflection;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using Prism.DryIoc;
using Prism.Ioc;
using Prism.Mvvm;
using SopHelper.Core.Prism;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Pipeline;
using SopHelper.Engine.Sop;
using SopHelper.Models;
using SopHelper.VVMs.MainWindow;
using SopHelper.VVMs.RecipeEditor;
using SopHelper.VVMs.SopPage;
namespace SopHelper;
public partial class App : PrismApplication
{
private ICameraService? _camera;
private DetectionPipeline? _pipeline;
private Engine.Training.WorkerClient? _worker;
public App() { }
public App(ICameraService camera) { _camera=camera; }
public override void Initialize() { AvaloniaXamlLoader.Load(this); base.Initialize(); }
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
AppDomain.CurrentDomain.UnhandledException+=(_,e)=>Log(e.ExceptionObject as Exception,"AppDomain");
Avalonia.Threading.Dispatcher.UIThread.UnhandledException+=(_,e)=>{Log(e.Exception,"Dispatcher");e.Handled=true;};
foreach(var model in Assembly.GetExecutingAssembly().GetTypes().Where(t=>t.GetCustomAttribute<ModelAttribute>()!=null))
containerRegistry.RegisterSingleton(model);
foreach(var view in Assembly.GetExecutingAssembly().GetTypes().Where(t=>t.GetCustomAttribute<NavigationPageAttribute>()!=null))
containerRegistry.RegisterForNavigation(view,view.Name);
containerRegistry.RegisterSingleton<NavigationModel>();
_camera??=new CameraService();_pipeline=new DetectionPipeline(_camera);
containerRegistry.RegisterInstance<ICameraService>(_camera);
containerRegistry.RegisterInstance(_pipeline);
containerRegistry.RegisterSingleton<SopEngine>();
containerRegistry.RegisterSingleton<SopPageViewModel>();
_worker=new Engine.Training.WorkerClient();containerRegistry.RegisterInstance(_worker);
containerRegistry.RegisterSingleton<Training.MainViewModel>();
containerRegistry.RegisterDialog<RecipeEditor,RecipeEditorViewModel>("RecipeEditorDialog");
containerRegistry.RegisterDialogWindow<RecipeDialogWindow>();
}
protected override AvaloniaObject CreateShell()
{
var navigation=Container.Resolve<NavigationModel>();
foreach(var type in Assembly.GetExecutingAssembly().GetTypes().Where(t=>t.GetCustomAttribute<NavigationPageAttribute>()!=null)
.OrderBy(t=>t.GetCustomAttribute<NavigationPageAttribute>()!.Index))
{
var page=type.GetCustomAttribute<NavigationPageAttribute>()!;
var item=Container.Resolve<NavigateItem>();item.ViewName=page.ViewName;item.DisplayName=page.DisplayName;navigation.Pages.Add(item);
}
var window=Container.Resolve<MainWindow>();
window.Opened+=(_,_)=> { if(navigation.Pages.Count>0) navigation.SelectedIndex=0; };
window.Closed+=(_,_)=>
{
_worker?.Dispose();
try{_camera?.Dispose();}catch(Exception ex){Log(ex,"Exit.Camera");}
try{_pipeline?.Dispose();}catch(Exception ex){Log(ex,"Exit.Pipeline");}
};
return window;
}
protected override void ConfigureViewModelLocator()
{
base.ConfigureViewModelLocator();
ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver(t=>Type.GetType($"{t.FullName}ViewModel, {t.Assembly.FullName}"));
}
private static void Log(Exception? exception,string from)
{
if(exception is null)return;
var line=$"[{DateTime.Now:HH:mm:ss.fff}] [{from}] {exception.Message}";Console.WriteLine(line);
try{Directory.CreateDirectory("logs");File.AppendAllText(Path.Combine("logs","error.log"),line+Environment.NewLine);}catch{ }
}
}

View File

@ -0,0 +1,165 @@
<ResourceDictionary xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:conv="using:Avalonia.Data.Converters">
<DrawingImage x:Key="BellwetherLogo">
<DrawingImage.Drawing>
<DrawingGroup>
<GeometryDrawing Brush="Transparent" Geometry="M0,0 H380 V120 H0 Z" />
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.08,0,0,1.08,-40.6,-75.6892" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#2B387C" Geometry="F0 M58.0 108.0C63.12 107.93 68.25 107.87 73.37 107.84C75.11 107.82 76.85 107.8 78.59 107.77C81.1 107.74 83.61 107.72 86.12 107.71C86.51 107.7 86.51 107.7 88.45 107.66C93.94 107.66 97.99000000000001 108.74 103.0 111.0C105.0 113.0 105.0 113.0 105.44 116.81C105.35 120.28 105.03999999999999 120.95 102.81 123.88C100.22 125.84 98.09 127.03 95.0 128.0C95.83 128.52 96.65 129.03 97.5 129.56C100.0 132.0 100.0 132.0 100.62 135.44C99.82 140.01 98.69 141.21 95.0 144.0C87.73 147.84 81.72 149.15 73.52 149.1C72.7 149.1 71.88 149.09 71.03999999999999 149.09C68.45 149.09 65.85 149.07999999999998 63.25 149.06C61.49 149.06 59.72 149.05 57.96 149.05C53.64 149.04 49.32 149.02 45.0 149.0C47.31 139.96 50.21 131.15 53.19 122.31C53.66 120.92 54.12 119.52 54.59 118.13C55.72 114.75 56.86 111.37 58.0 108.0ZM63.0 130.0C65.75 129.92 68.5 129.86 71.25 129.81C72.03 129.79 72.8 129.76 73.61 129.74C79.43 129.66 79.43 129.66 82.55 131.51C83.03 132.0 83.51 132.49 84.0 133.0C83.83 137.35 83.5 139.45 80.53 142.72C76.49 145.88 72.55 145.57 67.62 145.31C66.79 145.29 65.96 145.27 65.11 145.24C63.07 145.19 61.03 145.1 59.0 145.0C59.48 143.06 59.96 141.12 60.44 139.19C60.7 138.11 60.97 137.03 61.25 135.92C61.76 133.93 62.35 131.95 63.0 130.0ZM69.0 111.0C71.4 110.92 73.79 110.86 76.19 110.81C76.86 110.79 77.53 110.76 78.23 110.74C82.71000000000001 110.67 85.4 111.31 89.0 114.0C90.0 115.0 90.0 115.0 90.38 117.25C89.84 121.16 87.96000000000001 122.52 85.0 125.0C82.28999999999999 125.9 80.76 126.12 77.99 126.1C77.61 126.1 77.61 126.1 75.69 126.09C74.91 126.08 74.12 126.07 73.31 126.06C72.52 126.06 71.72 126.05 70.9 126.05C68.93 126.03999999999999 66.97 126.02 65.0 126.0C65.56 122.23 66.31 118.73 67.56 115.12C67.83 114.34 68.1 113.56 68.38 112.76C68.58 112.18 68.79 111.6 69.0 111.0Z" />
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,108.0,108.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#253278" Geometry="F1 M0 0 C4.29 0 8.58 0 13 0 C12.67 6.6 12.34 13.2 12 20 C13.4 17.53 14.81 15.05 16.25 12.5 C20.61 5.42 20.61 5.42 25.34 4 C28.62 4.06 28.62 4.06 34 5 C34.16 7.64 34.16 7.64 35 21 C35.27 20.45 35.27 20.45 36.64 17.68 C37.37 16.22 38.09 14.77 38.81 13.31 C39.17 12.59 39.53 11.87 39.89 11.13 C40.59 9.72 41.31 8.31 42.03 6.91 C42.85 5.29 43.62 3.65 44.38 2 C46 0 46 0 48.92 -0.49 C50 -0.43 51.08 -0.37 52.19 -0.31 C53.27 -0.27 54.36 -0.22 55.48 -0.18 C56.31 -0.12 57.14 -0.06 58 0 C53.27 10.09 48.48 20.15 43.5 30.12 C43.07 31 42.63 31.87 42.19 32.76 C41.79 33.57 41.38 34.37 40.97 35.2 C40.61 35.91 40.26 36.62 39.89 37.35 C39 39 39 39 38 40 C35.98 40.07 33.96 40.08 31.94 40.06 C31.39 40.06 31.39 40.06 28.59 40.04 C27.74 40.02 26.88 40.01 26 40 C25.94 39.4 25.89 38.8 25.83 38.18 C25.58 35.47 25.32 32.77 25.06 30.06 C24.98 29.12 24.89 28.17 24.8 27.2 C24.71 26.3 24.62 25.4 24.54 24.47 C24.46 23.64 24.38 22.81 24.3 21.95 C24 20 24 20 23 19 C20.85 22.29 18.71 25.58 16.56 28.88 C16.26 29.34 16.26 29.34 14.71 31.71 C14.13 32.61 13.54 33.51 12.94 34.43 C12.4 35.26 11.86 36.08 11.31 36.94 C10 39 10 39 9 41 C4.71 41 0.42 41 -4 41 C-3.37 30.27 -2.32 19.67 -1 9 C-0.66 6 -0.33 3 0 0 Z " />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,175.75,77.5625" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#D13A2E" Geometry="F1 M0 0 C0.48 -0.01 0.48 -0.01 2.9 -0.07 C10.94 -0.04 17.42 1.99 24.19 6.31 C28.61 10.87 29.42 14.58 29.44 20.81 C29.39 22.69 29.33 24.56 29.25 26.44 C25.62 26.44 21.99 26.44 18.25 26.44 C17.86 25.36 17.47 24.29 17.06 23.19 C15.45 19.49 13.78 17.56 10.25 15.44 C-8.16 8.49 -29.61 16.24 -46.75 23.44 C-47.19 23.71 -47.19 23.71 -49.43 25.11 C-54.58 27.17 -59.64 26.75 -65.12 26.62 C-65.68 26.62 -65.68 26.62 -68.51 26.58 C-71.26 26.55 -74 26.5 -76.75 26.44 C-73.33 22.84 -69.82 20.7 -65.38 18.56 C-64.67 18.22 -63.96 17.87 -63.22 17.51 C-61.07 16.48 -58.91 15.45 -56.75 14.44 C-55.57 13.88 -54.4 13.33 -53.18 12.76 C-44.91 9.05 -36.51 6.3 -27.75 3.97 C-25.95 3.49 -24.16 2.98 -22.37 2.46 C-14.9 0.54 -7.69 0.11 0 0 Z " />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,185.390625,107.90234375" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#263378" Geometry="F1 M0 0 C0.35 0 0.35 0 2.14 0 C4.38 0.01 6.62 0.02 8.86 0.04 C10.38 0.04 11.91 0.04 13.43 0.05 C17.16 0.06 20.88 0.08 24.61 0.1 C23.62 3.07 22.63 6.04 21.61 9.1 C20.77 9.12 19.93 9.14 19.07 9.16 C15.97 9.24 12.86 9.32 9.76 9.42 C7.75 9.47 5.74 9.52 3.74 9.57 C3.11 9.59 3.11 9.59 -0.07 9.68 C-1.23 9.72 -2.4 9.75 -3.59 9.78 C-6.39 10.1 -6.39 10.1 -8.39 12.1 C-8.39 13.09 -8.39 14.08 -8.39 15.1 C-7.16 15.14 -5.93 15.17 -4.66 15.21 C-3.03 15.28 -1.4 15.34 0.23 15.41 C1.04 15.43 1.85 15.46 2.68 15.48 C7.67 15.7 11.29 16.34 15.61 19.1 C17.22 22.32 17.07 25.6 16.61 29.1 C14.1 34.21 10.45 37.28 5.61 40.1 C1.91 41.33 -1.49 41.22 -5.34 41.2 C-6.11 41.19 -6.89 41.19 -7.68 41.19 C-10.15 41.19 -12.61 41.17 -15.08 41.16 C-16.75 41.16 -18.42 41.15 -20.1 41.15 C-24.19 41.14 -28.29 41.12 -32.39 41.1 C-31.4 38.13 -30.41 35.16 -29.39 32.1 C-28.46 32.08 -27.53 32.06 -26.58 32.04 C-23.14 31.96 -19.7 31.87 -16.26 31.78 C-14.77 31.74 -13.28 31.71 -11.79 31.68 C-9.65 31.63 -7.51 31.57 -5.37 31.51 C-4.08 31.48 -2.79 31.45 -1.46 31.42 C1.61 31.1 1.61 31.1 3.61 29.1 C3.61 28.11 3.61 27.12 3.61 26.1 C3.29 26.09 3.29 26.09 1.67 26.07 C-1.25 26.02 -4.16 25.93 -7.08 25.85 C-8.09 25.83 -9.09 25.82 -10.13 25.8 C-14.59 25.66 -17.62 25.53 -21.56 23.32 C-24.16 20.16 -24.05 18.29 -23.8 14.34 C-23 9.97 -20.99 7.31 -17.48 4.66 C-11.48 0.72 -7.23 -0.03 0 0 Z " />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,55.0,153.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#D13A2D" Geometry="F1 M0 0 C2.42 -0.16 4.83 -0.28 7.25 -0.38 C7.93 -0.43 8.61 -0.48 9.32 -0.53 C11.33 -0.59 11.33 -0.59 15 0 C17.24 2.84 17.24 2.84 19 6 C26.15 12.65 36.47 11.67 45.56 11.36 C52.28 11 58.53 9.85 65 8 C65.87 7.77 66.75 7.54 67.65 7.31 C72.34 6.01 76.68 4.29 81.12 2.31 C86.1 0.17 89.63 -0.52 95 0 C92.77 2.5 90.79 3.71 87.68 4.94 C86.84 5.28 85.99 5.61 85.12 5.96 C84.23 6.3 83.35 6.65 82.44 7 C81.58 7.34 80.72 7.69 79.84 8.04 C59.97 15.87 34.34 23.1 13.27 16.04 C7.96 13.6 4.12 10.78 1 5.81 C0 3 0 3 0 0 Z " />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,150.0,153.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#D34338" Geometry="F1 M0 0 C-3.24 3.54 -6.88 4.94 -11.25 6.75 C-11.99 7.08 -12.73 7.41 -13.49 7.75 C-18.5 9.84 -21.69 10.26 -27 9 C-23.59 6.13 -19.84 4.47 -15.75 2.81 C-15.43 2.68 -15.43 2.68 -13.84 1.99 C-9.04 0.04 -5.17 -0.26 0 0 Z " />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,88.0,165.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#D86359" Geometry="F1 M0 0 C2.75 -0.11 5.5 -0.19 8.25 -0.25 C9.03 -0.28 9.8 -0.32 10.61 -0.35 C16.43 -0.45 16.43 -0.45 19.55 2.02 C20.03 2.67 20.51 3.33 21 4 C20.17 3.84 20.17 3.84 16 3 C16 2.34 16 1.68 16 1 C10.72 1 5.44 1 0 1 C0 0.67 0 0.34 0 0 Z " />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,131.0,159.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#D0392D" Geometry="F1 M0 0 C-0.33 1.32 -0.66 2.64 -1 4 C-3.31 3.67 -5.62 3.34 -8 3 C-4.94 0.38 -4.27 0 0 0 Z " />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,150.0,153.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#D04337" Geometry="F1 M0 0 C-2.23 2.5 -4.21 3.71 -7.32 4.94 C-7.74 5.11 -7.74 5.11 -9.88 5.96 C-10.77 6.3 -11.65 6.65 -12.56 7 C-13.42 7.34 -14.28 7.69 -15.16 8.04 C-21.02 10.35 -26.94 12.28 -33 14 C-33.73 14.22 -34.46 14.44 -35.21 14.66 C-39.15 15.77 -42.06 16.23 -46 15 C-46 14.34 -46 13.68 -46 13 C-51.28 13 -56.56 13 -62 13 C-62 12.67 -62 12.34 -62 12 C-61.43 11.98 -61.43 11.98 -58.55 11.89 C-48.71 11.49 -39.56 10.51 -30 8 C-29.12 7.77 -28.24 7.55 -27.34 7.31 C-22.65 6 -18.32 4.28 -13.88 2.31 C-8.9 0.17 -5.37 -0.52 0 0 Z " />
</DrawingGroup>
</DrawingGroup>
<DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="0.2226833,0,0,-0.2070485,195.76487,60.23789" />
</DrawingGroup.Transform>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,0.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M201 178Q201 83 202 55L187 48V184H78V48L63 42Q64 80 64.0 119.5Q64 159 63 198L79 190H186L196 200L211 185ZM28 -19Q88 6 102.5 28.5Q117 51 120.0 83.5Q123 116 122 164L147 152L138 145Q138 70 121.5 35.0Q105 0 29 -23ZM147 43Q190 27 208.0 14.0Q226 1 223.0 -9.5Q220 -20 216 -20Q214 -20 210 -15Q201 -3 187.0 10.0Q173 23 146 39Z">
<GeometryDrawing.Pen>
<Pen Brush="#FFFFFF" LineJoin="Round" Thickness="5" />
</GeometryDrawing.Pen>
</GeometryDrawing>
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,256.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M244 -4V-8Q227 -8 219 -19Q176 27 165 109H158Q153 53 130.0 23.5Q107 -6 63 -23L62 -20Q101 3 120.0 31.0Q139 59 144 109H115Q102 109 91 106L82 115H144Q146 146 146 176Q115 174 91 172V176Q114 179 133.0 182.0Q152 185 173.5 190.5Q195 196 207 203L224 186Q205 185 160 178Q160 147 158 115H208L224 130L243 109H170Q195 12 244 -4ZM86 161Q57 56 54.5 43.5Q52 31 52 13Q52 -5 51.5 -10.5Q51 -16 48 -16Q45 -16 38.5 -12.5Q32 -9 32 -2Q32 5 34 11Q37 20 37 26Q37 32 33.0 36.0Q29 40 14 45V49Q29 47 34.5 47.0Q40 47 46.0 58.0Q52 69 82 162ZM14 138Q45 123 44.5 113.5Q44 104 41.0 100.5Q38 97 36 97Q33 97 30 106Q26 118 12 136ZM36 200Q58 190 61.5 185.5Q65 181 65 177Q65 172 62.0 166.5Q59 161 57 161Q54 161 52 169Q47 182 34 198Z">
<GeometryDrawing.Pen>
<Pen Brush="#FFFFFF" LineJoin="Round" Thickness="5" />
</GeometryDrawing.Pen>
</GeometryDrawing>
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,512.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M76 66 99 56 91 49V13Q90 -3 103 -1H169Q181 0 182.5 13.0Q184 26 185 45H190Q191 23 193.5 13.5Q196 4 204 2Q196 -16 167 -14H98Q76 -16 77 6Q77 49 76 66ZM106 76 108 79Q126 72 135.0 66.0Q144 60 145.0 53.5Q146 47 142.5 41.5Q139 36 137 36Q134 36 131 44Q126 56 106 76ZM197 54 199 57Q219 47 229.0 39.0Q239 31 239.0 23.0Q239 15 235.0 10.5Q231 6 230 6Q226 6 222 18Q216 34 197 54ZM46 59H50Q50 34 48.0 22.0Q46 10 40.5 6.5Q35 3 30 3Q26 3 22.5 4.5Q19 6 19 7Q19 11 27 19Q39 31 46 59ZM67 188V143H122V188ZM136 188V143H190V188ZM67 137V93H122V137ZM136 137V93H190V137ZM204 185V118Q204 98 205 80L190 74V87H67V77L52 71Q53 101 53.0 142.5Q53 184 52 203L67 194H188L195 204L212 192Z">
<GeometryDrawing.Pen>
<Pen Brush="#FFFFFF" LineJoin="Round" Thickness="5" />
</GeometryDrawing.Pen>
</GeometryDrawing>
</DrawingGroup>
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="0.0123755,0,0,-0.0129604,196.14367,101.0" />
</DrawingGroup.Transform>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,0.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M150 1466H736Q910 1466 995.5 1451.5Q1081 1437 1148.5 1391.0Q1216 1345 1261.0 1268.5Q1306 1192 1306 1097Q1306 994 1250.5 908.0Q1195 822 1100 779Q1234 740 1306.0 646.0Q1378 552 1378 425Q1378 325 1331.5 230.5Q1285 136 1204.5 79.5Q1124 23 1006 10Q932 2 649 0H150ZM446 1222V883H640Q813 883 855 888Q931 897 974.5 940.5Q1018 984 1018 1055Q1018 1123 980.5 1165.5Q943 1208 869 1217Q825 1222 616 1222ZM446 639V247H720Q880 247 923 256Q989 268 1030.5 314.5Q1072 361 1072 439Q1072 505 1040.0 551.0Q1008 597 947.5 618.0Q887 639 685 639Z" />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,1479.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M149 0V1466H1236V1218H445V893H1181V646H445V247H1264V0Z" />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,2845.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M157 0V1454H453V247H1189V0Z" />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,4096.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M157 0V1454H453V247H1189V0Z" />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,5347.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M357 0 7 1466H310L531 459L799 1466H1151L1408 442L1633 1466H1931L1575 0H1261L969 1096L678 0Z" />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,7280.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M149 0V1466H1236V1218H445V893H1181V646H445V247H1264V0Z" />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,8646.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M479 0V1218H44V1466H1209V1218H775V0Z" />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,9897.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M150 0V1466H446V889H1026V1466H1322V0H1026V641H446V0Z" />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,11376.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M149 0V1466H1236V1218H445V893H1181V646H445V247H1264V0Z" />
</DrawingGroup>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1.0,0,0,1.0,12742.0,0.0" />
</DrawingGroup.Transform>
<GeometryDrawing Brush="#FFFFFF" Geometry="F1 M150 0V1466H773Q1008 1466 1114.5 1426.5Q1221 1387 1285.0 1286.0Q1349 1185 1349 1055Q1349 890 1252.0 782.5Q1155 675 962 647Q1058 591 1120.5 524.0Q1183 457 1289 286L1468 0H1114L900 319Q786 490 744.0 534.5Q702 579 655.0 595.5Q608 612 506 612H446V0ZM446 846H665Q878 846 931.0 864.0Q984 882 1014.0 926.0Q1044 970 1044 1036Q1044 1110 1004.5 1155.5Q965 1201 893 1213Q857 1218 677 1218H446Z" />
</DrawingGroup>
</DrawingGroup>
</DrawingGroup>
</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
</ResourceDictionary>

View File

@ -0,0 +1,39 @@
namespace SopHelper.Core.Prism;
/// <summary>
/// 标志此特性的类会被注册为单例(照搬 plcsharp 约定)
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class ModelAttribute : Attribute
{
}
/// <summary>
/// 标志此特性的 View 会被注册到导航列表
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class NavigationPageAttribute : Attribute
{
/// <summary>
/// 视图名称(导航用)
/// </summary>
public string ViewName { get; set; } = "";
/// <summary>
/// Display名称
/// </summary>
public string DisplayName { get; set; } = "";
/// <summary>
/// 排序序号
/// </summary>
public int Index { get; set; }
}
/// <summary>
/// 标志此特性的类会被注册为弹出窗口
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class DialogAttribute : Attribute
{
}

View File

@ -0,0 +1,61 @@
using Prism.Events;
namespace SopHelper.Core.Prism;
/// <summary>
/// 全局消息事件(照搬 plcsharp:模块间解耦都走事件聚合器)
/// </summary>
public class MessageEvent : PubSubEvent<Message>
{
}
/// <summary>
/// 消息内容
/// </summary>
public struct Message
{
/// <summary>
/// 消息目标
/// </summary>
public string Target { get; set; }
/// <summary>
/// 消息
/// </summary>
public string Content { get; set; }
/// <summary>
/// 消息类型 1 记录 2 弹出 3 弹出并记录
/// </summary>
public ShowType Type { get; set; }
/// <summary>
/// 级别
/// </summary>
public MsgLevel Level { get; set; }
}
/// <summary>
/// 显示方式
/// </summary>
public enum ShowType
{
/// <summary>仅记录日志</summary>
Log = 1,
/// <summary>仅提示</summary>
Show = 2,
/// <summary>提示并记录</summary>
Both = 3,
}
/// <summary>
/// 消息级别
/// </summary>
public enum MsgLevel
{
Info,
Warn,
Error,
}

View File

@ -0,0 +1,48 @@
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
namespace SopHelper.Core.Prism;
/// <summary>
/// 模型Base
/// </summary>
public class ModelBase : BindableBase
{
/// <summary>
/// 事件聚合器
/// </summary>
protected readonly IEventAggregator _eventAggregator;
/// <summary>
/// DI 容器
/// </summary>
protected readonly IContainerExtension _container;
/// <summary>
/// 模型Base
/// </summary>
public ModelBase(IContainerExtension container, IEventAggregator ea)
{
_container = container;
_eventAggregator = ea;
_eventAggregator.GetEvent<MessageEvent>().Subscribe(OnMessage, ThreadOption.PublisherThread, true);
AppDomain.CurrentDomain.ProcessExit += OnExit;
}
/// <summary>
/// 收到消息(子类覆写做本模块的落库/统计)
/// </summary>
protected virtual void OnMessage(Message message)
{
}
/// <summary>
/// 进程退出(子类覆写做释放)
/// </summary>
protected virtual void OnExit(object? sender, EventArgs e)
{
}
}

View File

@ -0,0 +1,31 @@
using Prism.Mvvm;
namespace SopHelper.Core.Prism;
/// <summary>
/// Navigate项
/// </summary>
public class NavigateItem : BindableBase
{
private string _viewName = "";
/// <summary>
/// 视图名称
/// </summary>
public string ViewName
{
get { return _viewName; }
set { SetProperty(ref _viewName, value); }
}
private string _displayName = "";
/// <summary>
/// Display名称
/// </summary>
public string DisplayName
{
get { return _displayName; }
set { SetProperty(ref _displayName, value); }
}
}

View File

@ -0,0 +1,17 @@
using Prism.Mvvm;
using Prism.Navigation;
namespace SopHelper.Core.Prism;
/// <summary>
/// 视图模型Base
/// </summary>
public abstract class ViewModelBase : BindableBase, IDestructible
{
/// <summary>
/// Destroy
/// </summary>
public virtual void Destroy()
{
}
}

View File

@ -0,0 +1,28 @@
using System.Text.Json;
using OpenCvSharp;
using SopHelper.Engine.Common;
using SopHelper.Engine.Inference;
using SopHelper.Engine.Sop;
namespace SopHelper.Diagnostics;
internal static class RuntimeCheck
{
public static int Run()
{
try
{
var root=AppContext.BaseDirectory;
using var yolo=new YoloDetector();using var hand=new MediaPipeHandDetector();
yolo.Load(Path.Combine(root,"models/yolo11n.onnx"),[],preferGpu:false);
hand.Load(Path.Combine(root,"models/palm_detection_full_Nx3x192x192_post.onnx"),Path.Combine(root,"models/hand_landmark_sparse_Nx3x224x224.onnx"),false);
if(!yolo.IsReady||!hand.IsReady)throw new InvalidOperationException("模型未加载");
using var frame=new Mat(480,640,MatType.CV_8UC3,Scalar.Black);yolo.Detect(frame);hand.Detect(frame);
var config=SopConfigLoader.Parse("sop:\n name: runtime-check\n settings:\n auto_reset_on_complete: false\n steps:\n - id: 1\n name: timer\n detection:\n method: time_elapsed\n duration_ms: 1\n");
var engine=new SopEngine();engine.Load(config);engine.Start();Thread.Sleep(10);engine.ProcessFrame(new FrameResult());
if(engine.State!=EngineState.Completed)throw new Exception("SOP 状态机测试失败");
Console.WriteLine(JsonSerializer.Serialize(new{passed=true,opencv=Cv2.GetVersionString(),classes=yolo.ClassNames.Count,hand=hand.IsReady,sop=engine.State.ToString()}));return 0;
}
catch(Exception error){Console.Error.WriteLine(error);return 1;}
}
}

View File

@ -0,0 +1,80 @@
using System.Collections.ObjectModel;
using Prism.Events;
using Prism.Ioc;
using Prism.Navigation.Regions;
using SopHelper.Core.Prism;
namespace SopHelper.Models;
/// <summary>
/// Navigate模型
/// </summary>
[Model]
public class NavigationModel : ModelBase
{
private readonly IRegionManager _regionManager;
/// <summary>
/// Navigate模型
/// </summary>
public NavigationModel(IContainerExtension container, IEventAggregator ea, IRegionManager regionManager)
: base(container, ea)
{
_regionManager = regionManager;
}
private ObservableCollection<NavigateItem> _pages = [];
/// <summary>
/// 导航页列表(shell 侧栏绑定)
/// </summary>
public ObservableCollection<NavigateItem> Pages
{
get { return _pages; }
set { SetProperty(ref _pages, value); }
}
private NavigateItem? _target;
/// <summary>
/// 当前页
/// </summary>
public NavigateItem? Target
{
get { return _target; }
set { SetProperty(ref _target, value); }
}
private int _selectedIndex = -1;
/// <summary>
/// 侧栏选中索引
/// </summary>
public int SelectedIndex
{
get { return _selectedIndex; }
set
{
if (!SetProperty(ref _selectedIndex, value)) return;
if (value >= 0 && value < Pages.Count) Navigate(Pages[value].ViewName);
}
}
/// <summary>
/// 导航到指定页
/// </summary>
public void Navigate(string viewName)
{
if (string.IsNullOrEmpty(viewName)) return;
Target = Pages.FirstOrDefault(n => n.ViewName == viewName);
if (Target is null) return;
_regionManager.RequestNavigate(ContentRegion, viewName);
}
/// <summary>
/// 内容区名(shell 与导航的唯一约定)
/// </summary>
public const string ContentRegion = "ContentRegion";
}

View File

@ -0,0 +1,62 @@
using System.Diagnostics;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Platform.Storage;
namespace SopHelper.Presentation;
internal static class DesktopPlatform
{
public static Window Owner => ((IClassicDesktopStyleApplicationLifetime)Avalonia.Application.Current!.ApplicationLifetime!).MainWindow!;
public static string PythonPath
{
get
{
var relative=OperatingSystem.IsWindows()?Path.Combine("python","python.exe"):Path.Combine("python","bin","python3");
var bundled=Path.Combine(AppContext.BaseDirectory,relative);
if(File.Exists(bundled))return bundled;
// Source-tree builds use the same repository-managed runtime; published apps bundle it.
for(var directory=new DirectoryInfo(AppContext.BaseDirectory);directory is not null;directory=directory.Parent)
if(File.Exists(Path.Combine(directory.FullName,"SopHelper.Avalonia.slnx")))return Path.Combine(directory.FullName,relative);
return bundled;
}
}
public static void Reveal(string path)
{
var directory=File.Exists(path)?Path.GetDirectoryName(path)!:path;
var info=new ProcessStartInfo(OperatingSystem.IsWindows()?"explorer.exe":"xdg-open") { UseShellExecute=false };
info.ArgumentList.Add(directory); Process.Start(info);
}
}
public sealed class OpenFileDialog
{
public string Title { get; set; } = "选择文件";
public string Filter { get; set; } = "所有文件|*.*";
public string DefaultExt { get; set; } = "";
public bool CheckFileExists { get; set; } = true;
public bool Multiselect { get; set; }
public string InitialDirectory { get; set; } = "";
public string FileName { get; set; } = "";
public async Task<bool?> ShowDialogAsync()
{
var storage=DesktopPlatform.Owner.StorageProvider;
var filters=Filter.Split('|');var types=new List<FilePickerFileType>();
for(var i=0;i+1<filters.Length;i+=2) types.Add(new FilePickerFileType(filters[i]) { Patterns=filters[i+1].Split(';') });
var files=await storage.OpenFilePickerAsync(new FilePickerOpenOptions { Title=Title,AllowMultiple=Multiselect,
FileTypeFilter=types,SuggestedStartLocation=Directory.Exists(InitialDirectory)?await storage.TryGetFolderFromPathAsync(InitialDirectory):null });
if(files.Count==0)return false; FileName=files[0].TryGetLocalPath()??throw new IOException("请选择本地文件");return true;
}
}
public sealed class OpenFolderDialog
{
public string Title { get; set; } = "选择文件夹";
public string InitialDirectory { get; set; } = "";
public string FolderName { get; private set; } = "";
public async Task<bool?> ShowDialogAsync()
{
var storage=DesktopPlatform.Owner.StorageProvider;
var folders=await storage.OpenFolderPickerAsync(new FolderPickerOpenOptions { Title=Title,AllowMultiple=false,
SuggestedStartLocation=Directory.Exists(InitialDirectory)?await storage.TryGetFolderFromPathAsync(InitialDirectory):null });
if(folders.Count==0)return false; FolderName=folders[0].TryGetLocalPath()??throw new IOException("请选择本地文件夹");return true;
}
}

View File

@ -0,0 +1,81 @@
using System.Runtime.InteropServices;
using Avalonia;
using Avalonia.Media;
using Avalonia.Platform;
using NativeBitmap = Avalonia.Media.Imaging.Bitmap;
using NativeWritableBitmap = Avalonia.Media.Imaging.WriteableBitmap;
namespace SopHelper.Presentation.Imaging;
// Keeps the original acquisition/rendering ownership contract while using Avalonia bitmaps.
// Immutable snapshots can be created by acquisition threads; mutable previews are UI-thread owned.
public class BitmapSource : IImage, IDisposable
{
protected NativeBitmap? Native;
public int PixelWidth => Native?.PixelSize.Width ?? 0;
public int PixelHeight => Native?.PixelSize.Height ?? 0;
public Size Size => Native?.Size ?? default;
public void Draw(DrawingContext context, Rect sourceRect, Rect destRect)
{ if (Native is not null) context.DrawImage(Native,sourceRect,destRect); }
public BitmapSource Clone()
{
using var stream = new MemoryStream(); Native!.Save(stream); stream.Position=0;
return new BitmapSource { Native = new NativeBitmap(stream) };
}
public void Freeze() { /* Avalonia Bitmap snapshots are immutable already. */ }
public void Save(string path) => Native!.Save(path);
public void Dispose() { Native?.Dispose(); Native=null; GC.SuppressFinalize(this); }
public static BitmapSource Create(int width,int height,double dpiX,double dpiY,PixelFormat format,object? palette,
IntPtr data,int bufferSize,int stride)
{
if (bufferSize < checked(stride*height)) throw new ArgumentException("图像缓冲不足");
var input=new byte[bufferSize];Marshal.Copy(data,input,0,bufferSize);
using var converted=new WriteableBitmap(width,height,dpiX,dpiY,format,palette);
converted.WritePixels(new PixelRect(0,0,width,height),input,stride,0);
return converted.Snapshot();
}
public static unsafe BitmapSource Create(int width,int height,double dpiX,double dpiY,PixelFormat format,object? palette,byte[] bytes,int stride)
{fixed(byte* data=bytes)return Create(width,height,dpiX,dpiY,format,palette,(IntPtr)data,bytes.Length,stride);}
}
public enum BitmapCacheOption { OnLoad }
public sealed class BitmapImage : BitmapSource
{
public Uri? UriSource { get; set; }
public BitmapCacheOption CacheOption { get; set; }
public void BeginInit() { }
public void EndInit() { Native?.Dispose(); Native = new NativeBitmap(UriSource!.LocalPath); }
}
public sealed class WriteableBitmap : BitmapSource
{
public WriteableBitmap(int width,int height,double dpiX,double dpiY,PixelFormat format,object? palette)
{ Native = new NativeWritableBitmap(new PixelSize(width,height),new Vector(dpiX,dpiY),format,AlphaFormat.Opaque); }
public void WritePixels(PixelRect rect,byte[] bytes,int stride,int offset)
{
using var framebuffer=((NativeWritableBitmap)Native!).Lock();
if (rect.X!=0 || rect.Y!=0 || rect.Width!=PixelWidth || rect.Height!=PixelHeight) throw new ArgumentException("预览需写入完整帧");
var rowBytes=new byte[rect.Width*4];
for(var row=0;row<rect.Height;row++)
{
for(var x=0;x<rect.Width;x++)
{var source=offset+row*stride+x*3;var target=x*4;rowBytes[target]=bytes[source];rowBytes[target+1]=bytes[source+1];rowBytes[target+2]=bytes[source+2];rowBytes[target+3]=255;}
Marshal.Copy(rowBytes,0,framebuffer.Address+row*framebuffer.RowBytes,rowBytes.Length);
}
}
internal BitmapSource Snapshot()
{
using var framebuffer=((NativeWritableBitmap)Native!).Lock();
return FromPixels(framebuffer.Address,PixelWidth,PixelHeight,framebuffer.RowBytes);
}
private static BitmapSource FromPixels(IntPtr address,int width,int height,int stride)=>
new OwnedSnapshot(address,width,height,stride);
private sealed class OwnedSnapshot : BitmapSource
{
public OwnedSnapshot(IntPtr address,int width,int height,int stride)
{Native=new NativeBitmap(PixelFormat.Bgra8888,AlphaFormat.Opaque,address,new PixelSize(width,height),new Vector(96,96),stride);}
}
}
public static class PixelFormats
{
// Public acquisition buffers are BGR24; the adapter expands them to Avalonia's BGRA surface.
public static PixelFormat Bgr24 => PixelFormat.Bgra8888;
}

View File

@ -0,0 +1,13 @@
using System.Globalization;
using Avalonia.Data;
using Avalonia.Data.Converters;
namespace SopHelper.Presentation;
public sealed class SelectionConverter : IValueConverter
{
public object? Convert(object? value,Type targetType,object? parameter,CultureInfo culture)=>value;
// Avalonia clears selection while attaching/replacing an ItemsSource. That transient
// null must not erase a recipe field. Selecting the explicit empty-string item still works.
public object? ConvertBack(object? value,Type targetType,object? parameter,CultureInfo culture)=>value??BindingOperations.DoNothing;
}

View File

@ -0,0 +1,28 @@
namespace SopHelper.Presentation.Threading;
// UI scheduling is shared by both targets. No Win32/WPF dispatcher is involved.
public enum DispatcherPriority { Normal, Background }
public sealed class Dispatcher
{
public static Dispatcher CurrentDispatcher { get; } = new();
public bool HasShutdownStarted => Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime { MainWindow: null };
public void BeginInvoke(Action action, DispatcherPriority priority = DispatcherPriority.Normal) =>
Avalonia.Threading.Dispatcher.UIThread.Post(action, priority == DispatcherPriority.Background
? Avalonia.Threading.DispatcherPriority.Background : Avalonia.Threading.DispatcherPriority.Normal);
public void Invoke(Action action)
{
if (Avalonia.Threading.Dispatcher.UIThread.CheckAccess()) action();
else Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(action).GetAwaiter().GetResult();
}
}
public sealed class DispatcherTimer
{
private readonly Avalonia.Threading.DispatcherTimer _timer = new();
public TimeSpan Interval { get => _timer.Interval; set => _timer.Interval = value; }
public event EventHandler? Tick { add => _timer.Tick += value; remove => _timer.Tick -= value; }
public DispatcherTimer() { }
public DispatcherTimer(TimeSpan interval, DispatcherPriority priority, EventHandler tick, Dispatcher dispatcher)
{ Interval = interval; Tick += tick; Start(); }
public void Start() => _timer.Start();
public void Stop() => _timer.Stop();
}

View File

@ -0,0 +1,12 @@
using Avalonia;
namespace SopHelper;
internal static class Program
{
[STAThread]
public static int Main(string[] args)
{
if(args.Contains("--check-runtime"))return Diagnostics.RuntimeCheck.Run();
return AppBuilder.Configure<App>().UsePlatformDetect().LogToTrace().StartWithClassicDesktopLifetime(args);
}
}

View File

@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<RootNamespace>SopHelper</RootNamespace>
<AvaloniaUseCompiledBindingsByDefault>false</AvaloniaUseCompiledBindingsByDefault>
<!-- These two views are created by DI with constructor parameters, never by a runtime XAML URI. -->
<NoWarn>$(NoWarn);AVLN3001</NoWarn>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj" />
<PackageReference Include="Prism.DryIoc.Avalonia" Version="9.0.537.11130" />
<PackageReference Include="Avalonia.Desktop" Version="11.3.22" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.3.22" />
<AvaloniaResource Include="Assets/**" />
<Content Include="../../configs/**/*" Link="configs/%(RecursiveDir)%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
<Content Include="../../models/*.onnx" Link="models/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
<Content Include="../../yolo_models/*.onnx" Link="yolo_models/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
<Content Include="../../tools/worker.py" Link="tools/worker.py" CopyToOutputDirectory="PreserveNewest" />
<Content Include="../../tools/requirements.txt" Link="tools/requirements.txt" CopyToOutputDirectory="PreserveNewest" />
<Content Include="../../tools/linux/Setup-Python.sh" Link="tools/Setup-Python.sh" CopyToOutputDirectory="PreserveNewest" />
<Content Include="../../tools/Setup-Python.ps1" Link="tools/Setup-Python.ps1" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,101 @@
<Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:p="using:SopHelper.Presentation">
<Styles.Resources>
<p:SelectionConverter x:Key="SelectionConverter" />
<SolidColorBrush x:Key="Bg" Color="#FF101820" />
<SolidColorBrush x:Key="Panel" Color="#FF16222E" />
<SolidColorBrush x:Key="Line" Color="#FF2C4257" />
<SolidColorBrush x:Key="Fg" Color="#FFDCEBF5" />
<SolidColorBrush x:Key="FgDim" Color="#FF8FAFC4" />
<SolidColorBrush x:Key="Accent" Color="#FF00B8D4" />
<SolidColorBrush x:Key="Ok" Color="#FF37B26D" />
<SolidColorBrush x:Key="Ng" Color="#FFF0533C" />
</Styles.Resources>
<Style Selector="TextBlock">
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="FontFamily" Value="Microsoft YaHei, Noto Sans CJK SC, sans-serif" />
<Setter Property="FontSize" Value="13" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style Selector="TextBlock.Title">
<Setter Property="FontSize" Value="16" />
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Foreground" Value="{StaticResource Accent}" />
</Style>
<Style Selector="ListBoxItem:selected">
<Setter Property="Background" Value="#3300B8D4" />
</Style>
<Style Selector="ListBoxItem:pointerover">
<Setter Property="Background" Value="#22FFFFFF" />
</Style>
<Style Selector="Button:pointerover">
<Setter Property="BorderBrush" Value="{StaticResource Accent}" />
</Style>
<Style Selector="Border.panel">
<Setter Property="Background" Value="{StaticResource Panel}" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="6" />
<Setter Property="Padding" Value="10" />
</Style>
<Style Selector="Button">
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="Background" Value="{StaticResource Panel}" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Padding" Value="14,7" />
<Setter Property="FontFamily" Value="Microsoft YaHei, Noto Sans CJK SC, sans-serif" />
<Setter Property="FontSize" Value="13" />
<Setter Property="Cursor" Value="Hand" />
</Style>
<Style Selector="ComboBox">
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="Background" Value="{StaticResource Panel}" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Height" Value="28" />
</Style>
<Style Selector="ComboBoxItem">
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="Padding" Value="8,6" />
</Style>
<Style Selector="TextBox">
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="CaretBrush" Value="{StaticResource Accent}" />
<Setter Property="Background" Value="{StaticResource Panel}" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="MinHeight" Value="28" />
<Setter Property="Padding" Value="6,3" />
<Setter Property="FontFamily" Value="Microsoft YaHei, Noto Sans CJK SC, sans-serif" />
<Setter Property="FontSize" Value="13" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="SelectionBrush" Value="{StaticResource Accent}" />
</Style>
<Style Selector="CheckBox">
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="FontFamily" Value="Microsoft YaHei, Noto Sans CJK SC, sans-serif" />
<Setter Property="FontSize" Value="13" />
<Setter Property="VerticalContentAlignment" Value="Center" />
</Style>
<Style Selector="TabControl">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="BorderThickness" Value="1" />
</Style>
<Style Selector="TabItem">
<Setter Property="Foreground" Value="{StaticResource FgDim}" />
<Setter Property="FontFamily" Value="Microsoft YaHei, Noto Sans CJK SC, sans-serif" />
<Setter Property="FontSize" Value="13" />
<Setter Property="Padding" Value="14,7" />
</Style>
<Style Selector="TextBlock.Field">
<Setter Property="Width" Value="74" />
<Setter Property="Foreground" Value="{StaticResource FgDim}" />
</Style>
<Style Selector="ListBox">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Foreground" Value="{StaticResource Fg}" />
</Style>
</Styles>

View File

@ -0,0 +1,43 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using SopHelper.Presentation.Imaging;
namespace SopHelper.Training;
public sealed class AnnotationCanvas : Control
{
public static readonly StyledProperty<BitmapSource?> SourceProperty=AvaloniaProperty.Register<AnnotationCanvas,BitmapSource?>(nameof(Source));
public static readonly StyledProperty<double[]?> BoxProperty=AvaloniaProperty.Register<AnnotationCanvas,double[]?>(nameof(Box));
public BitmapSource? Source {get=>GetValue(SourceProperty);set=>SetValue(SourceProperty,value);}
public double[]? Box {get=>GetValue(BoxProperty);set=>SetValue(BoxProperty,value);}
public event Action<double[]>? BoxDrawn;
private Point? _start;private Point _end;private IPointer? _pointer;
static AnnotationCanvas(){AffectsRender<AnnotationCanvas>(SourceProperty,BoxProperty);}
public AnnotationCanvas(){ClipToBounds=true;Cursor=new Cursor(StandardCursorType.Cross);Focusable=true;}
private Rect ImageRect=>Source is null?default:VVMs.RecipeEditor.RegionCanvas.FitImage(Bounds.Size,new Size(Source.PixelWidth,Source.PixelHeight));
public override void Render(DrawingContext dc)
{
dc.DrawRectangle(Brushes.Transparent,null,new Rect(Bounds.Size));var image=ImageRect;if(Source is null||image.Width<=0)return;
dc.DrawImage(Source,image);var pen=new Pen(new SolidColorBrush(Color.FromRgb(0,220,220)),2);
if(Box is { Length:4 } b)
{var scale=image.Width/Source.PixelWidth;dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(30,0,220,220)),pen,new Rect(image.X+b[0]*scale,image.Y+b[1]*scale,(b[2]-b[0])*scale,(b[3]-b[1])*scale));}
if(_start is {} start)dc.DrawRectangle(null,new Pen(Brushes.Yellow,2),DragRect(start,_end));
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
if(!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed||!IsEnabled||Source is null||!ImageRect.Contains(e.GetPosition(this)))return;
Focus();_start=_end=e.GetPosition(this);_pointer=e.Pointer;_pointer.Capture(this);InvalidateVisual();e.Handled=true;
}
protected override void OnPointerMoved(PointerEventArgs e)
{if(_start is null)return;var p=e.GetPosition(this);var image=ImageRect;_end=new Point(Math.Clamp(p.X,image.Left,image.Right),Math.Clamp(p.Y,image.Top,image.Bottom));InvalidateVisual();}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
if(_start is not {} start||Source is null)return;
var rectangle=DragRect(start,_end);var image=ImageRect;_start=null;_pointer?.Capture(null);_pointer=null;InvalidateVisual();
if(rectangle.Width<3||rectangle.Height<3||image.Width<=0)return;
var scale=Source.PixelWidth/image.Width;BoxDrawn?.Invoke([(rectangle.Left-image.Left)*scale,(rectangle.Top-image.Top)*scale,Math.Min(Source.PixelWidth,(rectangle.Right-image.Left)*scale),Math.Min(Source.PixelHeight,(rectangle.Bottom-image.Top)*scale)]);
}
protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e){_start=null;_pointer=null;InvalidateVisual();base.OnPointerCaptureLost(e);}
private static Rect DragRect(Point a,Point b)=>new(Math.Min(a.X,b.X),Math.Min(a.Y,b.Y),Math.Abs(a.X-b.X),Math.Abs(a.Y-b.Y));
}

View File

@ -0,0 +1,286 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using Avalonia;
using SopHelper.Presentation;
using Avalonia.Media;
using SopHelper.Presentation.Imaging;
using SopHelper.Presentation.Threading;
using OpenCvSharp;
using SopHelper.Engine.Camera;
using Prism.Commands;
using Prism.Mvvm;
namespace SopHelper.Training;
public sealed class CameraViewModel : BindableBase
{
private readonly ICameraService _camera;
private readonly VideoRecorder _recorder = new();
private readonly object _frames = new();
private readonly Dispatcher _dispatcher;
private readonly DispatcherTimer _timer;
private readonly string _settingsPath;
private readonly Stopwatch _previewClock = Stopwatch.StartNew();
private Mat? _latest;
private int _previewPending;
private int _generation;
private long _lastFrameTick;
private volatile bool _closing;
private bool _busy, _previewing, _recording;
private string _status = "刷新设备列表,选择相机后开启预览";
private string _directory;
private string _lastRecording = "";
private string _recordingInfo = "未录像";
private CameraInfo? _selected;
private BitmapSource? _preview;
private Task _operation = Task.CompletedTask;
private Task? _shutdown;
private readonly List<DelegateCommand> _commands = [];
public ObservableCollection<CameraInfo> Cameras { get; } = [];
public CameraInfo? SelectedCamera { get => _selected; set { SetProperty(ref _selected, value); UpdateCommands(); } }
public BitmapSource? Preview { get => _preview; private set => SetProperty(ref _preview, value); }
public string Status { get => _status; private set => SetProperty(ref _status, value); }
public bool IsBusy { get => _busy; private set { SetProperty(ref _busy, value); StateChanged(); } }
public bool IsPreviewing { get => _previewing; private set { SetProperty(ref _previewing, value); StateChanged(); } }
public bool IsRecording { get => _recording; private set { SetProperty(ref _recording, value); StateChanged(); } }
public bool CanChooseCamera => !IsBusy && !IsPreviewing && !_closing;
public bool CanChangeDirectory => !IsBusy && !IsRecording && !_closing;
public string PreviewButtonText => IsPreviewing ? "关闭相机" : "开启相机预览";
public string RecordButtonText => IsRecording ? "停止录像" : "开始录像";
public string RecordingInfo { get => _recordingInfo; private set => SetProperty(ref _recordingInfo, value); }
public string SaveDirectory { get => _directory; set => SetProperty(ref _directory, value); }
public string LastRecording { get => _lastRecording; private set { SetProperty(ref _lastRecording, value); UpdateCommands(); } }
public double RecordingFps { get; set; } = 30;
public DelegateCommand RefreshCommand { get; }
public DelegateCommand PreviewCommand { get; }
public DelegateCommand RecordCommand { get; }
public DelegateCommand BrowseCommand { get; }
public DelegateCommand RevealCommand { get; }
public CameraViewModel(ICameraService camera, string root)
{
_camera = camera; _dispatcher = Dispatcher.CurrentDispatcher;
_directory = Path.Combine(root, "workspace", "recordings");
_settingsPath = Path.Combine(root, "workspace", "camera-settings.json");
try
{
if (File.Exists(_settingsPath))
{
using var json = JsonDocument.Parse(File.ReadAllText(_settingsPath));
SaveDirectory = json.RootElement.GetProperty("directory").GetString() ?? _directory;
}
}
catch (Exception e) { Status = "录像目录配置读取失败:" + e.Message; }
RefreshCommand = Command(RefreshAsync, () => CanChooseCamera);
PreviewCommand = Command(TogglePreviewAsync, () => !IsBusy && !_closing && (IsPreviewing || SelectedCamera != null));
RecordCommand = Command(ToggleRecordingAsync, () => !IsBusy && !_closing && (IsRecording || (IsPreviewing && Preview != null && HasRecentFrame)));
BrowseCommand = Command(async () =>
{
var picker = new OpenFolderDialog { Title = "选择录像保存目录" };
if (Directory.Exists(SaveDirectory)) picker.InitialDirectory = SaveDirectory;
if (await picker.ShowDialogAsync() == true) { SaveDirectory = picker.FolderName; SaveSettings(); }
}, () => CanChangeDirectory);
RevealCommand = Command(() =>
{
if (!string.IsNullOrEmpty(LastRecording) && File.Exists(LastRecording))
{
DesktopPlatform.Reveal(LastRecording);
}
else
{
Directory.CreateDirectory(SaveDirectory);
var info = new ProcessStartInfo("explorer.exe") { UseShellExecute = true };
info.ArgumentList.Add(Path.GetFullPath(SaveDirectory)); Process.Start(info);
}
return Task.CompletedTask;
}, () => !IsBusy && !_closing);
_camera.FrameArrived += OnFrame;
_camera.ConnectionChanged += OnConnection;
_camera.Error += OnError;
_timer = new DispatcherTimer(TimeSpan.FromMilliseconds(250), DispatcherPriority.Background, (_, _) => Tick(), _dispatcher);
_timer.Start();
}
private DelegateCommand Command(Func<Task> action, Func<bool> canExecute)
{
var command = new DelegateCommand(() => _operation = PerformAsync(action), canExecute);
_commands.Add(command); return command;
}
private async Task PerformAsync(Func<Task> action)
{
if (IsBusy || _closing) return;
IsBusy = true;
try { await action(); }
catch (Exception e) { Status = e.Message; }
finally { IsBusy = false; }
}
private void UpdateCommands() { foreach (var command in _commands) command.RaiseCanExecuteChanged(); }
private void StateChanged()
{
RaisePropertyChanged(nameof(CanChooseCamera)); RaisePropertyChanged(nameof(CanChangeDirectory));
RaisePropertyChanged(nameof(PreviewButtonText)); RaisePropertyChanged(nameof(RecordButtonText)); UpdateCommands();
}
private async Task RefreshAsync()
{
Status = "正在枚举 UVC / 海康相机…";
var devices = await _camera.EnumerateAsync();
if (_closing) return;
Cameras.Clear(); foreach (var device in devices) Cameras.Add(device);
SelectedCamera = Cameras.FirstOrDefault();
Status = Cameras.Count == 0 ? "未找到相机,请检查连接;海康设备需要 MVS x64 运行时" : $"找到 {Cameras.Count} 台相机";
}
private async Task TogglePreviewAsync()
{
if (IsPreviewing)
{
StopRecording();
await Task.Run(_camera.Disconnect);
ClearPreview(); IsPreviewing = false; Status = "相机已关闭";
return;
}
var selected = SelectedCamera ?? throw new InvalidOperationException("请选择相机");
Status = "正在连接 " + selected.Name;
if (!await _camera.ConnectAsync(selected)) throw new IOException("相机连接失败,请检查设备是否被其他程序占用");
if (_closing) return;
if (!await _camera.StartAsync())
{
await Task.Run(_camera.Disconnect);
throw new IOException("相机已连接,但采集启动失败");
}
IsPreviewing = true; Status = "相机预览中,可开始录像";
}
private Task ToggleRecordingAsync()
{
if (IsRecording) { StopRecording(); return Task.CompletedTask; }
if (string.IsNullOrWhiteSpace(SaveDirectory)) throw new ArgumentException("请选择录像保存目录");
var directory = Path.GetFullPath(SaveDirectory.Trim());
SaveDirectory = directory; SaveSettings();
lock (_frames)
{
if (_latest == null || !_camera.IsGrabbing) throw new InvalidOperationException("尚未收到相机画面,请先开启预览");
if (Stopwatch.GetElapsedTime(_lastFrameTick).TotalSeconds > 2) throw new IOException("超过2秒未收到相机画面,请重新连接后再录像");
LastRecording = _recorder.Start(directory, _latest, RecordingFps);
}
IsRecording = true; Status = "正在录像,点击“停止录像”保存文件"; Tick();
return Task.CompletedTask;
}
private void StopRecording()
{
RecordingResult? result;
lock (_frames) result = _recorder.Stop();
IsRecording = false;
if (result != null)
{
LastRecording = result.Path;
RecordingInfo = $"已保存 · {result.Duration.TotalSeconds:F1} 秒 · {result.Frames} 帧";
Status = "录像已保存,可在主窗口导入视频继续标注";
}
}
private void OnFrame(CameraFrame frame)
{
if (_closing) return;
BitmapSource? preview = null;
string? recordingError = null;
var generation = Volatile.Read(ref _generation);
lock (_frames)
{
if (_closing) return;
Interlocked.Exchange(ref _lastFrameTick, Stopwatch.GetTimestamp());
if (_latest == null) _latest = frame.Bgr.Clone(); else frame.Bgr.CopyTo(_latest);
try { _recorder.Write(frame.Bgr); }
catch (Exception e) { recordingError = "录像中断:" + e.Message + ";已写入内容保存在 " + _recorder.CurrentPath; }
if (_previewClock.ElapsedMilliseconds >= 66 && Interlocked.CompareExchange(ref _previewPending, 1, 0) == 0)
{
try
{
var stride = checked((int)frame.Bgr.Step());
preview = BitmapSource.Create(frame.Bgr.Width, frame.Bgr.Height, 96, 96, PixelFormats.Bgr24,
null, frame.Bgr.Data, checked(stride * frame.Bgr.Height), stride);
preview.Freeze(); _previewClock.Restart();
}
catch { Interlocked.Exchange(ref _previewPending, 0); throw; }
}
}
if (recordingError != null)
{
var error = recordingError;
Post(() => { IsRecording = false; Status = error; RecordingInfo = "录像中断,请检查日志提示"; });
}
if (preview != null)
{
var bitmap = preview;
Post(() =>
{
try
{
if (generation == Volatile.Read(ref _generation)) { Preview = bitmap; UpdateCommands(); }
}
finally { Interlocked.Exchange(ref _previewPending, 0); }
});
}
}
private void OnConnection(bool connected)
{
if (!connected) Post(() =>
{
if (_camera.IsConnected) return; // Ignore a queued disconnect from the previous connection.
StopRecording(); IsPreviewing = false; ClearPreview();
});
}
private void OnError(string message) => Post(() => Status = message);
private void Post(Action action)
{
if (!_closing && !_dispatcher.HasShutdownStarted)
_dispatcher.BeginInvoke(() => { if (!_closing) action(); }, DispatcherPriority.Background);
}
private void Tick()
{
if (_closing) return;
if (IsRecording)
{
if (Stopwatch.GetElapsedTime(Interlocked.Read(ref _lastFrameTick)).TotalSeconds > 2)
{
StopRecording(); Status = "超过2秒未收到相机画面,录像已结束,请检查相机连接";
}
else if (!_recorder.IsRecording) IsRecording = false;
else RecordingInfo = $"● 正在录像 {_recorder.Elapsed:hh\\:mm\\:ss} · {RecordingFps:F0} fps";
}
if (IsPreviewing && !_camera.IsGrabbing && !IsBusy)
{
StopRecording(); IsPreviewing = false; ClearPreview(); Status = "相机采集已中断,请重新连接";
}
}
private bool HasRecentFrame => Interlocked.Read(ref _lastFrameTick) != 0 &&
Stopwatch.GetElapsedTime(Interlocked.Read(ref _lastFrameTick)).TotalSeconds <= 2;
private void ClearPreview()
{
Interlocked.Increment(ref _generation);
lock (_frames) { _latest?.Dispose(); _latest = null; }
Preview = null;
}
private void SaveSettings()
{
Directory.CreateDirectory(Path.GetDirectoryName(_settingsPath)!);
File.WriteAllText(_settingsPath, JsonSerializer.Serialize(new { directory = SaveDirectory }));
}
public Task ShutdownAsync() => _shutdown ??= ShutdownCoreAsync();
private async Task ShutdownCoreAsync()
{
_closing = true; _timer.Stop(); StateChanged();
await _operation;
try { await Task.Run(_camera.Dispose); }
finally
{
try { StopRecording(); }
finally
{
ClearPreview();
_camera.FrameArrived -= OnFrame; _camera.ConnectionChanged -= OnConnection; _camera.Error -= OnError;
IsPreviewing = false;
}
}
}
}

View File

@ -0,0 +1,64 @@
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SopHelper.Training.CameraWindow" Title="SopHelper · 相机与录像" Width="1080" Height="800" MinWidth="840" MinHeight="650" WindowStartupLocation="CenterOwner" xmlns:conv="using:Avalonia.Data.Converters">
<Window.Styles>
<StyleInclude Source="avares://SopHelper.Avalonia/Training/Styles.axaml" />
<Style Selector="TextBlock.state1">
<Setter Property="Foreground" Value="#F0533C" />
</Style>
</Window.Styles>
<Window.Resources>
</Window.Resources>
<Grid Margin="18">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="相机与录像" FontSize="22" FontWeight="Bold" Foreground="{StaticResource Accent}" Margin="0,0,0,16" />
<Grid Grid.Row="1" Margin="0,0,0,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ComboBox ItemsSource="{Binding Cameras}" SelectedItem="{Binding SelectedCamera, Converter={StaticResource SelectionConverter}}" IsEnabled="{Binding CanChooseCamera}" Margin="0,0,10,6" MinHeight="36">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Button Grid.Column="1" Content="刷新相机" Command="{Binding RefreshCommand}" />
<Button Grid.Column="2" Content="{Binding PreviewButtonText}" Command="{Binding PreviewCommand}" />
</Grid>
<Border Grid.Row="2" Background="#080E14" BorderBrush="{StaticResource Line}" BorderThickness="1" CornerRadius="6" Classes="panel">
<Grid>
<TextBlock Text="开启相机后在此显示实时画面" HorizontalAlignment="Center" Foreground="{StaticResource Dim}" />
<Image Source="{Binding Preview}" Stretch="Uniform" />
<Border HorizontalAlignment="Left" VerticalAlignment="Top" Margin="12" Padding="10,5" Background="#CC101820" CornerRadius="4" Classes="panel">
<TextBlock Text="{Binding RecordingInfo}" Foreground="{StaticResource Dim}" Classes.state1="{Binding IsRecording}" />
</Border>
</Grid>
</Border>
<StackPanel Grid.Row="3" Margin="0,14,0,0">
<TextBlock Text="录像保存目录" />
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Text="{Binding SaveDirectory, Mode=TwoWay}" IsEnabled="{Binding CanChangeDirectory}" Margin="0,6,10,8" />
<Button Grid.Column="1" Content="选择目录…" Command="{Binding BrowseCommand}" Margin="0,6,6,8" />
<Button Grid.Column="2" Content="打开保存位置" Command="{Binding RevealCommand}" Margin="0,6,0,8" />
</Grid>
<DockPanel>
<Button DockPanel.Dock="Left" Content="{Binding RecordButtonText}" Command="{Binding RecordCommand}" BorderBrush="{StaticResource Accent}" MinWidth="130" />
<TextBlock Text="AVI / MJPEG · 30 fps · 原始画面,不含标注和界面" Foreground="{StaticResource Dim}" Margin="12,0,0,6" />
</DockPanel>
<TextBlock Text="{Binding LastRecording}" TextTrimming="CharacterEllipsis" Foreground="{StaticResource Dim}" Margin="0,0,0,8" ToolTip.Tip="{Binding LastRecording}" />
</StackPanel>
<TextBlock Grid.Row="4" Text="{Binding Status}" TextWrapping="Wrap" Margin="0,8,0,0" />
</Grid>
</Window>

View File

@ -0,0 +1,16 @@
using Avalonia.Controls;
using Avalonia.Threading;
namespace SopHelper.Training;
public partial class CameraWindow : Window
{
public CameraViewModel Model { get; }
private bool _closedSafely,_closeRequested;
public CameraWindow(CameraViewModel model){InitializeComponent();Model=model;DataContext=model;Closing+=OnSafeClosing;}
private async void OnSafeClosing(object? sender,WindowClosingEventArgs e)
{
if(_closedSafely)return;e.Cancel=true;if(_closeRequested)return;_closeRequested=true;IsEnabled=false;
try{await Model.ShutdownAsync();}catch(Exception error){System.Diagnostics.Trace.TraceError("关闭相机时出错:"+error);}
_closedSafely=true;Dispatcher.UIThread.Post(Close);
}
}

View File

@ -0,0 +1,367 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using Avalonia;
using SopHelper.Presentation.Threading;
using SopHelper.Presentation;
using SopHelper.Presentation.Imaging;
using SopHelper.Engine.Training;
using Prism.Commands;
using Prism.Mvvm;
namespace SopHelper.Training;
public sealed class MainViewModel : BindableBase
{
private readonly WorkerClient _worker;
private CancellationTokenSource? _cancellation;
private TaskCompletionSource? _completion;
private TrainingProject? _project;
private FrameAnnotation? _selected;
private BitmapImage? _preview;
private bool _busy;
private double _progress;
private string _status = "新建项目:导入视频,在任意清晰帧拖动画框";
private string _logs = "";
private bool _isTraining;
private string _trainingStatus = "打开已复核项目后即可开始训练";
private string _trainingMetrics = "尚无训练指标";
private string _latestWeights = "";
private string _trainingRunDirectory = "";
public bool IsTraining { get => _isTraining; private set => SetProperty(ref _isTraining, value); }
public string TrainingStatus { get => _trainingStatus; private set => SetProperty(ref _trainingStatus, value); }
public string TrainingMetrics { get => _trainingMetrics; private set => SetProperty(ref _trainingMetrics, value); }
public string LatestWeights { get => _latestWeights; private set => SetProperty(ref _latestWeights, value); }
public string TrainingRunDirectory { get => _trainingRunDirectory; private set => SetProperty(ref _trainingRunDirectory, value); }
public string TrainingOutputDirectory { get; set; } = "";
public string Root { get; }
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()); } }
public bool IsIdle => !IsBusy;
public double Progress { get => _progress; set => SetProperty(ref _progress, value); }
public string Status { get => _status; set => SetProperty(ref _status, value); }
public string Logs { get => _logs; set => SetProperty(ref _logs, value); }
public string Summary => _project == null ? "尚未导入视频" : $"{_project.Width} × {_project.Height} · {Frames.Count} 帧 · 已复核 {Frames.Count(f => f.Status is "reviewed" or "absent")} · 待复核 {Frames.Count(f => f.Status == "auto")}";
public string FrameInfo => _selected == null || _project == null ? "拖动画框以标记零件" : $"第 {_selected.Index + 1} 帧 · 原视频帧 {_selected.SourceIndex} · {(_project.Fps > 0 ? (_selected.SourceIndex / _project.Fps).ToString("F2") + " 秒" : "时间未知")} · {_selected.Display}";
public string ProjectPath => _project?.FilePath ?? "项目会自动保存到你选择的文件夹";
public BitmapImage? Preview { get => _preview; private set => SetProperty(ref _preview, value); }
public double[]? CurrentBox => _selected?.Box;
public FrameAnnotation? SelectedFrame
{
get => _selected;
set
{
if (!SetProperty(ref _selected, value)) return;
try
{
if (value != null && _project != null)
{
var bitmap = new BitmapImage();
bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.UriSource = new Uri(Path.Combine(_project.DirectoryPath, value.Image));
bitmap.EndInit(); bitmap.Freeze(); Preview = bitmap;
}
}
catch (Exception e) { Status = "图像读取失败:" + e.Message; Preview = null; }
RaisePropertyChanged(nameof(CurrentBox)); RaisePropertyChanged(nameof(FrameInfo));
}
}
// Configuration is saved locally, except the API key which is passed only through the worker environment.
private static string PythonPath => DesktopPlatform.PythonPath;
public string Label { get; set; } = "零件";
public int ExtractStride { get; set; } = 1;
public int MaxFrames { get; set; } = 600;
public string Checkpoint { get; set; } = "";
public string SamConfig { get; set; } = "configs/sam2.1/sam2.1_hiera_t.yaml";
public string Device { get; set; } = "auto";
public int ExportEvery { get; set; } = 5;
public int Epochs { get; set; } = 50;
public int Batch { get; set; } = 4;
public int ImageSize { get; set; } = 640;
public string Model { get; set; } = "yolo11n.pt";
public string Endpoint { get; set; } = "https://api.example.com/v1";
public string ApiModel { get; set; } = "";
public string Description { get; set; } = "";
public Func<string>? ReadApiKey { get; set; }
public DelegateCommand ImportCommand { get; }
public DelegateCommand OpenCommand { get; }
public DelegateCommand DoctorCommand { get; }
public DelegateCommand PropagateCommand { get; }
public DelegateCommand ExportCommand { get; }
public DelegateCommand TrainCommand { get; }
public DelegateCommand PickTrainingModelCommand { get; }
public DelegateCommand PickTrainingOutputCommand { get; }
public DelegateCommand OpenTrainingResultsCommand { get; }
public DelegateCommand OnnxCommand { get; }
public DelegateCommand SuggestCommand { get; }
public DelegateCommand ApproveCommand { get; }
public DelegateCommand ApproveAllCommand { get; }
public DelegateCommand AbsentCommand { get; }
public DelegateCommand ExcludeCommand { get; }
public DelegateCommand PreviousCommand { get; }
public DelegateCommand NextCommand { get; }
public DelegateCommand CancelCommand { get; }
public DelegateCommand RevealCommand { get; }
private List<DelegateCommand> Commands { get; } = [];
public MainViewModel(WorkerClient worker)
{
_worker = worker;
var directory = new DirectoryInfo(AppContext.BaseDirectory);
while (directory.Parent != null && !File.Exists(Path.Combine(directory.FullName, "SopHelper.slnx"))) directory = directory.Parent;
Root = File.Exists(Path.Combine(directory.FullName, "SopHelper.slnx")) ? directory.FullName : AppContext.BaseDirectory;
LoadSettings();
ImportCommand = Command(Import);
OpenCommand = Command(async () =>
{
var dialog = new OpenFileDialog { Filter = "标注项目|project.json" };
if (await dialog.ShowDialogAsync() == true) Load(dialog.FileName);
});
DoctorCommand = Command(async () => await Run(new { action = "doctor" }, reload: false));
PropagateCommand = Command(async () => { SaveLabel(); await Run(new { action = "propagate", project = RequireProject().FilePath, checkpoint = Checkpoint, config = SamConfig, device = Device }); });
ExportCommand = Command(async () => { SaveLabel(); await Run(Request("export")); });
TrainCommand = Command(async () => { SaveLabel(); await Run(Request("train")); });
PickTrainingModelCommand = Command(async () =>
{
var dialog = new OpenFileDialog { Filter = "YOLO模型|*.pt;*.yaml;*.yml" };
if (await dialog.ShowDialogAsync() == true) { Model = dialog.FileName; RaisePropertyChanged(nameof(Model)); }
});
PickTrainingOutputCommand = Command(async () =>
{
var dialog = new OpenFolderDialog { Title = "选择训练结果保存目录" };
if (await dialog.ShowDialogAsync() == true) { TrainingOutputDirectory = dialog.FolderName; RaisePropertyChanged(nameof(TrainingOutputDirectory)); }
});
OpenTrainingResultsCommand = Command(() =>
{
var directory = TrainingRunDirectory;
if (!Directory.Exists(directory)) throw new DirectoryNotFoundException("尚无训练结果目录,请先完成一次训练");
DesktopPlatform.Reveal(directory);
});
OnnxCommand = Command(async () => await Run(Request("onnx")));
SuggestCommand = Command(async () =>
{
SaveLabel();
if (SelectedFrame == null) throw new InvalidOperationException("请先选择帧");
await Run(new { action = "suggest", project = RequireProject().FilePath, index = SelectedFrame.Index,
endpoint = Endpoint, apiModel = ApiModel, description = Description }, apiKey: ReadApiKey?.Invoke());
});
ApproveCommand = Command(() => Update("reviewed"));
ApproveAllCommand = Command(ApproveAll);
AbsentCommand = Command(() => Update("absent"));
ExcludeCommand = Command(() => Update("excluded"));
PreviousCommand = Command(() => Move(-1));
NextCommand = Command(() => Move(1));
CancelCommand = new DelegateCommand(() => _cancellation?.Cancel());
RevealCommand = Command(() => DesktopPlatform.Reveal(_project?.DirectoryPath ?? Root));
}
private DelegateCommand Command(Action action)
{
var command = new DelegateCommand(() => { try { action(); } catch (Exception e) { Status = e.Message; Append(e.Message); } }, () => !IsBusy);
Commands.Add(command); return command;
}
private DelegateCommand Command(Func<Task> action)
{
var command = new DelegateCommand(async () =>
{
try { await action(); }
catch (Exception e) { Status = e.Message; Append(e.Message); }
}, () => !IsBusy);
Commands.Add(command); return command;
}
// Async operations catch their own exceptions inside Run. Import does synchronous validation before awaiting.
private object Request(string action) => new { action, project = RequireProject().FilePath, every = ExportEvery,
valRatio = 0.2, epochs = Epochs, imageSize = ImageSize, batch = Batch, model = Model, device = Device,
outputDirectory = TrainingOutputDirectory };
private TrainingProject RequireProject() => _project ?? throw new InvalidOperationException("请先导入视频或打开项目");
private void SaveLabel()
{
var project = RequireProject();
if (string.IsNullOrWhiteSpace(Label)) throw new ArgumentException("请填写零件类别名称");
project.Name = Label.Trim(); project.Save();
}
private async void Import()
{
try
{
var video = new OpenFileDialog { Filter = "视频|*.mp4;*.avi;*.mov;*.mkv;*.wmv|所有文件|*.*" };
if (await video.ShowDialogAsync() != true) return;
var folder = new OpenFolderDialog { Title = "选择项目保存的父文件夹(会自动新建子文件夹)" };
if (await folder.ShowDialogAsync() != true) return;
if (string.IsNullOrWhiteSpace(Label)) throw new ArgumentException("请填写零件类别名称");
var output = Path.Combine(folder.FolderName, "part-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + "-" + Guid.NewGuid().ToString("N")[..4]);
if (await Run(new { action = "extract", video = video.FileName, output, name = Label.Trim(), stride = ExtractStride, maxFrames = MaxFrames }, reload: false))
Load(Path.Combine(output, "project.json"));
}
catch (Exception e) { Status = e.Message; Append(e.Message); }
}
public void Load(string path, int index = 0)
{
_project = TrainingProject.Load(path);
Label = _project.Name; RaisePropertyChanged(nameof(Label));
_selected = null; Frames.Clear();
foreach (var frame in _project.Frames) Frames.Add(frame);
SelectedFrame = Frames[Math.Clamp(index, 0, Frames.Count - 1)];
RaisePropertyChanged(nameof(Summary)); RaisePropertyChanged(nameof(ProjectPath));
LoadTrainingResult();
if (!IsBusy) Status = "项目已打开;拖动画框或选择帧进行复核";
}
public void DrawBox(double[] box)
{
if (IsBusy || SelectedFrame == null || _project == null) return;
try
{
_project.ValidateBox(box); SelectedFrame.Box = box; SelectedFrame.Prompt = true;
SelectedFrame.Status = "reviewed"; _project.Save(); Refresh();
Status = "关键帧已保存;可再选其他角度画框,或开始 SAM2 传播";
}
catch (Exception e) { Status = e.Message; }
}
private void Update(string status)
{
if (SelectedFrame == null) return;
if (status == "reviewed" && SelectedFrame.Box == null) throw new InvalidOperationException("该帧没有目标框,请画框或标记无目标");
SelectedFrame.Status = status;
if (status != "reviewed") { SelectedFrame.Box = null; SelectedFrame.Prompt = false; }
RequireProject().Save(); Refresh();
Status = "当前帧已保存";
}
private void ApproveAll()
{
var project = RequireProject();
var pending = project.Frames.Where(frame => frame.Status == "auto" && frame.Box != null).ToList();
// Validate the whole batch before changing any annotation status.
foreach (var frame in pending) project.ValidateBox(frame.Box!);
if (pending.Count == 0) { Status = "没有带目标框的待复核帧"; return; }
var selectedIndex = SelectedFrame?.Index ?? 0;
foreach (var frame in pending) frame.Status = "reviewed";
try { project.Save(); }
catch
{
foreach (var frame in pending) frame.Status = "auto";
throw;
}
Load(project.FilePath, selectedIndex);
Status = $"一键复核完成:已确认 {pending.Count} 帧并保存";
}
private void Refresh()
{
var frame = SelectedFrame;
if (frame == null) return;
var index = Frames.IndexOf(frame); Frames[index] = frame;
SelectedFrame = frame;
RaisePropertyChanged(nameof(CurrentBox)); RaisePropertyChanged(nameof(FrameInfo)); RaisePropertyChanged(nameof(Summary));
}
private void Move(int delta)
{
if (Frames.Count > 0) SelectedFrame = Frames[Math.Clamp(Frames.IndexOf(SelectedFrame!) + delta, 0, Frames.Count - 1)];
}
private void Append(string line)
{
Dispatcher.CurrentDispatcher.Invoke(() =>
{
Logs += line + Environment.NewLine;
if (Logs.Length > 40000) Logs = Logs[^30000..];
});
}
private async Task<bool> Run(object request, bool reload = true, string? apiKey = null)
{
if (IsBusy) return false;
IsTraining = JsonSerializer.SerializeToElement(request).GetProperty("action").GetString() == "train";
if (IsTraining) { TrainingStatus = "正在准备数据与模型…"; TrainingMetrics = "等待首轮训练指标"; }
IsBusy = true; Progress = 0; Status = "任务运行中…";
_cancellation = new CancellationTokenSource();
_completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var path = _project?.FilePath; var index = SelectedFrame?.Index ?? 0;
try
{
SaveSettings();
if (!File.Exists(PythonPath))
throw new FileNotFoundException("缺少内置 Python 环境,请运行 tools/Setup-Python.ps1 -Sam2 后重新构建程序。", PythonPath);
await _worker.RunAsync(PythonPath, Path.Combine(Root, "tools", "worker.py"), request, line =>
{
try
{
using var json = JsonDocument.Parse(line);
var item = json.RootElement;
var message = item.TryGetProperty("message", out var m) ? m.GetString() ?? line : line;
Append(message);
Dispatcher.CurrentDispatcher.Invoke(() =>
{
Status = message;
if (item.TryGetProperty("progress", out var progress) && (!IsTraining || item.TryGetProperty("event", out _))) Progress = Math.Clamp(progress.GetDouble(), 0, 1) * 100;
if (IsTraining)
{
TrainingStatus = message;
if (item.TryGetProperty("metrics", out var metrics)) TrainingMetrics = FormatMetrics(metrics);
if (item.TryGetProperty("runDirectory", out var directory)) TrainingRunDirectory = directory.GetString() ?? "";
if (item.TryGetProperty("weights", out var weights)) LatestWeights = weights.GetString() ?? "";
}
});
if (item.TryGetProperty("modules", out var modules)) Append(modules.ToString());
if (item.TryGetProperty("output", out var output)) Append(output.GetString() ?? "");
}
catch (Exception e) when (e is JsonException or InvalidOperationException or FormatException) { Append(line); }
}, _cancellation.Token, apiKey);
Progress = 100; return true;
}
catch (OperationCanceledException) { Status = "任务已取消;已保存的标注保留"; if (IsTraining) TrainingStatus = "训练已停止;已写入的日志与检查点保留在结果目录"; Append(Status); return false; }
catch (Exception e) { Status = e.Message; if (IsTraining) TrainingStatus = "训练失败,请查看运行日志:" + e.Message; Append(e.Message); return false; }
finally
{
if (reload && path != null)
{
try { Load(path, index); } catch (Exception e) { Append("重新读取项目失败:" + e.Message); }
}
_cancellation.Dispose(); _cancellation = null; IsBusy = false; IsTraining = false;
_completion.TrySetResult();
}
}
public void Cancel() => _cancellation?.Cancel();
public async Task StopAsync()
{
Cancel();
if (_completion != null) await _completion.Task;
}
private static string FormatMetrics(JsonElement metrics) => string.Join(Environment.NewLine,
metrics.EnumerateObject().Where(m => m.Value.ValueKind == JsonValueKind.Number)
.Select(m => $"{m.Name}: {m.Value.GetDouble():F4}"));
private void LoadTrainingResult()
{
if (IsTraining) return;
LatestWeights = ""; TrainingRunDirectory = ""; TrainingMetrics = "尚无训练指标";
var file = Path.Combine(RequireProject().DirectoryPath, "latest-model.json");
if (!File.Exists(file)) return;
try
{
using var result = JsonDocument.Parse(File.ReadAllText(file));
LatestWeights = result.RootElement.GetProperty("weights").GetString() ?? "";
TrainingRunDirectory = result.RootElement.TryGetProperty("runDirectory", out var directory) ? directory.GetString() ?? "" : Path.GetDirectoryName(Path.GetDirectoryName(LatestWeights)) ?? "";
if (result.RootElement.TryGetProperty("metrics", out var metrics)) TrainingMetrics = FormatMetrics(metrics);
}
catch (Exception e) { Append("读取训练结果失败:" + e.Message); }
}
private void SaveSettings()
{
Directory.CreateDirectory(Path.Combine(Root, "workspace"));
File.WriteAllText(Path.Combine(Root, "workspace", "settings.json"), JsonSerializer.Serialize(new
{ Checkpoint, SamConfig, Device, ExportEvery, Epochs, Batch, ImageSize, Model, TrainingOutputDirectory, Endpoint, ApiModel, Description, ExtractStride, MaxFrames }));
}
private void LoadSettings()
{
var path = Path.Combine(Root, "workspace", "settings.json");
if (!File.Exists(path)) return;
try
{
using var settings = JsonDocument.Parse(File.ReadAllText(path));
foreach (var item in settings.RootElement.EnumerateObject())
{
var property = GetType().GetProperty(item.Name);
if (property?.CanWrite == true && property.PropertyType == typeof(string)) property.SetValue(this, item.Value.GetString());
else if (property?.CanWrite == true && property.PropertyType == typeof(int)) property.SetValue(this, item.Value.GetInt32());
}
}
catch (Exception) { Status = "设置文件不可读,已使用默认配置"; }
}
}

View File

@ -0,0 +1,73 @@
<Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Styles.Resources>
<SolidColorBrush x:Key="Bg" Color="#101820" />
<SolidColorBrush x:Key="Panel" Color="#16222E" />
<SolidColorBrush x:Key="Line" Color="#2C4257" />
<SolidColorBrush x:Key="Fg" Color="#DCEBF5" />
<SolidColorBrush x:Key="Dim" Color="#8FAFC4" />
<SolidColorBrush x:Key="Accent" Color="#00B8D4" />
</Styles.Resources>
<Style Selector="Window">
<Setter Property="FontFamily" Value="Microsoft YaHei, Noto Sans CJK SC, sans-serif" />
<Setter Property="Background" Value="{StaticResource Bg}" />
<Setter Property="Foreground" Value="{StaticResource Fg}" />
</Style>
<Style Selector="TextBlock">
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="FontSize" Value="13" />
</Style>
<Style Selector="TextBlock.Hint">
<Setter Property="Foreground" Value="{StaticResource Dim}" />
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="Margin" Value="0,6,0,12" />
<Setter Property="LineHeight" Value="21" />
</Style>
<Style Selector="Button">
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="Background" Value="{StaticResource Panel}" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="Padding" Value="12,8" />
<Setter Property="Margin" Value="0,0,6,6" />
<Setter Property="Cursor" Value="Hand" />
</Style>
<Style Selector="TextBox">
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="Background" Value="#101820" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="Padding" Value="7" />
<Setter Property="Margin" Value="0,4,0,10" />
<Setter Property="CaretBrush" Value="{StaticResource Accent}" />
</Style>
<Style Selector="TextBox.password">
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="Background" Value="#101820" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="Padding" Value="7" />
<Setter Property="Margin" Value="0,4,0,10" />
</Style>
<Style Selector="TabControl">
<Setter Property="Background" Value="{StaticResource Panel}" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="Padding" Value="12" />
</Style>
<Style Selector="TabItem">
<Setter Property="Foreground" Value="{StaticResource Dim}" />
</Style>
<Style Selector="ListBox">
<Setter Property="Background" Value="#101820" />
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
</Style>
<Style Selector="ListBoxItem">
<Setter Property="Padding" Value="10,8" />
</Style>
<Style Selector="ComboBox">
<Setter Property="Foreground" Value="{StaticResource Fg}" />
</Style>
<Style Selector="ComboBoxItem">
<Setter Property="Foreground" Value="{StaticResource Fg}" />
<Setter Property="Padding" Value="10,8" />
</Style>
</Styles>

View File

@ -0,0 +1,155 @@
<UserControl xmlns="https://github.com/avaloniaui" xmlns:local="clr-namespace:SopHelper.Training" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SopHelper.Training.TrainingPage" xmlns:conv="using:Avalonia.Data.Converters">
<UserControl.Styles>
<StyleInclude Source="avares://SopHelper.Avalonia/Training/Styles.axaml" />
</UserControl.Styles>
<UserControl.Resources>
</UserControl.Resources>
<ScrollViewer Margin="12" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
<Grid Height="{Binding Viewport.Height, RelativeSource={RelativeSource AncestorType=ScrollViewer}}" MinWidth="1080" MinHeight="720">
<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="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>
<DockPanel>
<StackPanel DockPanel.Dock="Top" Margin="0,0,0,10">
<TextBlock Text="视频帧" FontSize="16" FontWeight="Bold" />
<TextBlock Text="{Binding Summary}" Classes="Hint" />
</StackPanel>
<ListBox ItemsSource="{Binding Frames}" SelectedItem="{Binding SelectedFrame}" IsEnabled="{Binding IsIdle}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Display}" FontSize="12" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel>
<Grid Grid.Column="2">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding FrameInfo}" Margin="0,0,0,10" TextWrapping="Wrap" />
<Border Grid.Row="1" Background="#080E14" BorderBrush="{StaticResource Line}" BorderThickness="1" CornerRadius="6" ClipToBounds="True" Classes="panel">
<local:AnnotationCanvas x:Name="Canvas" Source="{Binding Preview}" Box="{Binding CurrentBox}" IsEnabled="{Binding IsIdle}" />
</Border>
<WrapPanel Grid.Row="2" Margin="0,12,0,0">
<Button Content="← 上一帧" Command="{Binding PreviousCommand}" />
<Button Content="下一帧 →" Command="{Binding NextCommand}" />
<Button Content="确认当前框" Command="{Binding ApproveCommand}" />
<Button Content="一键复核" Command="{Binding ApproveAllCommand}" ToolTip.Tip="确认本项目中所有带目标框的待复核帧,并立即保存" />
<Button Content="无目标" Command="{Binding AbsentCommand}" />
<Button Content="排除此帧" Command="{Binding ExcludeCommand}" />
</WrapPanel>
<TextBlock Grid.Row="3" Text="拖动画框或修正,自动保存为关键帧。← → 切帧,Enter 确认当前框并进入下一帧。" Classes="Hint" />
</Grid>
<TabControl Grid.Column="4" IsEnabled="{Binding IsIdle}">
<TabItem Header="标注">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel>
<TextBlock Text="01 导入旋转视频" FontWeight="Bold" Foreground="{StaticResource Accent}" />
<TextBlock Text="零件类别名称" Margin="0,12,0,0" />
<TextBox Text="{Binding Label, Mode=TwoWay}" />
<TextBlock Text="抽帧间隔(原视频帧数)" />
<TextBox Text="{Binding ExtractStride, Mode=TwoWay}" />
<TextBlock Text="最多导入帧数" />
<TextBox Text="{Binding MaxFrames, Mode=TwoWay}" />
<TextBlock Text="默认最多600帧;长视频会自动增大间隔覆盖全片。快速旋转建议分成短片导入。" Classes="Hint" />
<TextBlock Text="02 画框并自动传播" FontWeight="Bold" Foreground="{StaticResource Accent}" Margin="0,10,0,8" />
<Button Content="开始 SAM2 传播" Command="{Binding PropagateCommand}" BorderBrush="{StaticResource Accent}" />
<TextBlock Text="先在清晰帧画一个框。旋转幅度大时,可在多个角度补框后再运行。传播保留已复核帧。" Classes="Hint" />
<TextBlock Text="03 人工复核" FontWeight="Bold" Foreground="{StaticResource Accent}" />
<TextBlock Text="逐帧确认目标框;框偏了直接重画。无目标用于负样本,排除帧不参与训练。只导出已复核数据。" Classes="Hint" />
</StackPanel>
</ScrollViewer>
</TabItem>
<TabItem Header="训练">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel>
<TextBlock Text="YOLO 目标检测训练" FontSize="16" FontWeight="Bold" />
<TextBlock Text="按时间分段:前段训练、末尾20%验证,边界留出间隔。正式评估请另拍独立测试视频。" Classes="Hint" />
<TextBlock Text="训练抽样间隔(导入后的帧数)" />
<TextBox Text="{Binding ExportEvery, Mode=TwoWay}" />
<TextBlock Text="YOLO 初始模型 / 本地 .pt 路径" />
<TextBox Text="{Binding Model, Mode=TwoWay}" />
<TextBlock Text="训练轮数" />
<TextBox Text="{Binding Epochs, Mode=TwoWay}" />
<TextBlock Text="图像尺寸(32的倍数)" />
<TextBox Text="{Binding ImageSize, Mode=TwoWay}" />
<TextBlock Text="批次大小" />
<TextBox Text="{Binding Batch, Mode=TwoWay}" />
<Button Content="导出 YOLO 数据集" Command="{Binding ExportCommand}" />
<Button Content="开始训练" Command="{Binding TrainCommand}" BorderBrush="{StaticResource Accent}" />
<Button Content="导出最新模型为 ONNX" Command="{Binding OnnxCommand}" />
<TextBlock Text="每次训练重新导出当前复核数据。best.pt、ONNX 和训练指标保存在项目 runs 文件夹。默认 yolo11n,检测框格式便于接入 SopHelper,仍需现场验证。" Classes="Hint" />
</StackPanel>
</ScrollViewer>
</TabItem>
<TabItem Header="设置">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel>
<Button Content="检查环境与 CUDA" Command="{Binding DoctorCommand}" />
<TextBlock Text="设备:auto / cpu / cuda(训练可填0)" />
<TextBox Text="{Binding Device, Mode=TwoWay}" />
<TextBlock Text="SAM2 checkpoint(留空自动下载 tiny)" />
<TextBox Text="{Binding Checkpoint, Mode=TwoWay}" />
<TextBlock Text="SAM2 配置(仅本地 checkpoint 使用)" />
<TextBox Text="{Binding SamConfig, Mode=TwoWay}" />
<TextBlock Text="可选:视觉大模型建议框" FontWeight="Bold" Margin="0,12,0,0" />
<TextBlock Text="兼容 chat/completions 的视觉接口。点击时会上传当前帧到下方地址;结果需人工确认,再用于 SAM2 传播。" Classes="Hint" />
<TextBlock Text="API Base URL(包含 /v1,不含 /chat/completions)" />
<TextBox Text="{Binding Endpoint, Mode=TwoWay}" />
<TextBlock Text="视觉模型名称" />
<TextBox Text="{Binding ApiModel, Mode=TwoWay}" />
<TextBlock Text="API Key(仅本次运行,不写入项目)" />
<TextBox x:Name="ApiKey" PasswordChar="●" />
<TextBlock Text="零件外观描述" />
<TextBox Text="{Binding Description, Mode=TwoWay}" AcceptsReturn="True" Height="64" TextWrapping="Wrap" />
<Button Content="让视觉模型建议当前帧目标框" Command="{Binding SuggestCommand}" />
</StackPanel>
</ScrollViewer>
</TabItem>
</TabControl>
</Grid>
<Grid Grid.Row="2" Margin="0,12,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<DockPanel>
<TextBlock Text="运行日志" Foreground="{StaticResource Dim}" />
<TextBlock Text="{Binding ProjectPath}" TextTrimming="CharacterEllipsis" HorizontalAlignment="Right" MaxWidth="850" Foreground="{StaticResource Dim}" />
</DockPanel>
<TextBox x:Name="LogBox" Grid.Row="1" Text="{Binding Logs, Mode=OneWay}" IsReadOnly="True" TextWrapping="Wrap" ScrollViewer.VerticalScrollBarVisibility="Auto" FontFamily="Consolas, Microsoft YaHei" TextChanged="LogChanged" Margin="0,6,0,0" />
</Grid>
<DockPanel Grid.Row="3" Margin="0,10,0,0">
<ProgressBar DockPanel.Dock="Right" Width="180" Height="5" Value="{Binding Progress}" Foreground="{StaticResource Accent}" Background="{StaticResource Line}" />
<TextBlock Text="{Binding Status}" TextTrimming="CharacterEllipsis" Margin="0,0,15,0" />
</DockPanel>
</Grid>
</ScrollViewer>
</UserControl>

View File

@ -0,0 +1,57 @@
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Threading;
using SopHelper.Core.Prism;
using SopHelper.Engine.Camera;
using SopHelper.VVMs.SopPage;
namespace SopHelper.Training;
[NavigationPage(ViewName=nameof(TrainingPage),DisplayName="零件标注与训练",Index=1)]
public partial class TrainingPage : UserControl
{
private readonly MainViewModel _model;
private readonly SopPageViewModel? _sop;
private CameraWindow? _cameraWindow;
private Window? _host;
private bool _closing,_closedSafely;
public TrainingPage(MainViewModel model,SopPageViewModel? sop)
{
InitializeComponent();_model=model;_sop=sop;DataContext=model;
Canvas.BoxDrawn+=model.DrawBox;
model.ReadApiKey=()=>ApiKey.Text??"";
AttachedToVisualTree+=(_,_)=>
{
if(_host!=null || TopLevel.GetTopLevel(this) is not Window host)return;
_host=host;host.Closing+=HostClosing;
};
AddHandler(KeyDownEvent,(_,e)=>
{
if(model.IsBusy || TopLevel.GetTopLevel(this)?.FocusManager?.GetFocusedElement() is TextBox)return;
if(e.Key==Key.Left){model.PreviousCommand.Execute();e.Handled=true;}
else if(e.Key==Key.Right){model.NextCommand.Execute();e.Handled=true;}
else if(e.Key==Key.Enter && model.SelectedFrame?.Box!=null)
{model.ApproveCommand.Execute();model.NextCommand.Execute();e.Handled=true;}
},RoutingStrategies.Tunnel);
}
private async void OpenCameraClicked(object? sender,RoutedEventArgs e)
{
if(_sop is { CanSelectCamera:false } || _sop is { IsConnected:true })
{_model.Status="请先停止 SOP 采集并等待相机操作完成,再打开录像";return;}
if(TopLevel.GetTopLevel(this) is not Window owner)return;
_cameraWindow=new CameraWindow(new CameraViewModel(new CameraService(),_model.Root));
try { await _cameraWindow.ShowDialog(owner); }
finally { _cameraWindow=null; }
}
public async Task ShutdownAsync()
{await _model.StopAsync();if(_cameraWindow!=null)await _cameraWindow.Model.ShutdownAsync();}
private async void HostClosing(object? sender,WindowClosingEventArgs e)
{
if(_closedSafely)return;e.Cancel=true;if(_closing)return;_closing=true;_host!.IsEnabled=false;
try{await ShutdownAsync();}catch(Exception error){_model.Status="关闭训练任务时出错:"+error.Message;}
_closedSafely=true;Dispatcher.UIThread.Post(()=>_host.Close());
}
private void LogChanged(object? sender,TextChangedEventArgs e)
{if(sender is TextBox box)box.CaretIndex=box.Text?.Length??0;}
}

View File

@ -0,0 +1,37 @@
<Window xmlns="https://github.com/avaloniaui" xmlns:prism="http://prismlibrary.com/" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SopHelper.VVMs.MainWindow.MainWindow" prism:ViewModelLocator.AutoWireViewModel="True" Title="{Binding Title}" Height="720" Width="1180" MinHeight="560" MinWidth="900" WindowState="Maximized" Background="{StaticResource Bg}" WindowStartupLocation="CenterScreen" xmlns:conv="using:Avalonia.Data.Converters">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceInclude Source="avares://SopHelper.Avalonia/Assets/BellwetherLogo.axaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="180" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Border Grid.ColumnSpan="2" HorizontalAlignment="Left" Width="202" Height="72" Margin="2,2,2,10" Background="Transparent" BorderThickness="0" CornerRadius="4" Padding="6" Classes="panel">
<Image Source="{StaticResource BellwetherLogo}" Stretch="Uniform" AutomationProperties.Name="贝沃思 BELLWETHER" />
</Border>
<Border Grid.Row="1" Margin="0,0,10,0" Classes="panel">
<ListBox ItemsSource="{Binding Navigation.Pages}" SelectedIndex="{Binding Navigation.SelectedIndex, Mode=TwoWay}">
<ListBox.Styles>
<Style Selector="ListBoxItem">
<Setter Property="Padding" Value="12,10" />
</Style>
</ListBox.Styles>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding DisplayName}" FontSize="14" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Border>
<ContentControl Grid.Row="1" Grid.Column="1" prism:RegionManager.RegionName="ContentRegion" />
</Grid>
</Window>

View File

@ -0,0 +1,4 @@
using Avalonia.Controls;
namespace SopHelper.VVMs.MainWindow;
public partial class MainWindow : Window
{ public MainWindow() { InitializeComponent(); } }

View File

@ -0,0 +1,39 @@
using Prism.Commands;
using Prism.Mvvm;
using SopHelper.Models;
namespace SopHelper.VVMs.MainWindow;
/// <summary>
/// Main窗口视图模型
/// </summary>
public class MainWindowViewModel : BindableBase
{
private readonly NavigationModel _navigation;
/// <summary>
/// Main窗口视图模型
/// </summary>
public MainWindowViewModel(NavigationModel navigation)
{
_navigation = navigation;
}
private string _title = "SopHelper";
/// <summary>
/// 标题
/// </summary>
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
/// <summary>
/// 导航模型(侧栏绑定)
/// </summary>
public NavigationModel Navigation => _navigation;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,15 @@
using Avalonia.Controls;
using Prism.Dialogs;
namespace SopHelper.VVMs.RecipeEditor;
public sealed class RecipeDialogWindow : Window,IDialogWindow
{
public IDialogResult Result {get;set;}=new DialogResult();
public RecipeDialogWindow()
{
Width=1040;Height=760;MinWidth=1040;MinHeight=760;
WindowStartupLocation=WindowStartupLocation.CenterOwner;
HorizontalContentAlignment=Avalonia.Layout.HorizontalAlignment.Stretch;
VerticalContentAlignment=Avalonia.Layout.VerticalAlignment.Stretch;
}
}

View File

@ -0,0 +1,440 @@
<UserControl xmlns="https://github.com/avaloniaui" xmlns:ed="clr-namespace:SopHelper.VVMs.RecipeEditor" xmlns:prism="http://prismlibrary.com/" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SopHelper.VVMs.RecipeEditor.RecipeEditor" prism:ViewModelLocator.AutoWireViewModel="True" Background="{StaticResource Bg}" xmlns:conv="using:Avalonia.Data.Converters">
<UserControl.DataTemplates>
<DataTemplate DataType="{x:Type ed:TextItem}">
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" />
<Button Grid.Column="1" Margin="6,0,0,0" Classes="Mini" Content="删" Command="{Binding RemoveCommand}" CommandParameter="{Binding}" />
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type ed:ViolationRuleNode}">
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="130" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="56" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ComboBox ItemsSource="{Binding DataContext.Recipe.ViolationTypes, RelativeSource={RelativeSource AncestorType=UserControl}}" SelectedItem="{Binding Type, Converter={StaticResource SelectionConverter}}" />
<TextBox Grid.Column="1" Margin="6,0,0,0" Text="{Binding Description, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Grid.Column="2" Margin="6,0,0,0" Text="{Binding Severity}" />
<Button Grid.Column="3" Margin="6,0,0,0" Classes="Mini" Content="删" Command="{Binding RemoveCommand}" CommandParameter="{Binding}" />
</Grid>
</DataTemplate>
</UserControl.DataTemplates>
<UserControl.Styles>
<Style Selector="Grid.Row">
<Setter Property="Margin" Value="0,0,0,6" />
</Style>
<Style Selector="Button.Mini">
<Setter Property="Padding" Value="8,3" />
<Setter Property="FontSize" Value="12" />
</Style>
<Style Selector="ListBox.Pick">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="{StaticResource Line}" />
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
</Style>
<Style Selector="ListBoxItem.PickItem">
<Setter Property="Padding" Value="8,6" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
<Style Selector="TextBlock.state2">
<Setter Property="IsVisible" Value="True" />
</Style>
<Style Selector="TextBlock.state3">
<Setter Property="IsVisible" Value="True" />
</Style>
</UserControl.Styles>
<UserControl.Resources>
<DataTemplate x:Key="StepRow" DataType="{x:Type ed:StepNode}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock>
<Run Text="{Binding Id}" Foreground="{StaticResource Accent}" />
<Run Text=" " />
<Run Text="{Binding Name}" />
</TextBlock>
<StackPanel Grid.Column="1" Orientation="Horizontal">
<Button Content="↑" Margin="2,0,0,0" Command="{Binding DataContext.Recipe.MoveStepUpCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" CommandParameter="{Binding}" Classes="Mini" />
<Button Content="↓" Margin="2,0,0,0" Command="{Binding DataContext.Recipe.MoveStepDownCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" CommandParameter="{Binding}" Classes="Mini" />
<Button Content="×" Margin="2,0,0,0" Foreground="{StaticResource Ng}" Command="{Binding DataContext.Recipe.RemoveStepCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" CommandParameter="{Binding}" Classes="Mini" />
</StackPanel>
</Grid>
</DataTemplate>
<DataTemplate x:Key="RegionRow" DataType="{x:Type ed:RegionNode}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal">
<Rectangle Width="10" Height="10" Fill="{Binding Brush}" VerticalAlignment="Center" />
<TextBlock Margin="6,0,0,0">
<Run Text="{Binding Key}" Foreground="{StaticResource Accent}" />
<Run Text=" " />
<Run Text="{Binding Name}" />
</TextBlock>
</StackPanel>
<Button Grid.Column="1" Content="×" Foreground="{StaticResource Ng}" Command="{Binding DataContext.Recipe.RemoveRegionCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" CommandParameter="{Binding}" Classes="Mini" />
</Grid>
</DataTemplate>
</UserControl.Resources>
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal" Margin="0,0,0,10">
<TextBlock Text="{Binding Title}" Classes="Title" />
<TextBlock Text="文件名" Margin="24,0,8,0" Classes="Field" />
<TextBox Width="150" IsEnabled="{Binding Recipe.CanEditFileName}" Text="{Binding Recipe.FileName, Mode=TwoWay}" ToolTip.Tip="只有新建时能改——SOP 页是按文件名选配方的" />
<TextBlock Text="配方名" Margin="16,0,8,0" Classes="Field" />
<TextBox Width="170" Text="{Binding Recipe.Name, Mode=TwoWay}" />
<TextBlock Text="版本" Margin="16,0,8,0" Classes="Field" />
<TextBox Width="60" Text="{Binding Recipe.Version, Mode=TwoWay}" />
</StackPanel>
<TabControl Grid.Row="1">
<TabItem Header="步骤">
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="270" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<DockPanel>
<Button DockPanel.Dock="Bottom" Content="加步骤" Margin="0,8,0,0" Padding="0,6" Command="{Binding Recipe.AddStepCommand}" />
<ListBox ItemTemplate="{StaticResource StepRow}" ItemsSource="{Binding Recipe.Steps}" SelectedItem="{Binding Recipe.SelectedStep}" Classes="Pick" />
</DockPanel>
<ScrollViewer Grid.Column="1" Margin="12,0,0,0" VerticalScrollBarVisibility="Auto" DataContext="{Binding Recipe.SelectedStep}">
<StackPanel>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="步骤号" Classes="Field" />
<TextBox Grid.Column="1" Text="{Binding Id, Mode=TwoWay}" />
<TextBlock Grid.Column="2" Text="超时秒" Margin="16,0,8,0" Classes="Field" />
<TextBox Grid.Column="3" Text="{Binding Timeout, Mode=TwoWay}" />
</Grid>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="步骤名" Classes="Field" />
<TextBox Grid.Column="1" Text="{Binding Name, Mode=TwoWay}" />
<TextBlock Grid.Column="2" Text="节拍毫秒" Margin="16,0,8,0" Classes="Field" />
<TextBox Grid.Column="3" Text="{Binding StandardDurationMs, Mode=TwoWay}" />
</Grid>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="说明" Classes="Field" />
<TextBox Grid.Column="1" Text="{Binding Description, Mode=TwoWay}" />
</Grid>
<TextBlock Text="判定条件" FontSize="13" Margin="0,10,0,6" Classes="Title" />
<StackPanel>
<TextBlock Text="请先选择判定方法;等待后完成请选择 time_elapsed" Classes.state2="{Binding Detection, Converter={x:Static conv:ObjectConverters.IsNull}}" Classes.state3="{Binding Detection.Method, Converter={x:Static conv:StringConverters.IsNullOrEmpty}}" IsVisible="False">
</TextBlock>
<Grid Margin="0,8,0,0" Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="方法" Classes="Field" />
<ComboBox Grid.Column="1" ItemsSource="{Binding DataContext.Recipe.Methods, RelativeSource={RelativeSource AncestorType=UserControl}}" SelectedItem="{Binding Detection.Method, Converter={StaticResource SelectionConverter}}" />
<TextBlock Grid.Column="2" Text="目标类别" Margin="16,0,8,0" Classes="Field" />
<TextBox Grid.Column="3" Text="{Binding Detection.TargetObject, Mode=TwoWay}" />
</Grid>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="主区域" Classes="Field" />
<ComboBox Grid.Column="1" ItemsSource="{Binding DataContext.Recipe.RegionNames, RelativeSource={RelativeSource AncestorType=UserControl}}" SelectedItem="{Binding Detection.Region, Converter={StaticResource SelectionConverter}}" />
<TextBlock Grid.Column="2" Text="起点区域" Margin="16,0,8,0" Classes="Field" />
<ComboBox Grid.Column="3" ItemsSource="{Binding DataContext.Recipe.RegionNames, RelativeSource={RelativeSource AncestorType=UserControl}}" SelectedItem="{Binding Detection.FromRegion, Converter={StaticResource SelectionConverter}}" />
</Grid>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="终点区域" Classes="Field" />
<ComboBox Grid.Column="1" ItemsSource="{Binding DataContext.Recipe.RegionNames, RelativeSource={RelativeSource AncestorType=UserControl}}" SelectedItem="{Binding Detection.ToRegion, Converter={StaticResource SelectionConverter}}" />
<TextBlock Grid.Column="2" Text="手" Margin="16,0,8,0" Classes="Field" />
<ComboBox Grid.Column="3" ItemsSource="{Binding DataContext.Recipe.Hands, RelativeSource={RelativeSource AncestorType=UserControl}}" SelectedItem="{Binding Detection.Hand, Converter={StaticResource SelectionConverter}}" />
</Grid>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="容差像素" Classes="Field" />
<TextBox Grid.Column="1" Text="{Binding Detection.Tolerance, Mode=TwoWay}" />
</Grid>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="置信度" Classes="Field" />
<TextBox Grid.Column="1" Text="{Binding Detection.MinConfidence, Mode=TwoWay}" />
<TextBlock Grid.Column="2" Text="稳定帧" Margin="16,0,8,0" Classes="Field" />
<TextBox Grid.Column="3" Text="{Binding Detection.StableFrames, Mode=TwoWay}" />
</Grid>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="计时毫秒" Classes="Field" />
<TextBox Grid.Column="1" Text="{Binding Detection.DurationMs, Mode=TwoWay}" HorizontalAlignment="Left" Width="120" />
</Grid>
<TextBlock Text="time_elapsed / hand_move 豁免稳定帧门控(自带时序或瞬时语义)" Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,0,0,6" />
</StackPanel>
<DockPanel Margin="0,10,0,6">
<Button DockPanel.Dock="Right" Content="加必留物品" Command="{Binding MustKeep.AddCommand}" Classes="Mini" />
<TextBlock FontSize="13" Text="{Binding MustKeep.Title}" Classes="Title" />
</DockPanel>
<ItemsControl ItemsSource="{Binding MustKeep.Items}" />
<DockPanel Margin="0,10,0,6">
<Button DockPanel.Dock="Right" Content="加完成必需物品" Command="{Binding RequiredObjects.AddCommand}" Classes="Mini" />
<TextBlock FontSize="13" Text="{Binding RequiredObjects.Title}" Classes="Title" />
</DockPanel>
<ItemsControl ItemsSource="{Binding RequiredObjects.Items}" />
<DockPanel Margin="0,10,0,6">
<Button DockPanel.Dock="Right" Content="加违规规则" Command="{Binding ViolationRules.AddCommand}" Classes="Mini" />
<TextBlock FontSize="13" Text="{Binding ViolationRules.Title}" Classes="Title" />
</DockPanel>
<ItemsControl ItemsSource="{Binding ViolationRules.Items}" />
</StackPanel>
</ScrollViewer>
</Grid>
</TabItem>
<TabItem Header="区域">
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="180" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="230" />
</Grid.ColumnDefinitions>
<DockPanel>
<Button DockPanel.Dock="Bottom" Content="加区域" Margin="0,8,0,0" Padding="0,6" Command="{Binding Recipe.AddRegionCommand}" />
<ListBox ItemTemplate="{StaticResource RegionRow}" ItemsSource="{Binding Recipe.Regions}" SelectedItem="{Binding Recipe.SelectedRegion}" Classes="Pick" />
</DockPanel>
<Grid Grid.Column="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" MinHeight="210" />
</Grid.RowDefinitions>
<WrapPanel Margin="0,0,0,6">
<Button Content="从相机取图" Command="{Binding CaptureImageCommand}" Classes="Mini" />
<Button Content="打开图片" Command="{Binding OpenImageCommand}" Margin="8,0,0,0" Classes="Mini" />
</WrapPanel>
<TextBlock Grid.Row="1" Text="选中左侧区域,再在图上拖动画框" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,0,0,6" />
<TextBlock Grid.Row="2" Text="{Binding PreviewStatus}" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,0,0,6" />
<Border Grid.Row="3" Padding="0" CornerRadius="4" ClipToBounds="True" Classes="panel">
<ed:RegionCanvas Image="{Binding PreviewImage}" Regions="{Binding Recipe.Regions}" SelectedRegion="{Binding Recipe.SelectedRegion, Mode=TwoWay}" />
</Border>
</Grid>
<ScrollViewer x:Name="RegionParameters" Grid.Column="2" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">
<StackPanel DataContext="{Binding Recipe.SelectedRegion}">
<TextBlock Text="区域参数" FontSize="13" Margin="0,0,0,10" Classes="Title" />
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="54" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="键名" Foreground="{StaticResource FgDim}" />
<TextBox Grid.Column="1" Text="{Binding Key, Mode=TwoWay}" />
</Grid>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="54" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="显示名" Foreground="{StaticResource FgDim}" />
<TextBox Grid.Column="1" Text="{Binding Name, Mode=TwoWay}" />
</Grid>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="54" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="X1" Foreground="{StaticResource FgDim}" />
<TextBox Grid.Column="1" Text="{Binding X1, Mode=TwoWay}" />
</Grid>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="54" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="Y1" Foreground="{StaticResource FgDim}" />
<TextBox Grid.Column="1" Text="{Binding Y1, Mode=TwoWay}" />
</Grid>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="54" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="X2" Foreground="{StaticResource FgDim}" />
<TextBox Grid.Column="1" Text="{Binding X2, Mode=TwoWay}" />
</Grid>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="54" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="Y2" Foreground="{StaticResource FgDim}" />
<TextBox Grid.Column="1" Text="{Binding Y2, Mode=TwoWay}" />
</Grid>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="54" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="颜色" Foreground="{StaticResource FgDim}" />
<TextBox Grid.Column="1" Text="{Binding Color, Mode=TwoWay}" />
<Rectangle Grid.Column="2" Width="18" Height="18" Fill="{Binding Brush}" Margin="6,0,0,0" VerticalAlignment="Center" />
</Grid>
<TextBlock Text="说明" Foreground="{StaticResource FgDim}" Margin="0,4,0,6" />
<TextBox Text="{Binding Description, Mode=TwoWay}" TextWrapping="Wrap" AcceptsReturn="True" Height="72" ScrollViewer.VerticalScrollBarVisibility="Auto" />
<TextBlock Text="坐标使用原图像素;画框更新右侧数值,也可手动微调。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,12,0,0" />
<TextBlock Text="改键名会同步更新所有步骤里对它的引用" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" Margin="0,8,0,0" />
</StackPanel>
</ScrollViewer>
</Grid>
</TabItem>
<TabItem Header="全局设置">
<StackPanel Margin="10" DataContext="{Binding Recipe.Settings}">
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="置信度" Classes="Field" />
<TextBox Grid.Column="1" Text="{Binding ConfidenceThreshold, Mode=TwoWay}" HorizontalAlignment="Left" Width="120" />
<TextBlock Grid.Column="2" Text="稳定帧" Margin="16,0,8,0" Classes="Field" />
<TextBox Grid.Column="3" Text="{Binding StableFrames, Mode=TwoWay}" HorizontalAlignment="Left" Width="120" />
</Grid>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="命中容差" Classes="Field" />
<TextBox Grid.Column="1" Text="{Binding PositionTolerance, Mode=TwoWay}" HorizontalAlignment="Left" Width="120" />
<TextBlock Grid.Column="2" Text="抽帧" Margin="16,0,8,0" Classes="Field" />
<TextBox Grid.Column="3" Text="{Binding FrameStride, Mode=TwoWay}" HorizontalAlignment="Left" Width="120" />
</Grid>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="复位延时" Classes="Field" />
<TextBox Grid.Column="1" Text="{Binding ResetDelaySec, Mode=TwoWay}" HorizontalAlignment="Left" Width="120" />
</Grid>
<StackPanel Orientation="Horizontal" Margin="0,10,0,0">
<CheckBox Content="超时违规" IsChecked="{Binding EnableTimeoutDetection}" Margin="0,0,20,0" />
<CheckBox Content="完成后自动复位" IsChecked="{Binding AutoResetOnComplete}" />
</StackPanel>
</StackPanel>
</TabItem>
<TabItem Header="检测模型">
<StackPanel x:Name="ModelSettings" Margin="10" DataContext="{Binding Recipe}">
<CheckBox Content="使用检测模型(object_* 与 hand_near_object / person_present 依赖它)" IsChecked="{Binding HasModel}" Margin="0,0,0,10" />
<StackPanel Orientation="Horizontal" Margin="0,0,0,10">
<TextBlock Text="相机曝光(μs)" VerticalAlignment="Center" Margin="0,0,8,0" />
<TextBox x:Name="CameraExposureInput" Width="120" Text="{Binding Settings.ExposureTimeUs, Mode=TwoWay}" ToolTip.Tip="海康相机曝光时间,10000 为 10 毫秒;留空保留相机设置。保存配方后保留,区域取图和 SOP 启动前应用。" />
</StackPanel>
<StackPanel DataContext="{Binding Model}" IsVisible="{Binding DataContext.HasModel, ElementName=ModelSettings}">
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="模型路径" Classes="Field" />
<TextBox Grid.Column="1" Text="{Binding Path, Mode=TwoWay}" />
<Button Grid.Column="2" Content="选择模型…" Margin="8,0,0,0" Command="{Binding DataContext.BrowseModelCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" Classes="Mini" />
</Grid>
<Grid Classes="Row">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="输入尺寸" Classes="Field" />
<TextBox Grid.Column="1" Text="{Binding InputSize, Mode=TwoWay}" HorizontalAlignment="Left" Width="120" />
</Grid>
<StackPanel DataContext="{Binding Classes}">
<TextBlock FontSize="13" Margin="0,10,0,6" Text="{Binding Title}" Classes="Title" />
<StackPanel Orientation="Horizontal" Margin="0,0,0,6">
<Button Content="加类别" Command="{Binding AddCommand}" Classes="Mini" />
</StackPanel>
<ItemsControl ItemsSource="{Binding Items}" />
</StackPanel>
</StackPanel>
<TextBlock Margin="0,10,0,0" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" Text="可选择 .onnx 模型文件,或手填相对程序目录的路径;当前用的 yolo11n 是 AGPL-3.0 血统,量产前换掉(见 README)" />
</StackPanel>
</TabItem>
</TabControl>
<Grid Grid.Row="2" Margin="0,10,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel>
<TextBlock Text="{Binding SaveStatus}" Foreground="{StaticResource Ok}" FontSize="12" />
<TextBlock Text="校验提醒(不阻止保存;现场常见先存草稿再补区域)" Foreground="{StaticResource FgDim}" FontSize="12" />
<ItemsControl ItemsSource="{Binding Warnings}" MaxHeight="66">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Foreground="{StaticResource Ng}" FontSize="12" Text="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Bottom">
<Button Content="关闭" Command="{Binding CloseCommand}" Margin="0,0,8,0" />
<Button Content="保存" Command="{Binding SaveCommand}" Background="{StaticResource Panel}" BorderBrush="{StaticResource Accent}" />
</StackPanel>
</Grid>
</Grid>
</UserControl>

View File

@ -0,0 +1,4 @@
using Avalonia.Controls;
namespace SopHelper.VVMs.RecipeEditor;
public partial class RecipeEditor : UserControl
{ public RecipeEditor() { InitializeComponent(); } }

View File

@ -0,0 +1,318 @@
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using Avalonia.Media;
using SopHelper.Presentation.Imaging;
using SopHelper.Presentation;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Mvvm;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Camera;
namespace SopHelper.VVMs.RecipeEditor;
/// <summary>
/// 配方编辑器(SOP 页「编辑」按钮弹出)。表单在 EditorNodes 那一侧,
/// 保存时整体映射回 SopConfig 交给 SopConfigLoader 写 YAML。
/// 类名必须是"视图全名 + ViewModel",Prism 的 ViewModelLocator 按这个约定绑定(见 App)。
/// </summary>
public class RecipeEditorViewModel : BindableBase, IDialogAware
{
private RecipeNode _recipe = new();
private string _path = "";
private bool _isNew;
private Action<string>? _onSaved;
private readonly HashSet<EditorNode> _observedStepNodes = [];
private string _saveStatus = "";
public string SaveStatus { get => _saveStatus; private set => SetProperty(ref _saveStatus, value); }
private BitmapSource? _previewImage;
private string _previewStatus = "选中一个区域后,在图像上拖动画框;Esc 取消本次绘制";
private bool _isCapturing;
private ICameraService? _camera;
private CameraInfo? _cameraInfo;
public BitmapSource? PreviewImage { get => _previewImage; private set => SetProperty(ref _previewImage, value); }
public string PreviewStatus { get => _previewStatus; private set => SetProperty(ref _previewStatus, value); }
public bool IsCapturing
{
get => _isCapturing;
private set
{
if (!SetProperty(ref _isCapturing, value)) return;
CaptureImageCommand.RaiseCanExecuteChanged();
OpenImageCommand.RaiseCanExecuteChanged();
BrowseModelCommand.RaiseCanExecuteChanged();
SaveCommand.RaiseCanExecuteChanged();
CloseCommand.RaiseCanExecuteChanged();
}
}
public DelegateCommand CaptureImageCommand { get; }
public DelegateCommand OpenImageCommand { get; }
public DelegateCommand BrowseModelCommand { get; }
/// <summary>当前编辑的配方目录(configs/sop)</summary>
private string _directory = "";
/// <inheritdoc />
public string Title => _isNew ? "新建配方" : $"编辑配方 - {FileNameText}";
/// <inheritdoc />
public DialogCloseListener RequestClose { get; } = new();
/// <summary>标题栏显示的文件名</summary>
public string FileNameText => string.IsNullOrEmpty(_path) ? $"{_recipe.FileName}.yaml(新建)" : Path.GetFileName(_path);
/// <summary>编辑中的配方</summary>
public RecipeNode Recipe
{
get { return _recipe; }
private set
{
if (!SetProperty(ref _recipe, value)) return;
RaisePropertyChanged(nameof(FileNameText));
RaisePropertyChanged(nameof(Title));
}
}
/// <summary>保存前的校验提醒(不阻止保存——现场常见"先存草稿再补区域")</summary>
public ObservableCollection<string> Warnings { get; } = [];
/// <summary>保存</summary>
public DelegateCommand SaveCommand { get; private set; } = null!;
/// <summary>关闭编辑器,未保存的修改不写入文件</summary>
public DelegateCommand CloseCommand { get; private set; } = null!;
/// <summary>
/// 配方编辑器
/// </summary>
public RecipeEditorViewModel()
{
SaveCommand = new DelegateCommand(Save, () => !IsCapturing);
CloseCommand = new DelegateCommand(() => RequestClose.Invoke(ButtonResult.Cancel), () => !IsCapturing);
CaptureImageCommand = new DelegateCommand(async () => await CaptureImageAsync(),
() => !IsCapturing && _camera is not null && _cameraInfo is not null);
OpenImageCommand = new DelegateCommand(OpenImage, () => !IsCapturing);
BrowseModelCommand = new DelegateCommand(BrowseModel, () => !IsCapturing);
}
/// <inheritdoc />
public void OnDialogOpened(IDialogParameters parameters)
{
_directory = parameters.GetValue<string>("directory") ?? "";
_path = parameters.GetValue<string>("path") ?? "";
_isNew = parameters.GetValue<bool>("new");
_onSaved = parameters.GetValue<Action<string>>("onSaved");
SaveStatus = "";
_camera = parameters.GetValue<ICameraService>("cameraService");
_cameraInfo = parameters.GetValue<CameraInfo>("cameraInfo");
PreviewImage = parameters.GetValue<BitmapSource>("preview");
CaptureImageCommand.RaiseCanExecuteChanged();
if (PreviewImage is not null) DescribeImage("最近一帧");
else if (_cameraInfo is null) PreviewStatus = "请在 SOP 页先选择相机,或打开图片;选中区域后在图上拖动画框";
var config = parameters.GetValue<SopConfig>("config") ?? new SopConfig();
// 新建时文件名还没定,用配方名兜底;已存在的文件名不可改(SOP 页按文件名选配方)
var fileName = string.IsNullOrEmpty(_path) ? config.Sop.Name : Path.GetFileNameWithoutExtension(_path);
Recipe = RecipeNode.From(config, fileName, _isNew);
Recipe.Changed += RefreshWarnings;
RefreshWarnings();
}
/// <inheritdoc />
public bool CanCloseDialog() => !IsCapturing;
/// <inheritdoc />
public void OnDialogClosed()
{
Recipe.Changed -= RefreshWarnings;
foreach (var node in _observedStepNodes) node.PropertyChanged -= StepChanged;
_observedStepNodes.Clear();
_onSaved = null;
}
private void DescribeImage(string source) => PreviewStatus =
$"{source} · {PreviewImage!.PixelWidth} × {PreviewImage.PixelHeight} 像素;选中区域后拖动画框,Esc 取消";
private async void OpenImage()
{
var dialog = new OpenFileDialog
{
Title = "选择区域标定图片(使用与相机相同分辨率的原图)",
Filter = "图像|*.png;*.jpg;*.jpeg;*.bmp;*.tif;*.tiff|所有文件|*.*",
};
if (await dialog.ShowDialogAsync() != true) return;
try
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(dialog.FileName, UriKind.Absolute);
image.EndInit();
image.Freeze();
PreviewImage = image;
DescribeImage(Path.GetFileName(dialog.FileName));
}
catch (Exception ex) { PreviewStatus = "打开图片失败:" + ex.Message; }
}
private async void BrowseModel()
{
if (Recipe.Model is null) return;
var dialog = new OpenFileDialog
{
Title = "选择 ONNX 检测模型",
Filter = "ONNX 模型 (*.onnx)|*.onnx",
DefaultExt = ".onnx",
CheckFileExists = true,
Multiselect = false,
InitialDirectory = AppContext.BaseDirectory,
};
try
{
if (!string.IsNullOrWhiteSpace(Recipe.Model.Path))
{
var currentPath = Path.GetFullPath(Recipe.Model.Path, AppContext.BaseDirectory);
var directory = Path.GetDirectoryName(currentPath);
if (Directory.Exists(directory)) dialog.InitialDirectory = directory;
if (File.Exists(currentPath)) dialog.FileName = Path.GetFileName(currentPath);
}
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
// 手填路径无效时,仍可从程序目录重新选择。
}
if (await dialog.ShowDialogAsync() != true) return;
Recipe.Model.Path = dialog.FileName;
RefreshWarnings();
}
private async Task CaptureImageAsync()
{
if (IsCapturing || _camera is null || _cameraInfo is null) return;
var camera = _camera;
IsCapturing = true;
PreviewStatus = "正在取图…";
var ready = new TaskCompletionSource<BitmapSource>(TaskCreationOptions.RunContinuationsAsynchronously);
void Receive(CameraFrame frame)
{
if (ready.Task.IsCompleted) return;
try
{
// 不保留相机 Mat;图像在采集线程复制并冻结后再交给 UI。
using var copy = frame.Bgr.Clone();
var bytes = new byte[checked(copy.Rows * copy.Cols * 3)];
Marshal.Copy(copy.Data, bytes, 0, bytes.Length);
var bitmap = BitmapSource.Create(copy.Cols, copy.Rows, 96, 96, PixelFormats.Bgr24,
null, bytes, copy.Cols * 3);
bitmap.Freeze();
ready.TrySetResult(bitmap);
}
catch (Exception ex) { ready.TrySetException(ex); }
}
try
{
if (!await camera.ConnectAsync(_cameraInfo)) throw new InvalidOperationException("连接相机失败,请查看 SOP 页日志");
if (Recipe.Settings.ExposureTimeUs is { } exposure)
{
if (!double.IsFinite(exposure) || exposure <= 0)
throw new InvalidOperationException("相机曝光必须大于 0(微秒),或留空保留相机设置");
await camera.SetExposureTimeAsync(exposure);
}
camera.FrameArrived += Receive;
if (!await camera.StartAsync()) throw new InvalidOperationException("启动采集失败");
PreviewImage = await ready.Task.WaitAsync(TimeSpan.FromSeconds(5));
DescribeImage(_cameraInfo.Name);
}
catch (Exception ex) { PreviewStatus = "取图失败:" + ex.Message; }
finally
{
camera.FrameArrived -= Receive;
try { await Task.Run(camera.Disconnect); }
catch (Exception ex) { PreviewStatus = "关闭相机失败:" + ex.Message; }
IsCapturing = false;
}
}
private void Save()
{
SaveStatus = "";
if (Recipe.Settings.ExposureTimeUs is { } exposure && (!double.IsFinite(exposure) || exposure <= 0))
{
Warnings.Add("相机曝光必须大于 0(微秒),或留空保留相机设置");
return;
}
if (string.IsNullOrWhiteSpace(Recipe.Name))
{
Warnings.Add("配方名(sop.name)不能为空");
return;
}
var fileName = string.IsNullOrWhiteSpace(Recipe.FileName) ? Recipe.Name : Recipe.FileName;
// 只取文件名部分,别让人在这儿塞路径
fileName = string.Join("_", fileName.Split(Path.GetInvalidFileNameChars()));
var path = string.IsNullOrEmpty(_path) ? Path.Combine(_directory, fileName + ".yaml") : _path;
try
{
// Save 内部落盘后会回读校验,返回值就是磁盘上那份
var saved = SopConfigLoader.Save(Recipe.ToConfig(), path);
_path = path;
_isNew = false;
Recipe.MarkSaved(Path.GetFileNameWithoutExtension(path));
RaisePropertyChanged(nameof(FileNameText));
RaisePropertyChanged(nameof(Title));
Warnings.Clear();
foreach (var warning in saved.Warnings) Warnings.Add(warning);
SaveStatus = $"已保存 {Path.GetFileName(_path)}";
_onSaved?.Invoke(Path.GetFileName(_path));
}
catch (Exception ex)
{
// 写盘失败(文件被占用/只读)留给用户看,别让整个编辑器跟着炸
Warnings.Clear();
Warnings.Add("保存失败:" + ex.Message);
}
}
/// <summary>
/// 用当前编辑结果跑一遍加载器校验(就是"这一步永远不推进"那类问题)
/// </summary>
private void RefreshWarnings()
{
SaveStatus = "";
// 步骤和条件字段变化时同步校验,避免方法已选择却仍显示旧的缺失提示。
var current = new HashSet<EditorNode>(Recipe.Steps);
foreach (var step in Recipe.Steps)
if (step.Detection is not null) current.Add(step.Detection);
foreach (var removed in _observedStepNodes.Except(current).ToArray())
{
removed.PropertyChanged -= StepChanged;
_observedStepNodes.Remove(removed);
}
foreach (var added in current.Except(_observedStepNodes))
{
added.PropertyChanged += StepChanged;
_observedStepNodes.Add(added);
}
Warnings.Clear();
var config = Recipe.ToConfig();
SopConfigLoader.Validate(config);
foreach (var warning in config.Warnings) Warnings.Add(warning);
}
private void StepChanged(object? sender, PropertyChangedEventArgs e) => RefreshWarnings();
}

View File

@ -0,0 +1,96 @@
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using SopHelper.Presentation.Imaging;
namespace SopHelper.VVMs.RecipeEditor;
public sealed class RegionCanvas : Control
{
public static readonly StyledProperty<BitmapSource?> ImageProperty=AvaloniaProperty.Register<RegionCanvas,BitmapSource?>(nameof(Image));
public static readonly StyledProperty<ObservableCollection<RegionNode>?> RegionsProperty=AvaloniaProperty.Register<RegionCanvas,ObservableCollection<RegionNode>?>(nameof(Regions));
public static readonly StyledProperty<RegionNode?> SelectedRegionProperty=AvaloniaProperty.Register<RegionCanvas,RegionNode?>(nameof(SelectedRegion));
public BitmapSource? Image {get=>GetValue(ImageProperty);set=>SetValue(ImageProperty,value);}
public ObservableCollection<RegionNode>? Regions {get=>GetValue(RegionsProperty);set=>SetValue(RegionsProperty,value);}
public RegionNode? SelectedRegion {get=>GetValue(SelectedRegionProperty);set=>SetValue(SelectedRegionProperty,value);}
private readonly HashSet<RegionNode> _observed=[];
private Point? _start;private Point _end;private RegionNode? _drawingRegion;private IPointer? _pointer;
static RegionCanvas(){AffectsRender<RegionCanvas>(ImageProperty,RegionsProperty,SelectedRegionProperty);}
public RegionCanvas(){Focusable=true;Cursor=new Cursor(StandardCursorType.Cross);DetachedFromVisualTree+=(_,_)=>CancelDrag();}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if(change.Property==ImageProperty||change.Property==SelectedRegionProperty)CancelDrag();
if(change.Property==RegionsProperty)
{
if(change.OldValue is ObservableCollection<RegionNode> old)old.CollectionChanged-=CollectionChanged;
if(change.NewValue is ObservableCollection<RegionNode> current)current.CollectionChanged+=CollectionChanged;
ObserveRegions();
}
}
public static Rect FitImage(Size viewport,Size image)
{
if(viewport.Width<=0||viewport.Height<=0||image.Width<=0||image.Height<=0)return default;
var scale=Math.Min(viewport.Width/image.Width,viewport.Height/image.Height);var size=new Size(image.Width*scale,image.Height*scale);
return new Rect(new Point((viewport.Width-size.Width)/2,(viewport.Height-size.Height)/2),size);
}
public static Point ToImage(Point point,Rect display,Size image)=>new(
Math.Clamp((point.X-display.X)*image.Width/display.Width,0,image.Width),Math.Clamp((point.Y-display.Y)*image.Height/display.Height,0,image.Height));
public static PixelRect PixelBounds(Point first,Point last,Size image)
{
var x1=(int)Math.Clamp(Math.Floor(Math.Min(first.X,last.X)),0,image.Width);var y1=(int)Math.Clamp(Math.Floor(Math.Min(first.Y,last.Y)),0,image.Height);
var x2=(int)Math.Clamp(Math.Ceiling(Math.Max(first.X,last.X)),0,image.Width);var y2=(int)Math.Clamp(Math.Ceiling(Math.Max(first.Y,last.Y)),0,image.Height);
return new PixelRect(x1,y1,x2-x1,y2-y1);
}
public override void Render(DrawingContext dc)
{
dc.DrawRectangle(new SolidColorBrush(Color.FromRgb(10,16,22)),null,new Rect(Bounds.Size));
if(Image is null)
{
var text=new FormattedText("从相机取图,或打开一张图片后画框",CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Microsoft YaHei, Noto Sans CJK SC"),13,Brushes.LightGray);
dc.DrawText(text,new Point(Math.Max(8,(Bounds.Width-text.Width)/2),Math.Max(8,Bounds.Height/2-text.Height/2)));return;
}
var size=new Size(Image.PixelWidth,Image.PixelHeight);var display=FitImage(Bounds.Size,size);if(display.Width<=0)return;
dc.DrawImage(Image,display);var scale=display.Width/size.Width;
using var clip=dc.PushClip(display);using var transform=dc.PushTransform(new Matrix(scale,0,0,scale,display.X,display.Y));
foreach(var region in Regions??[])
{
if(region.X2<=region.X1||region.Y2<=region.Y1)continue;
var rect=new Rect(region.X1,region.Y1,region.X2-region.X1,region.Y2-region.Y1);var selected=ReferenceEquals(region,SelectedRegion);
if(selected)dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(35,0,184,212)),null,rect);
dc.DrawRectangle(null,new Pen(region.Brush,(selected?3:1.5)/scale),rect);
var label=new FormattedText(string.IsNullOrWhiteSpace(region.Name)?region.Key:region.Name,CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Microsoft YaHei, Noto Sans CJK SC"),12/scale,region.Brush);
var origin=new Point(Math.Max(0,rect.X),Math.Max(0,rect.Y-label.Height));dc.DrawRectangle(Brushes.Black,null,new Rect(origin,new Size(label.Width,label.Height)));dc.DrawText(label,origin);
}
if(_start is Point start)dc.DrawRectangle(null,new Pen(Brushes.Yellow,2/scale,new DashStyle([2,2],0)),
new Rect(Math.Min(start.X,_end.X),Math.Min(start.Y,_end.Y),Math.Abs(start.X-_end.X),Math.Abs(start.Y-_end.Y)));
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);if(!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed||Image is null||SelectedRegion is null)return;
var display=FitImage(Bounds.Size,new Size(Image.PixelWidth,Image.PixelHeight));var point=e.GetPosition(this);if(display.Width<=0||!display.Contains(point))return;
Focus();_pointer=e.Pointer;_pointer.Capture(this);_drawingRegion=SelectedRegion;_start=_end=ToImage(point,display,new Size(Image.PixelWidth,Image.PixelHeight));InvalidateVisual();e.Handled=true;
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);if(_start is null||Image is null)return;
_end=ToImage(e.GetPosition(this),FitImage(Bounds.Size,new Size(Image.PixelWidth,Image.PixelHeight)),new Size(Image.PixelWidth,Image.PixelHeight));InvalidateVisual();e.Handled=true;
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);if(_start is not Point start||Image is null)return;
var size=new Size(Image.PixelWidth,Image.PixelHeight);var display=FitImage(Bounds.Size,size);var end=ToImage(e.GetPosition(this),display,size);var bounds=PixelBounds(start,end,size);
if(bounds.Width*display.Width/size.Width>=4&&bounds.Height*display.Height/size.Height>=4&&ReferenceEquals(_drawingRegion,SelectedRegion))_drawingRegion?.SetBounds(bounds);
CancelDrag();e.Handled=true;
}
protected override void OnKeyDown(KeyEventArgs e){if(e.Key==Key.Escape&&_start is not null){CancelDrag();e.Handled=true;}else base.OnKeyDown(e);}
protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e){base.OnPointerCaptureLost(e);CancelDrag();}
private void CancelDrag(){_start=null;_drawingRegion=null;var pointer=_pointer;_pointer=null;if(pointer?.Captured==this)pointer.Capture(null);InvalidateVisual();}
private void CollectionChanged(object? sender,NotifyCollectionChangedEventArgs e){CancelDrag();ObserveRegions();}
private void ObserveRegions(){foreach(var n in _observed)n.PropertyChanged-=NodeChanged;_observed.Clear();foreach(var n in Regions??[]){_observed.Add(n);n.PropertyChanged+=NodeChanged;}InvalidateVisual();}
private void NodeChanged(object? sender,PropertyChangedEventArgs e)=>InvalidateVisual();
}

View File

@ -0,0 +1,35 @@
using System.Globalization;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
using SopHelper.Engine.Common;
namespace SopHelper.VVMs.SopPage;
public sealed class DetectionOverlay : Control
{
public static readonly StyledProperty<FrameResult?> ResultProperty=AvaloniaProperty.Register<DetectionOverlay,FrameResult?>(nameof(Result));
public FrameResult? Result {get=>GetValue(ResultProperty);set=>SetValue(ResultProperty,value);}
static DetectionOverlay(){AffectsRender<DetectionOverlay>(ResultProperty);}
public override void Render(DrawingContext dc)
{
base.Render(dc);var result=Result;if(result is null || result.Size.W<=0 || result.Size.H<=0 || Bounds.Width<=0 || Bounds.Height<=0)return;
using var clip=dc.PushClip(new Rect(Bounds.Size));
using var transform=dc.PushTransform(Matrix.CreateScale(Bounds.Width/result.Size.W,Bounds.Height/result.Size.H));
var unit=Math.Max(result.Size.W,result.Size.H)/700.0;
var imageBounds=new Rect(0,0,result.Size.W,result.Size.H);
var background=new SolidColorBrush(Color.FromArgb(220,12,18,24));
var padding=3*unit;
foreach(var d in result.Detections)
{
var r=d.Rect;if(r.W<=0||r.H<=0||!float.IsFinite(r.X)||!float.IsFinite(r.Y)||!float.IsFinite(r.Right)||!float.IsFinite(r.Bottom)||!float.IsFinite(d.Confidence))continue;
var rect=imageBounds.Intersect(new Rect(r.X,r.Y,r.W,r.H));if(rect.Width<=0||rect.Height<=0)continue;
dc.DrawRectangle(null,new Pen(Brushes.Orange,2*unit),rect);
var text=new FormattedText($"{d.Label} {d.Confidence:P0}",CultureInfo.CurrentCulture,FlowDirection.LeftToRight,new Typeface("Microsoft YaHei, Noto Sans CJK SC"),12*unit,Brushes.White)
{MaxTextWidth=Math.Max(1,imageBounds.Width-2*padding),MaxLineCount=1,Trimming=TextTrimming.CharacterEllipsis};
var size=new Size(text.Width+2*padding,text.Height+2*padding);
var left=Math.Clamp(rect.Left,0,Math.Max(0,imageBounds.Width-size.Width));
var top=Math.Clamp(rect.Top>=size.Height?rect.Top-size.Height:rect.Top,0,Math.Max(0,imageBounds.Height-size.Height));
dc.DrawRectangle(background,null,new Rect(new Point(left,top),size));dc.DrawText(text,new Point(left+padding,top+padding));
}
}
}

View File

@ -0,0 +1,30 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
using SopHelper.Engine.Common;
namespace SopHelper.VVMs.SopPage;
public sealed class HandOverlay : Control
{
public static readonly StyledProperty<FrameResult?> ResultProperty=AvaloniaProperty.Register<HandOverlay,FrameResult?>(nameof(Result));
public FrameResult? Result { get=>GetValue(ResultProperty);set=>SetValue(ResultProperty,value); }
private static readonly (int From,int To)[] Bones=[(0,1),(1,2),(2,3),(3,4),(0,5),(5,6),(6,7),(7,8),(5,9),(9,10),(10,11),(11,12),(9,13),(13,14),(14,15),(15,16),(13,17),(0,17),(17,18),(18,19),(19,20)];
static HandOverlay(){AffectsRender<HandOverlay>(ResultProperty);}
public override void Render(DrawingContext drawing)
{
base.Render(drawing);var result=Result;
if(result is null || result.Size.W<=0 || result.Size.H<=0 || Bounds.Width<=0 || Bounds.Height<=0)return;
using var clip=drawing.PushClip(new Rect(Bounds.Size));
using var scale=drawing.PushTransform(Matrix.CreateScale(Bounds.Width/result.Size.W,Bounds.Height/result.Size.H));
var unit=Math.Max(result.Size.W,result.Size.H)/700.0;
foreach(var hand in result.Hands)
{
var brush=hand.HandType switch {HandType.Left=>Brushes.LimeGreen,HandType.Right=>Brushes.DeepSkyBlue,_=>Brushes.Gray};
var pen=new Pen(brush,unit*2);
var points=hand.Keypoints.Where(p=>p.Index is >=0 and <=20 && p.Confidence>0 && float.IsFinite(p.X) && float.IsFinite(p.Y)).GroupBy(p=>p.Index).ToDictionary(g=>g.Key,g=>g.First());
foreach(var (from,to) in Bones)
if(points.TryGetValue(from,out var a)&&points.TryGetValue(to,out var b))drawing.DrawLine(pen,new Point(a.X,a.Y),new Point(b.X,b.Y));
foreach(var p in points.Values)drawing.DrawEllipse(Brushes.Yellow,null,new Point(p.X,p.Y),unit*3,unit*3);
}
}
}

View File

@ -0,0 +1,203 @@
<UserControl xmlns="https://github.com/avaloniaui" xmlns:local="clr-namespace:SopHelper.VVMs.SopPage" xmlns:prism="http://prismlibrary.com/" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SopHelper.VVMs.SopPage.SopPage" prism:ViewModelLocator.AutoWireViewModel="True" Background="{StaticResource Bg}" xmlns:conv="using:Avalonia.Data.Converters">
<UserControl.Styles>
<Style Selector="Rectangle.state4">
<Setter Property="IsVisible" Value="True" />
</Style>
<Style Selector="Border.state5">
<Setter Property="BorderBrush" Value="{StaticResource Accent}" />
</Style>
<Style Selector="Border.state6">
<Setter Property="BorderThickness" Value="2" />
</Style>
<Style Selector="Ellipse.state7">
<Setter Property="Fill" Value="{StaticResource Ok}" />
</Style>
</UserControl.Styles>
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="390" />
</Grid.ColumnDefinitions>
<Border Grid.Column="0" Classes="panel">
<Viewbox Stretch="Uniform" Margin="4">
<Grid Width="{Binding FrameWidth}" Height="{Binding FrameHeight}">
<Image Source="{Binding Frame}" Stretch="Fill" />
<ItemsControl ItemsSource="{Binding Rois}">
<ItemsControl.Styles>
<Style Selector="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding X}" />
<Setter Property="Canvas.Top" Value="{Binding Y}" />
</Style>
</ItemsControl.Styles>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Width="{Binding W}" Height="{Binding H}" BorderBrush="{Binding Brush}" BorderThickness="2" Background="Transparent" Padding="0" CornerRadius="0" Classes="panel">
<TextBlock Text="{Binding Name}" Foreground="{Binding Brush}" FontSize="12" Margin="2,0,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<local:DetectionOverlay Result="{Binding HandResult}" IsHitTestVisible="False" />
<local:HandOverlay Result="{Binding HandResult}" IsHitTestVisible="False" />
</Grid>
</Viewbox>
</Border>
<Grid Grid.Column="1" Margin="10,0,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Border Grid.Row="0" Classes="panel">
<StackPanel>
<TextBlock Text="参数" Classes="Title" />
<Grid Margin="0,10,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="相机" Width="40" />
<ComboBox Grid.Column="1" Height="26" VerticalContentAlignment="Center" ItemsSource="{Binding Cameras}" IsEnabled="{Binding CanSelectCamera}" SelectedItem="{Binding SelectedCamera, Converter={StaticResource SelectionConverter}}" ToolTip.Tip="支持 UVC 和海康 GigE/USB 工业相机">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Button Grid.Column="2" Content="刷新" Margin="6,0,0,0" Padding="10,4" Command="{Binding RefreshCamerasCommand}" />
</Grid>
<Grid Margin="0,8,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="配方" Width="40" />
<ComboBox Grid.Column="1" Height="26" VerticalContentAlignment="Center" ItemsSource="{Binding Recipes}" SelectedItem="{Binding SelectedRecipe, Converter={StaticResource SelectionConverter}}" />
<Button Grid.Column="2" Content="编辑" Margin="6,0,0,0" Padding="10,4" Command="{Binding EditRecipeCommand}" />
<Button Grid.Column="3" Content="新建" Margin="6,0,0,0" Padding="10,4" Command="{Binding NewRecipeCommand}" />
<Button Grid.Column="4" Content="应用" Margin="6,0,0,0" Padding="10,4" Command="{Binding ApplyRecipeCommand}" />
</Grid>
<Grid Margin="0,8,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="44" />
</Grid.ColumnDefinitions>
<TextBlock Text="阈值" Width="40" />
<Slider Grid.Column="1" Minimum="0.1" Maximum="0.95" TickFrequency="0.05" IsSnapToTickEnabled="True" Value="{Binding Confidence}" VerticalAlignment="Center" />
<TextBlock Grid.Column="2" Text="{Binding Confidence, StringFormat={}{0:F2}}" HorizontalAlignment="Right" Foreground="{StaticResource FgDim}" />
</Grid>
<Grid Margin="0,8,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="44" />
</Grid.ColumnDefinitions>
<TextBlock Text="抽帧" Width="40" />
<Slider Grid.Column="1" Minimum="1" Maximum="10" TickFrequency="1" IsSnapToTickEnabled="True" Value="{Binding FrameStride}" VerticalAlignment="Center" />
<TextBlock Grid.Column="2" Text="{Binding FrameStride}" HorizontalAlignment="Right" Foreground="{StaticResource FgDim}" />
</Grid>
<WrapPanel Margin="0,10,0,0">
<TextBlock Text="状态" Width="40" />
<TextBlock Text="{Binding StatusText}" Foreground="{StaticResource Accent}" />
<TextBlock Text="耗时" Margin="16,0,6,0" />
<TextBlock Text="{Binding InferenceText}" Foreground="{StaticResource FgDim}" />
<TextBlock Text="帧率" Margin="16,0,6,0" />
<TextBlock Text="{Binding FpsText}" Foreground="{StaticResource FgDim}" />
</WrapPanel>
</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 Content="快照" Margin="6,0,0,0" Command="{Binding SnapshotCommand}" />
</WrapPanel>
<Border Grid.Row="2" Margin="0,10,0,0" Classes="panel">
<StackPanel>
<TextBlock Text="违规 Top3" Classes="Title" />
<ItemsControl ItemsSource="{Binding Violations}" Margin="0,8,0,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Foreground="{StaticResource Ng}" TextTrimming="CharacterEllipsis">
<TextBlock.Text>
<MultiBinding StringFormat="{}{0:HH:mm:ss} {1}">
<Binding Path="Time" />
<Binding Path="Message" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
<Border Grid.Row="3" Margin="0,10,0,0" Classes="panel">
<StackPanel>
<TextBlock Text="步骤" Classes="Title" />
<ItemsControl ItemsSource="{Binding StepCards}" Margin="0,8,0,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border x:Name="card" Padding="8,6" Margin="0,0,0,6" Background="{StaticResource Bg}" BorderBrush="{StaticResource Line}" BorderThickness="1" Classes.state5="{Binding IsCurrent}" Classes.state6="{Binding IsCurrent}" Classes="panel">
<StackPanel Orientation="Horizontal">
<TextBlock Width="28" FontWeight="Bold" Foreground="{StaticResource FgDim}" Text="{Binding StepId, StringFormat={}{0}.}" />
<TextBlock Width="140" Text="{Binding Name}" />
<TextBlock Text="{Binding Message}" Foreground="{StaticResource FgDim}" TextTrimming="CharacterEllipsis" />
<Rectangle x:Name="dot" Width="8" Height="8" Margin="8,0,0,0" VerticalAlignment="Center" Fill="{StaticResource Ok}" Classes.state4="{Binding IsMet}" IsVisible="False" />
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
<Border Grid.Row="4" Margin="0,10,0,0" Padding="6" Classes="panel">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="日志" Classes="Title" />
<ListBox Grid.Row="1" Margin="0,8,0,0" Background="Transparent" BorderThickness="0" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ItemsSource="{Binding Logs}">
<ListBox.Styles>
<Style Selector="ListBoxItem">
<Setter Property="Padding" Value="0,1" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListBox.Styles>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock FontSize="12" TextWrapping="Wrap">
<TextBlock.Text>
<MultiBinding StringFormat="{}{0:HH:mm:ss} [{1}] {2}">
<Binding Path="Time" />
<Binding Path="Level" />
<Binding Path="Message" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Border>
<StackPanel Grid.Row="5" Orientation="Horizontal" Margin="0,10,0,0">
<Ellipse Width="10" Height="10" Fill="{StaticResource Line}" Classes.state7="{Binding IsConnected}">
</Ellipse>
<TextBlock Text="{Binding ConnectionText}" Margin="6,0,0,0" Foreground="{StaticResource FgDim}" />
</StackPanel>
</Grid>
</Grid>
</UserControl>

View File

@ -0,0 +1,5 @@
using Avalonia.Controls;
namespace SopHelper.VVMs.SopPage;
[SopHelper.Core.Prism.NavigationPage(ViewName="SopPage", DisplayName="SOP 辅助", Index=0)]
public partial class SopPage : UserControl
{ public SopPage() { InitializeComponent(); } }

View File

@ -0,0 +1,846 @@
using System.Collections.ObjectModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.Json;
using Avalonia.Media;
using ImageSource = Avalonia.Media.IImage;
using SopHelper.Presentation.Imaging;
using SopHelper.Presentation.Threading;
using OpenCvSharp;
using Prism.Commands;
using Prism.Dialogs;
using SopHelper.Core.Prism;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Common;
using SopHelper.Engine.Pipeline;
using SopHelper.Engine.Sop;
namespace SopHelper.VVMs.SopPage;
/// <summary>
/// SOP 主页视图模型:相机 → 推理管线 → SOP 引擎,界面只订阅事件。
/// </summary>
public class SopPageViewModel : ViewModelBase
{
private const int MaxLogLines = 300;
private const int MaxTopViolations = 3;
/// <summary>配方目录(相对程序目录)</summary>
private static string RecipeDirectory => Path.Combine(AppContext.BaseDirectory, "configs", "sop");
private static string LastCameraPath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SopHelper", "last-camera.json");
/// <summary>配方编辑器弹窗的注册名(见 App.RegisterTypes)</summary>
private const string EditorDialogName = "RecipeEditorDialog";
private readonly ICameraService _camera;
private readonly DetectionPipeline _pipeline;
private readonly SopEngine _engine;
private readonly IDialogService _dialogs;
private readonly Dispatcher _dispatcher;
private readonly DispatcherTimer _renderTimer;
/// <summary>采集线程写、UI 线程取最新帧</summary>
private readonly object _frameLock = new();
private Mat? _pending;
private bool _destroyed;
/// <summary>最近一次处理过的帧(快照按钮存盘用,由推理线程写入)</summary>
private FrameResult? _lastFrame;
private FrameResult? _handResult;
private WriteableBitmap? _bitmap;
private long _frameCount;
private long _lastTickCount;
private CameraInfo? _selectedCamera;
private CameraInfo? _lastUsedCamera;
private string? _selectedRecipe;
private ImageSource? _frame;
private string _statusText = "就绪";
private string _fpsText = "—";
private string _inferenceText = "—";
private bool _isRunning;
private bool _isConnected;
private bool _isCameraBusy;
private double _frameWidth;
private double _frameHeight;
private double _confidence = 0.6;
private int _frameStride = 2;
/// <summary>
/// SOP 主页视图模型
/// </summary>
public SopPageViewModel(ICameraService camera, DetectionPipeline pipeline, SopEngine engine, IDialogService dialogs)
{
_camera = camera;
_pipeline = pipeline;
_engine = engine;
_dialogs = dialogs;
_dispatcher = Dispatcher.CurrentDispatcher;
_camera.ConnectionChanged += on => _dispatcher.BeginInvoke(() =>
{
IsConnected = on;
if (!on && IsRunning)
{
IsRunning = false;
StatusText = "相机已断开";
RaiseCommands();
}
});
_camera.Error += message => _dispatcher.BeginInvoke(() => Log("warn", message));
_pipeline.ResultArrived += result => _dispatcher.BeginInvoke(() => OnResult(result));
// 帧 Mat 只在采集线程的事件存活期内有效(事件返回即被释放),必须当场克隆
_camera.FrameArrived += OnCameraFrame;
_engine.LogArrived += entry => _dispatcher.BeginInvoke(() => AppendLog(entry));
_engine.ViolationRaised += violation => _dispatcher.BeginInvoke(() => AppendViolation(violation));
_engine.StepSnapshotChanged += snapshot => _dispatcher.BeginInvoke(() => UpdateCard(snapshot));
_engine.Completed += () => _dispatcher.BeginInvoke(() => StatusText = "本轮完成");
// 渲染定时器:从采集线程留下的最新帧取一份画出来(天然限帧,不在采集线程做 UI 活)
_renderTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(40) };
_renderTimer.Tick += (_, _) => RenderFrame();
_renderTimer.Start();
LoadRecipes();
// 命令接线(DelegateCommand 的可用条件都挂在这里)
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);
ApplyRecipeCommand = new DelegateCommand(ApplyRecipe, () => !IsRunning && !_isCameraBusy);
SnapshotCommand = new DelegateCommand(Snapshot, () => _lastFrame is not null);
EditRecipeCommand = new DelegateCommand(EditRecipe, CanEditRecipe);
NewRecipeCommand = new DelegateCommand(NewRecipe, () => !IsRunning && !_isCameraBusy);
StatusText = "选择相机和配方,点开始";
LoadLastCamera();
_ = RefreshCamerasAsync();
}
/// <summary>可用相机</summary>
public ObservableCollection<CameraInfo> Cameras { get; } = [];
/// <summary>可用配方文件</summary>
public ObservableCollection<string> Recipes { get; } = [];
/// <summary>步骤卡</summary>
public ObservableCollection<StepCard> StepCards { get; } = [];
/// <summary>Top3 违规</summary>
public ObservableCollection<ViolationItem> Violations { get; } = [];
/// <summary>日志</summary>
public ObservableCollection<LogItem> Logs { get; } = [];
/// <summary>画面 ROI</summary>
public ObservableCollection<RoiItem> Rois { get; } = [];
/// <summary>选中相机</summary>
public CameraInfo? SelectedCamera
{
get { return _selectedCamera; }
set
{
if (!SetProperty(ref _selectedCamera, value)) return;
RaiseCommands(); // 实测:不刷新会导致"开始/停止"一直灰着,选了相机也点不动
}
}
/// <summary>选中配方</summary>
public string? SelectedRecipe
{
get { return _selectedRecipe; }
set
{
if (!SetProperty(ref _selectedRecipe, value)) return;
RaiseCommands();
}
}
/// <summary>画面</summary>
public ImageSource? Frame
{
get { return _frame; }
set { SetProperty(ref _frame, value); }
}
/// <summary>最近一次推理结果,供图像上的手部与目标检测绘制层使用。</summary>
public FrameResult? HandResult
{
get => _handResult;
private set => SetProperty(ref _handResult, value);
}
/// <summary>状态</summary>
public string StatusText
{
get { return _statusText; }
set { SetProperty(ref _statusText, value); }
}
/// <summary>结果帧率</summary>
public string FpsText
{
get { return _fpsText; }
set { SetProperty(ref _fpsText, value); }
}
/// <summary>推理耗时</summary>
public string InferenceText
{
get { return _inferenceText; }
set { SetProperty(ref _inferenceText, value); }
}
/// <summary>是否运行中</summary>
public bool IsRunning
{
get { return _isRunning; }
set
{
if (!SetProperty(ref _isRunning, value)) return;
if (!value) HandResult = null;
RaisePropertyChanged(nameof(CanSelectCamera));
RaiseCommands();
}
}
/// <summary>连接、枚举、采集期间不切换设备。</summary>
public bool CanSelectCamera => !IsRunning && !_isCameraBusy;
/// <summary>相机是否已连接</summary>
public bool IsConnected
{
get { return _isConnected; }
set
{
if (!SetProperty(ref _isConnected, value)) return;
RaisePropertyChanged(nameof(ConnectionText));
}
}
/// <summary>右下角连接文字(实测静态文字不反映状态,改成绑定)</summary>
public string ConnectionText => IsConnected ? "相机已连接" : "相机未连接";
/// <summary>画面像素宽(ROI 覆盖层按它缩放)</summary>
public double FrameWidth
{
get { return _frameWidth; }
set { SetProperty(ref _frameWidth, value); }
}
/// <summary>画面像素高</summary>
public double FrameHeight
{
get { return _frameHeight; }
set { SetProperty(ref _frameHeight, value); }
}
/// <summary>置信度阈值(透传给 YOLO)</summary>
public double Confidence
{
get { return _confidence; }
set { SetProperty(ref _confidence, value); }
}
/// <summary>抽帧间隔</summary>
public int FrameStride
{
get { return _frameStride; }
set { SetProperty(ref _frameStride, value); }
}
/// <summary>刷新相机列表</summary>
public DelegateCommand RefreshCamerasCommand { get; private set; } = null!;
/// <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!;
/// <summary>应用配方</summary>
public DelegateCommand ApplyRecipeCommand { get; private set; } = null!;
/// <summary>快照</summary>
public DelegateCommand SnapshotCommand { get; private set; } = null!;
/// <summary>编辑当前选中的配方(弹窗)</summary>
public DelegateCommand EditRecipeCommand { get; private set; } = null!;
/// <summary>新建配方(弹窗)</summary>
public DelegateCommand NewRecipeCommand { get; private set; } = null!;
private bool CanStart() => !_isCameraBusy && (SelectedCamera is not null || IsRunning);
private void SetCameraBusy(bool busy)
{
_isCameraBusy = busy;
RaisePropertyChanged(nameof(CanSelectCamera));
RaiseCommands();
}
/// <summary>运行中不改配方——引擎已按当前配方建好区域与判定,改完要重新应用</summary>
private bool CanEditRecipe() => !IsRunning && !_isCameraBusy && !string.IsNullOrWhiteSpace(SelectedRecipe);
/// <summary>
/// 刷新所有命令的可用状态。Prism 的 DelegateCommand 只在被显式 raise 时才重估 CanExecute,
/// 绑定上去的按钮不会因属性变化自动亮起来(实测:选了相机"开始/停止"仍灰着)。
/// </summary>
private void RaiseCommands()
{
// 构造函数里 LoadRecipes() 会先设 SelectedRecipe,那时命令还没创建,必须空安全
RefreshCamerasCommand?.RaiseCanExecuteChanged();
StartStopCommand?.RaiseCanExecuteChanged();
TogglePauseCommand?.RaiseCanExecuteChanged();
ResetCommand?.RaiseCanExecuteChanged();
ApplyRecipeCommand?.RaiseCanExecuteChanged();
SnapshotCommand?.RaiseCanExecuteChanged();
EditRecipeCommand?.RaiseCanExecuteChanged();
NewRecipeCommand?.RaiseCanExecuteChanged();
}
/// <summary>
/// 采集线程:克隆一份交给渲染定时器,避免与相机的释放抢生命周期
/// </summary>
private void OnCameraFrame(CameraFrame frame)
{
lock (_frameLock)
{
if (_destroyed) return;
var clone = frame.Bgr.Clone();
var old = _pending;
_pending = clone;
old?.Dispose();
}
}
/// <summary>
/// 快照:把最近处理过的帧连同 ROI 存到 snaps/
/// </summary>
private void Snapshot()
{
var frame = _lastFrame;
if (frame is null) return;
lock (_frameLock)
{
if (_pending is null) return;
var dir = Path.Combine(AppContext.BaseDirectory, "snaps");
Directory.CreateDirectory(dir);
var path = Path.Combine(dir, $"{frame.FrameId}_{frame.Timestamp:HHmmss_fff}.png");
Cv2.ImWrite(path, _pending);
Log("info", $"快照已存:{path}");
}
}
/// <inheritdoc />
public override void Destroy()
{
_renderTimer.Stop();
_camera.FrameArrived -= OnCameraFrame;
lock (_frameLock)
{
_destroyed = true;
_pending?.Dispose();
_pending = null;
}
// 相机与推理管线是应用级单例,由 App.OnExit 按顺序统一释放。
base.Destroy();
}
/// <summary>
/// 扫描 configs/sop/*.yaml
/// </summary>
private void LoadRecipes()
{
if (!Directory.Exists(RecipeDirectory)) return;
foreach (var file in Directory.GetFiles(RecipeDirectory, "*.yaml").OrderBy(f => f))
Recipes.Add(Path.GetFileName(file));
if (Recipes.Count > 0) SelectedRecipe = Recipes[0];
}
/// <summary>
/// 编辑器保存后:重扫目录(新建的文件要能选到),选中刚存的那个,再重新应用一次
/// </summary>
private void RefreshRecipes(string fileName)
{
Recipes.Clear();
if (Directory.Exists(RecipeDirectory))
foreach (var file in Directory.GetFiles(RecipeDirectory, "*.yaml").OrderBy(f => f))
Recipes.Add(Path.GetFileName(file));
var pick = Recipes.Contains(fileName) ? fileName : Recipes.FirstOrDefault();
if (pick is not null) SelectedRecipe = pick;
ApplyRecipe();
}
/// <summary>
/// 编辑当前选中的配方
/// </summary>
private void EditRecipe()
{
var path = Path.Combine(RecipeDirectory, SelectedRecipe!);
if (!File.Exists(path))
{
Log("warn", $"配方不存在:{path}");
return;
}
// 编辑器读的是这个已解析的 config(含校验提醒),保存时再整体映射回去
OpenEditor(path, false, SopConfigLoader.Load(path));
}
/// <summary>
/// 新建配方(空白配方,文件名在编辑器里填)
/// </summary>
private void NewRecipe()
{
OpenEditor("", true, new SopConfig());
}
/// <summary>
/// 弹出配方编辑器。每次保存成功后刷新配方列表,编辑窗口保持打开。
/// </summary>
private void OpenEditor(string path, bool isNew, SopConfig config)
{
var parameters = new DialogParameters();
parameters.Add("directory", RecipeDirectory);
parameters.Add("path", path);
parameters.Add("new", isNew);
parameters.Add("config", config);
parameters.Add("onSaved", new Action<string>(fileName =>
_dispatcher.BeginInvoke(() => RefreshRecipes(fileName))));
parameters.Add("cameraService", _camera);
if (SelectedCamera is not null) parameters.Add("cameraInfo", SelectedCamera);
if (Frame is BitmapSource image)
{
var preview = image.Clone();
preview.Freeze();
parameters.Add("preview", preview);
}
_dialogs.ShowDialog(EditorDialogName, parameters, _ => { });
}
private void LoadLastCamera()
{
try
{
if (File.Exists(LastCameraPath))
_lastUsedCamera = JsonSerializer.Deserialize<CameraInfo>(File.ReadAllText(LastCameraPath));
}
catch (Exception ex)
{
Log("warn", $"读取上次使用的相机失败:{ex.Message}");
}
}
private void RememberCamera(CameraInfo camera)
{
_lastUsedCamera = camera;
try
{
Directory.CreateDirectory(Path.GetDirectoryName(LastCameraPath)!);
File.WriteAllText(LastCameraPath, JsonSerializer.Serialize(camera));
}
catch (Exception ex)
{
Log("warn", $"保存上次使用的相机失败:{ex.Message}");
}
}
private async Task RefreshCamerasAsync()
{
if (_destroyed || !CanSelectCamera) return;
SetCameraBusy(true);
try
{
var previous = SelectedCamera ?? _lastUsedCamera;
SelectedCamera = null;
Cameras.Clear();
var cameras = await _camera.EnumerateAsync();
if (_destroyed) return;
foreach (var info in cameras)
Cameras.Add(info);
if (Cameras.Count == 0)
{
Log("warn", "没有枚举到相机(支持 UVC、海康 GigE/USB 工业相机)");
return;
}
SelectedCamera = Cameras.FirstOrDefault(c => c.Kind == previous?.Kind &&
(c.Kind == CameraKind.Hikvision ? c.SerialNumber == previous.SerialNumber : c.Index == previous.Index))
?? Cameras[0];
Log("info", $"枚举到 {Cameras.Count} 个相机");
}
catch (Exception ex)
{
Log("warn", $"刷新相机失败:{ex.Message}");
}
finally { SetCameraBusy(false); }
}
private async Task StartStopAsync()
{
if (_isCameraBusy) return;
SetCameraBusy(true);
try { await StartStopCoreAsync(); }
catch (Exception ex)
{
await Task.Run(_camera.Disconnect);
IsRunning = false;
StatusText = "启动失败";
Log("warn", $"相机操作失败:{ex.Message}");
}
finally { SetCameraBusy(false); }
}
private async Task StartStopCoreAsync()
{
if (IsRunning)
{
await Task.Run(() =>
{
_pipeline.Stop();
// Recording opens its own capture session; stopping SOP must release the device.
_camera.Disconnect();
});
IsRunning = false;
StatusText = "已停止";
return;
}
if (SelectedCamera is null)
{
Log("warn", "先选相机");
return;
}
if (string.IsNullOrWhiteSpace(SelectedRecipe))
{
Log("warn", "先选配方");
return;
}
if (!await _camera.ConnectAsync(SelectedCamera)) return;
ApplyRecipe();
if (_engine.Config.Sop.Settings.ExposureTimeUs is { } exposure)
{
try
{
if (!double.IsFinite(exposure) || exposure <= 0)
throw new InvalidOperationException("相机曝光必须大于 0(微秒),或留空保留相机设置");
await _camera.SetExposureTimeAsync(exposure);
}
catch (Exception ex)
{
Log("error", "设置相机曝光失败:" + ex.Message);
await Task.Run(_camera.Disconnect);
StatusText = "设置相机曝光失败";
return;
}
}
// 阈值 / 抽帧从界面参数覆盖配方默认值
_pipeline.SetThresholds((float)Confidence, 0.45f);
_engine.Config.Sop.Settings.FrameStride = Math.Max(1, FrameStride);
if (!await _pipeline.StartAsync())
{
await Task.Run(_camera.Disconnect);
Log("warn", "采集启动失败");
return;
}
_engine.Start();
IsRunning = true;
RememberCamera(SelectedCamera);
StatusText = "运行中";
}
private void ApplyRecipe()
{
HandResult = null;
if (string.IsNullOrWhiteSpace(SelectedRecipe)) return;
var path = Path.Combine(RecipeDirectory, SelectedRecipe);
if (!File.Exists(path))
{
Log("warn", $"配方不存在:{path}");
return;
}
var config = SopConfigLoader.Load(path);
_engine.Load(config);
// 模型:配方写了就用配方的,没写就跳过(只有手部/计时类条件能工作)
var options = new PipelineOptions
{
YoloModelPath = ResolveModel(config.Sop.Model?.Path),
YoloClasses = config.Sop.Model?.Classes ?? [],
YoloInputSize = config.Sop.Model?.InputSize ?? 640,
// 文件名必须和 models/ 下实际一致,否则 ResolveModel 返回 null、手部链路静默不跑
PalmModelPath = ResolveModel("models/palm_detection_full_Nx3x192x192_post.onnx"),
LandmarkModelPath = ResolveModel("models/hand_landmark_sparse_Nx3x224x224.onnx"),
FrameStride = Math.Max(1, config.Sop.Settings.FrameStride),
};
_pipeline.LoadModels(options);
Log("info", $"推理设备:手部={_pipeline.HandBackend},YOLO={_pipeline.YoloBackend}");
StepCards.Clear();
Rois.Clear();
foreach (var step in config.Sop.Steps.OrderBy(s => s.Id))
StepCards.Add(new StepCard { StepId = step.Id, Name = step.Name, Message = "—" });
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 });
foreach (var warning in config.Warnings)
Log("warn", warning);
Log("info", $"配方已加载:{config.Sop.Name}({StepCards.Count} 步 / {Rois.Count} 区域)");
foreach (var warning in _pipeline.Warnings)
Log("warn", warning);
if (options.PalmModelPath is null || options.LandmarkModelPath is null)
Log("warn", "手部模型缺失,手部检测及画面标记不可用,请检查 models 目录中的 palm / landmark ONNX 文件");
}
/// <summary>
/// 模型路径解析:相对程序目录。不存在返回 null(管线会跳过并记警告)。
/// </summary>
private static string? ResolveModel(string? relative)
{
if (string.IsNullOrWhiteSpace(relative)) return null;
var path = Path.IsPathRooted(relative) ? relative : Path.Combine(AppContext.BaseDirectory, relative);
return File.Exists(path) ? path : null;
}
private void OnResult(FrameResult result)
{
if (_destroyed || !IsRunning) return;
lock (_frameLock)
{
_lastFrame = result;
}
_engine.ProcessFrame(result);
// 每帧均更新,无检测结果时清除上一帧的手部标记和目标框。
HandResult = result;
InferenceText = $"{result.InferenceMs:F1} ms";
}
/// <summary>
/// 渲染定时器:取采集线程留下的最新帧
/// </summary>
private void RenderFrame()
{
Mat? src;
lock (_frameLock)
{
src = _pending;
_pending = null;
}
if (src is null) return;
_frameCount++;
using (src)
{
if (_bitmap is null || _bitmap.PixelWidth != src.Width || _bitmap.PixelHeight != src.Height)
{
_bitmap = new WriteableBitmap(src.Cols, src.Rows, 96, 96, PixelFormats.Bgr24, null);
// ROI 覆盖层的坐标系就是帧像素坐标系,所以内层 Grid 尺寸必须跟着帧走
FrameWidth = src.Cols;
FrameHeight = src.Rows;
if (HandResult?.Size != (src.Cols, src.Rows)) HandResult = null;
}
var bytes = new byte[src.Rows * src.Cols * src.Channels()];
Marshal.Copy(src.Data, bytes, 0, bytes.Length);
// Mat.Step 是方法不是属性;这里按行字节数显式算,别依赖 Mat 的内部 stride
var stride = src.Cols * src.ElemSize();
// 注意:rect 是 (宽, 高),OpenCvSharp 的 Rows/Cols 是 (高, 宽),别写反
_bitmap.WritePixels(new Avalonia.PixelRect(0, 0, src.Cols, src.Rows), bytes, stride, 0);
}
Frame = _bitmap;
// 帧率:这 40ms 里处理了几帧
var delta = _frameCount - _lastTickCount;
_lastTickCount = _frameCount;
FpsText = $"{delta * 25.0:F1} fps(渲染)";
}
private void UpdateCard(StepSnapshot snapshot)
{
var card = StepCards.FirstOrDefault(c => c.StepId == snapshot.StepId);
if (card is null) return;
card.IsCurrent = snapshot.IsCurrent;
card.IsMet = snapshot.IsMet;
card.Message = snapshot.Message;
}
private void AppendViolation(ViolationEvent violation)
{
Violations.Insert(0, new ViolationItem
{
Time = violation.At,
StepId = violation.StepId,
Type = violation.Type,
Message = violation.Message,
});
while (Violations.Count > MaxTopViolations)
Violations.RemoveAt(Violations.Count - 1);
}
private void AppendLog(LogEntry entry)
{
Logs.Add(new LogItem { Time = entry.At, Level = entry.Level, Message = entry.Message });
while (Logs.Count > MaxLogLines)
Logs.RemoveAt(0);
}
private void Log(string level, string message)
{
AppendLog(new LogEntry { Level = level, Message = message });
}
}
/// <summary>
/// 步骤卡数据
/// </summary>
public class StepCard : ViewModelBase
{
private bool _isCurrent;
private bool _isMet;
private string _message = "";
/// <summary>步骤 Id</summary>
public int StepId { get; set; }
/// <summary>步骤名</summary>
public string Name { get; set; } = "";
/// <summary>当前步骤</summary>
public bool IsCurrent
{
get { return _isCurrent; }
set { SetProperty(ref _isCurrent, value); }
}
/// <summary>已完成</summary>
public bool IsMet
{
get { return _isMet; }
set { SetProperty(ref _isMet, value); }
}
/// <summary>判定说明</summary>
public string Message
{
get { return _message; }
set { SetProperty(ref _message, value); }
}
}
/// <summary>
/// Top3 违规条目
/// </summary>
public class ViolationItem
{
/// <summary>时刻</summary>
public DateTime Time { get; set; }
/// <summary>步骤 Id</summary>
public int StepId { get; set; }
/// <summary>类型</summary>
public string Type { get; set; } = "";
/// <summary>文案</summary>
public string Message { get; set; } = "";
}
/// <summary>
/// 日志条目
/// </summary>
public class LogItem
{
/// <summary>时刻</summary>
public DateTime Time { get; set; }
/// <summary>级别 info/warn/viol</summary>
public string Level { get; set; } = "info";
/// <summary>文案</summary>
public string Message { get; set; } = "";
}
/// <summary>
/// ROI 覆盖层条目(坐标 = 配方像素坐标,外层 Viewbox 负责缩放)
/// </summary>
public class RoiItem
{
/// <summary>区域名</summary>
public string Name { get; set; } = "";
/// <summary>X</summary>
public double X { get; set; }
/// <summary>Y</summary>
public double Y { get; set; }
/// <summary>W</summary>
public double W { get; set; }
/// <summary>H</summary>
public double H { get; set; }
/// <summary>颜色(#RRGGBB)。不叫 Color——会和 Avalonia.Media.Color 撞名</summary>
public string ColorHex { get; set; } = "#4CAF50";
/// <summary>画刷</summary>
public SolidColorBrush Brush => new((Avalonia.Media.Color)Color.Parse(ColorHex));
}

View File

@ -0,0 +1,28 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using MvCameraControl;
namespace SopHelper.Engine.Camera;
internal static class MvsNativeBindings
{
// The managed SDK's acquisition APIs import MvCameraControl.dll by name. On
// Linux bind those same calls to the MVS C runtime; no application/UI fork.
[ModuleInitializer]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Usage","CA2255",Justification="This application-owned adapter must install the SDK resolver before its first P/Invoke.")]
internal static void Initialize()
{
if(!OperatingSystem.IsWindows())NativeLibrary.SetDllImportResolver(typeof(SDKSystem).Assembly,Resolve);
}
private static IntPtr Resolve(string name,Assembly assembly,DllImportSearchPath? searchPath)
{
if(name!="MvCameraControl.dll")return IntPtr.Zero;
var configured=Environment.GetEnvironmentVariable("MVS_LIB_DIR");
var candidates=new List<string>();
if(!string.IsNullOrWhiteSpace(configured))candidates.Add(Path.Combine(configured,"libMvCameraControl.so"));
candidates.AddRange(["/opt/MVS/lib/64/libMvCameraControl.so","/opt/MVS/lib/aarch64/libMvCameraControl.so","libMvCameraControl.so"]);
foreach(var candidate in candidates)if(NativeLibrary.TryLoad(candidate,out var handle))return handle;
throw new DllNotFoundException("未找到 Linux MVS 原生运行库。请安装与托管 SDK 匹配的 MVS,并设置 MVS_LIB_DIR 及 LD_LIBRARY_PATH。");
}
}

View File

@ -21,4 +21,8 @@
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.23.0" Condition="'$(NativePlatform)' == 'Linux'" /> <PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.23.0" Condition="'$(NativePlatform)' == 'Linux'" />
<PackageReference Include="YamlDotNet" Version="16.3.0" /> <PackageReference Include="YamlDotNet" Version="16.3.0" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition="'$(NativePlatform)' == 'Windows'">
<None Include="../../libs/cuda/*.dll" Link="%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
<None Include="../../libs/cuda/LICENSE*" Link="licenses/cudnn/%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../src/SopHelper.Avalonia/SopHelper.Avalonia.csproj" />
<PackageReference Include="Avalonia.Headless" Version="11.3.22" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,166 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Headless;
using Avalonia.Media.Imaging;
using Avalonia.Threading;
using Prism.Ioc;
using Prism.Dialogs;
using SopHelper;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Training;
using SopHelper.Models;
using SopHelper.Training;
using SopHelper.VVMs.SopPage;
using SopHelper.VVMs.RecipeEditor;
using System.Text.Json;
using Avalonia.VisualTree;
using OpenCvSharp;
using Window = Avalonia.Controls.Window;
using Point = Avalonia.Point;
using Size = Avalonia.Size;
using Avalonia.Input;
internal static class Smoke
{
private static int _exit=1;
private static readonly FakeCamera Camera=new();
[STAThread]
public static int Main()
{
var settingsPath=Path.GetFullPath("workspace/settings.json");
var settingsBefore=File.Exists(settingsPath)?File.ReadAllBytes(settingsPath):null;
System.Diagnostics.Trace.Listeners.Add(new System.Diagnostics.ConsoleTraceListener());
Environment.SetEnvironmentVariable("SOPHELPER_CPU_THREADS","4");
try
{
AppBuilder.Configure(()=>new App(Camera)).UseSkia()
.UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing=false })
.LogToTrace(Avalonia.Logging.LogEventLevel.Warning)
.AfterSetup(_=>
{
var lifetime=(IClassicDesktopStyleApplicationLifetime)Application.Current!.ApplicationLifetime!;
lifetime.Startup+=(_,_)=>Dispatcher.UIThread.Post(async()=>await Run(lifetime));
}).StartWithClassicDesktopLifetime([],ShutdownMode.OnExplicitShutdown);
}
finally
{
if(settingsBefore is not null)File.WriteAllBytes(settingsPath,settingsBefore);
else if(File.Exists(settingsPath))File.Delete(settingsPath);
}
return _exit;
}
private static async Task Run(IClassicDesktopStyleApplicationLifetime lifetime)
{
try
{
await Task.Delay(150);
var app=(App)Application.Current!;var window=lifetime.MainWindow!;
var navigation=app.Container.Resolve<NavigationModel>();
Check(navigation.Pages.Count==2,"Both original navigation pages registered");
Check(navigation.Pages[0].DisplayName=="SOP 辅助"&&navigation.Pages[1].DisplayName=="零件标注与训练","Original navigation labels retained");
window.WindowState=WindowState.Normal;window.Width=1180;window.Height=820;
await Task.Delay(150);
var sop=app.Container.Resolve<SopPageViewModel>();
sop.ApplyRecipeCommand.Execute();
Check(sop.StepCards.Count==4&&sop.Rois.Count==3,"Original SOP recipe creates four steps and three ROIs");
sop.StartStopCommand.Execute();
for(var i=0;i<100&&!sop.IsRunning;i++)await Task.Delay(20);
Check(sop.IsRunning,"Original start command connects the shared camera/pipeline");
await Task.Run(()=>{Camera.Emit();Camera.Emit();});
await Task.Delay(150);
Check(sop.Frame is not null&&sop.FrameWidth==640&&sop.FrameHeight==480,"Camera buffer renders through the shared Avalonia bitmap adapter");
Save(window,"sop");
sop.StartStopCommand.Execute();for(var i=0;i<100&&sop.IsRunning;i++)await Task.Delay(20);
Check(!sop.IsRunning&&!Camera.IsConnected,"Stop command releases acquisition");
Check(window.GetVisualDescendants().OfType<SopPage>().Any(),"SOP page navigates");
sop.EditRecipeCommand.Execute();await Task.Delay(150);
var modal=lifetime.Windows.OfType<RecipeDialogWindow>().Single();
Check(modal.Width==1040&&modal.Height==760&&modal.DataContext is RecipeEditorViewModel,"Original edit command opens the sized Prism recipe dialog");
((RecipeEditorViewModel)modal.DataContext!).CloseCommand.Execute();await Task.Delay(80);
Check(!lifetime.Windows.Contains(modal),"Recipe close command respects the Prism dialog lifecycle");
navigation.SelectedIndex=1;await Task.Delay(150);Save(window,"training");
Check(window.GetVisualDescendants().OfType<TrainingPage>().Any(),"Training page navigates");
var trainer=app.Container.Resolve<SopHelper.Training.MainViewModel>();
var temporary=Path.Combine(Path.GetTempPath(),"sophelper-avalonia-project-"+Guid.NewGuid().ToString("N"));Directory.CreateDirectory(temporary);
using(var trainingFrame=new Mat(480,640,MatType.CV_8UC3,new Scalar(30,60,90)))Cv2.ImWrite(Path.Combine(temporary,"frame.png"),trainingFrame);
var project=new TrainingProject { FilePath=Path.Combine(temporary,"project.json"),Name="测试零件",Width=640,Height=480,
Frames=[new FrameAnnotation {Index=0,Image="frame.png",Status="unlabeled"}] };
project.Save();trainer.Load(project.FilePath);trainer.DrawBox([10,20,100,200]);trainer.ApproveCommand.Execute();
Check(TrainingProject.Load(project.FilePath).Frames[0].Status=="reviewed","Training annotation and review still save the original project format");
navigation.SelectedIndex=0;navigation.SelectedIndex=1;await Task.Delay(80);
Check(ReferenceEquals(trainer,app.Container.Resolve<SopHelper.Training.MainViewModel>())&&trainer.SelectedFrame?.Box is { Length:4 },"Navigation preserves the training project and annotation state");
Save(window,"training-project");
trainer.DoctorCommand.Execute();
for(var i=0;i<300&&trainer.IsBusy;i++)await Task.Delay(100);
Check(!trainer.IsBusy&&trainer.Progress==100&&trainer.Logs.Contains("Python ")&&trainer.Logs.Contains("PyTorch"),"Training worker command completes using the repository Python runtime");
var editorVm=new RecipeEditorViewModel();
editorVm.OnDialogOpened(new DialogParameters { {"directory",Path.Combine(AppContext.BaseDirectory,"configs","sop")},
{"config",SopHelper.Engine.Sop.SopConfigLoader.Load(Path.Combine(AppContext.BaseDirectory,"configs","sop","demo.yaml"))},
{"path",Path.Combine(AppContext.BaseDirectory,"configs","sop","demo.yaml")}, {"new",false} });
var editor=new RecipeEditor { DataContext=editorVm };
var recipeBefore=SopHelper.Engine.Sop.SopConfigLoader.ToYaml(editorVm.Recipe.ToConfig());
var dialog=new Window { Width=1180,Height=820,Content=editor };dialog.Show();await Task.Delay(100);
var tabs=editor.GetVisualDescendants().OfType<TabControl>().First();
Check(tabs.ItemCount==4,"All four original recipe tabs retained");
for(var i=0;i<tabs.ItemCount;i++){tabs.SelectedIndex=i;await Task.Delay(80);Save(dialog,"recipe-"+i);}
Check(editorVm.Recipe.Steps.Count>0,"Original recipe ViewModel loads steps");
Check(editorVm.Recipe.Steps[0].Detection?.Method=="hand_in_region","Recipe bindings preserve selected condition method");
Check(SopHelper.Engine.Sop.SopConfigLoader.ToYaml(editorVm.Recipe.ToConfig())==recipeBefore,"Opening all recipe tabs does not alter any recipe fields");
dialog.Close();editorVm.OnDialogClosed();
var recorder=new CameraWindow(new CameraViewModel(new FakeCamera(),Path.Combine(Path.GetTempPath(),"sophelper-avalonia-smoke")));
recorder.Show();await Task.Delay(100);Save(recorder,"camera");recorder.Close();
var fitted=RegionCanvas.FitImage(new Size(1000,800),new Size(1920,1080));
var pixel=RegionCanvas.ToImage(fitted.Center,fitted,new Size(1920,1080));
Check(Math.Abs(pixel.X-960)<.001&&Math.Abs(pixel.Y-540)<.001,"ROI maps letterbox center back to original pixels");
Check(RegionCanvas.PixelBounds(new Point(100,120),new Point(10,20),new Size(1920,1080))==new PixelRect(10,20,90,100),"Reverse ROI drag preserves bounds");
var pixels=new byte[]{3,17,240,29,100,31};
using(var bitmap=SopHelper.Presentation.Imaging.BitmapSource.Create(2,1,96,96,SopHelper.Presentation.Imaging.PixelFormats.Bgr24,null,pixels,6))
{
pixels[0]=255;bitmap.Save(Path.Combine(Output,"pixels.png"));
using var decoded=Cv2.ImRead(Path.Combine(Output,"pixels.png"));
Check(decoded.At<Vec3b>(0,0)==new Vec3b(3,17,240)&&decoded.At<Vec3b>(0,1)==new Vec3b(29,100,31),"Bitmap adapter owns its buffer and preserves BGR colors");
}
using(var image=SopHelper.Presentation.Imaging.BitmapSource.Create(200,100,96,96,SopHelper.Presentation.Imaging.PixelFormats.Bgr24,null,new byte[200*100*3],600))
{
var region=new RegionNode {Key="roi",X1=0,Y1=0,X2=10,Y2=10};
var canvas=new RegionCanvas {Image=image,Regions=[region],SelectedRegion=region};
var drawing=new Window {Width=400,Height=400,Content=canvas};drawing.Show();await Task.Delay(60);
drawing.MouseDown(new Point(300,250),MouseButton.Left);drawing.MouseMove(new Point(100,150));drawing.MouseUp(new Point(100,150),MouseButton.Left);
Check(region.X1==50&&region.Y1==25&&region.X2==150&&region.Y2==75,"Actual ROI pointer drag excludes image letterboxing and supports reverse drawing");
double[]? drawn=null;var annotation=new AnnotationCanvas {Source=image};annotation.BoxDrawn+=box=>drawn=box;drawing.Content=annotation;await Task.Delay(60);
drawing.MouseDown(new Point(300,250),MouseButton.Left);drawing.MouseMove(new Point(100,150));drawing.MouseUp(new Point(100,150),MouseButton.Left);
Check(drawn is {Length:4}&&drawn.SequenceEqual(new double[]{50,25,150,75}),"Actual annotation drag preserves original-image box coordinates");
drawing.Close();
}
File.WriteAllText(Path.Combine(Output,"result.json"),JsonSerializer.Serialize(new {passed=true,pages=navigation.Pages.Select(p=>p.DisplayName),recipeTabs=tabs.ItemCount}));
_exit=0;
}
catch(Exception ex){Console.Error.WriteLine(ex);}
finally{lifetime.Shutdown(_exit);}
}
private static string Output {get{var p=Path.GetFullPath("artifacts/avalonia-smoke");Directory.CreateDirectory(p);return p;}}
private static void Save(Window window,string name)
{
window.UpdateLayout();
using var image=new RenderTargetBitmap(new PixelSize((int)window.Bounds.Width,(int)window.Bounds.Height));image.Render(window);image.Save(Path.Combine(Output,name+".png"));
}
private static void Check(bool condition,string message){if(!condition)throw new Exception(message);Console.WriteLine("PASS: "+message);}
}
internal sealed class FakeCamera : ICameraService
{
public bool IsConnected{get;private set;}public bool IsGrabbing{get;private set;}
public event Action<CameraFrame>? FrameArrived;
public event Action<bool>? ConnectionChanged;
public event Action<string>? Error {add{}remove{}}
public Task<List<CameraInfo>> EnumerateAsync()=>Task.FromResult(new List<CameraInfo>{new(){Index=0,Name="测试相机"}});
public Task<bool> ConnectAsync(CameraInfo camera){IsConnected=true;ConnectionChanged?.Invoke(true);return Task.FromResult(true);}
public Task<bool> StartAsync(){IsGrabbing=true;return Task.FromResult(true);}
public void Stop(){IsGrabbing=false;}public void Disconnect(){Stop();IsConnected=false;ConnectionChanged?.Invoke(false);}public void Dispose()=>Disconnect();
private long _id;
public void Emit()
{
using var frame=new CameraFrame {FrameId=++_id,Timestamp=DateTime.Now,Bgr=new Mat(480,640,MatType.CV_8UC3,new Scalar(35,60,90))};
FrameArrived?.Invoke(frame);
}
}