将标注训练运行日志实时保存到文件并记录任务耗时

This commit is contained in:
tfarcraw 2026-11-10 14:48:53 +08:00
parent 78b83264b0
commit 56fd2194e1

View File

@ -27,6 +27,10 @@ public sealed class MainViewModel : BindableBase
private double _progress;
private string _status = "新建项目:导入视频,在任意清晰帧拖动画框";
private string _logs = "";
private readonly object _logGate = new();
private bool _logWriteWarningShown;
public string RuntimeLogPath { get; } = Path.Combine(DesktopPlatform.WorkspaceRoot, "logs",
$"training-{DateTime.Now:yyyyMMdd-HHmmss}-{Guid.NewGuid():N}.log");
private bool _isTraining;
private string _trainingStatus = "打开已复核项目后即可开始训练";
private string _trainingMetrics = "尚无训练指标";
@ -352,23 +356,47 @@ public sealed class MainViewModel : BindableBase
}
private void Append(string line)
{
var entry = $"[{DateTimeOffset.Now:yyyy-MM-dd HH:mm:ss.fff zzz}] {line}";
string? warning = null;
// Persist before dispatching to the UI; the on-screen buffer can be truncated independently.
lock (_logGate)
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(RuntimeLogPath)!);
File.AppendAllText(RuntimeLogPath, entry + Environment.NewLine, new System.Text.UTF8Encoding(false));
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
{
if (!_logWriteWarningShown)
{
_logWriteWarningShown = true;
warning = $"日志文件写入失败:{RuntimeLogPath} · {e.Message}";
}
}
}
Dispatcher.CurrentDispatcher.Invoke(() =>
{
Logs += line + Environment.NewLine;
Logs += entry + Environment.NewLine;
if (warning != null) Logs += warning + 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";
var action = JsonSerializer.SerializeToElement(request).GetProperty("action").GetString();
IsTraining = action == "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;
var elapsed = Stopwatch.StartNew();
var outcome = "失败";
try
{
Append($"任务开始:{action} · 项目:{path ?? "无"} · 日志:{RuntimeLogPath}");
SaveSettings();
if (!File.Exists(PythonPath))
throw new FileNotFoundException(DesktopPlatform.MissingPythonMessage, PythonPath);
@ -398,12 +426,13 @@ public sealed class MainViewModel : BindableBase
}
catch (Exception e) when (e is JsonException or InvalidOperationException or FormatException) { Append(line); }
}, _cancellation.Token, apiKey);
Progress = 100; return true;
outcome = "完成"; Progress = 100; return true;
}
catch (OperationCanceledException) { Status = "任务已取消;已保存的标注保留"; if (IsTraining) TrainingStatus = "训练已停止;已写入的日志与检查点保留在结果目录"; Append(Status); return false; }
catch (OperationCanceledException) { outcome = "取消"; 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
{
Append($"任务{outcome}:{action} · 耗时 {elapsed.Elapsed.TotalSeconds:F2} 秒");
if (reload && path != null)
{
try { Load(path, index); } catch (Exception e) { Append("重新读取项目失败:" + e.Message); }