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 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? 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 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.Avalonia.slnx"))) directory = directory.Parent; Root = File.Exists(Path.Combine(directory.FullName, "SopHelper.Avalonia.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 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 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(DesktopPlatform.MissingPythonMessage, 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 = "设置文件不可读,已使用默认配置"; } } }