using System.Diagnostics; using System.Text; using System.Text.Json; namespace ChaoXingAutoClass.Core.Implements.Services; public sealed class LearningController(ICourseBrowser browser, ILearningAgent agent, AppSettings settings, string sessionDirectory, TimeSpan? pollInterval = null, TimeSpan? initialMediaWait = null, ILessonTranscriber? transcriber = null, Func>? verifyChapterCompletion = null) { private readonly object _pauseLock = new(); private TaskCompletionSource? _pauseGate; private CancellationTokenSource? _stop; private int _running; private readonly List _skippedTasks = []; public IReadOnlyList SkippedTasks => _skippedTasks; public bool IsRunning => Volatile.Read(ref _running) == 1; public bool IsPaused { get { lock (_pauseLock) return _pauseGate is not null; } } public LearningStatus Status { get; private set; } = LearningStatus.Idle; public string CurrentSummary { get; private set; } = ""; public event Action? StatusChanged; public event Action? Notice; public event Action? SummaryChanged; public event Action? ChapterProgress; public event Action? PlaybackChanged; public event Action? ChapterCompleted; public event Action? TaskSkipped; public event Action>? HomeworksChanged; public event Action? HomeworkProgress; public async Task RunAsync(IReadOnlyList chapters, int startIndex = 0, CancellationToken cancellationToken = default, bool useCurrentChapter = false, bool includeHomework = false, CourseInfo? course = null, IReadOnlySet? homeworkIds = null) { if (Interlocked.CompareExchange(ref _running, 1, 0) != 0) throw new InvalidOperationException("已有学习任务正在运行。"); _stop = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var token = _stop.Token; _skippedTasks.Clear(); try { settings.Validate(); if ((chapters.Count == 0 && !includeHomework) || startIndex < 0 || (chapters.Count > 0 && startIndex >= chapters.Count)) throw new ArgumentException("请先加载并选择章节。"); if (includeHomework && (course is null || browser is not IHomeworkBrowser)) throw new ArgumentException("当前浏览器不支持课程作业。"); Directory.CreateDirectory(sessionDirectory); var courseKnowledge = new StringBuilder(); var imported = settings.CourseNotes; if (!string.IsNullOrWhiteSpace(settings.TranscriptPath)) { var info = new FileInfo(settings.TranscriptPath); if (!info.Exists || info.Length > 8 * 1024 * 1024) throw new InvalidOperationException("字幕文件不存在或超过 8 MiB。"); imported += "\n导入字幕:\n" + await File.ReadAllTextAsync(info.FullName, token); } for (var index = startIndex; index < chapters.Count; index++) { await CheckpointAsync(token); var chapter = chapters[index]; ChapterProgress?.Invoke(index + 1, chapters.Count, chapter.Title); if (chapter.Completed) { Log("info", "站点显示本节任务已完成,跳过。", chapter.Title); continue; } var directory = Path.Combine(sessionDirectory, $"{index + 1:D3}-{SafeName(chapter.Id)}"); try { Directory.CreateDirectory(directory); courseKnowledge.AppendLine(await RunChapterAsync(chapter, directory, imported, useCurrentChapter && index == startIndex, token)); } catch (Exception error) when (!token.IsCancellationRequested) { await RecordSkipAsync("Chapter", chapter.Id, chapter.Title, error.Message, token); } } if (includeHomework) { try { await RunHomeworksAsync((IHomeworkBrowser)browser, course!, Limit(courseKnowledge.ToString(), 60000), homeworkIds, token); } catch (Exception error) when (!token.IsCancellationRequested) { await RecordSkipAsync("HomeworkCatalog", course!.Id, course.Title + " / 作业列表", error.Message, token); } } await CheckpointAsync(token); SetStatus(LearningStatus.Completed); Log("info", $"本轮队列已结束,跳过 {_skippedTasks.Count} 项;勾选状态以站点确认为准。"); } catch (OperationCanceledException) when (token.IsCancellationRequested) { SetStatus(LearningStatus.Stopped); Log("info", "学习任务已停止。"); } catch (Exception error) { SetStatus(LearningStatus.Failed); Log("error", error.Message); } finally { _stop.Cancel(); await PauseMediaAsync(); Resume(); _stop.Dispose(); _stop = null; Volatile.Write(ref _running, 0); } } private async Task RunChapterAsync(ChapterInfo chapter, string directory, string imported, bool useCurrentChapter, CancellationToken runToken) { using var chapterStop = CancellationTokenSource.CreateLinkedTokenSource(runToken); var token = chapterStop.Token; var transcriptions = new Dictionary>(); var attemptedPapers = new HashSet(StringComparer.Ordinal); try { SetStatus(LearningStatus.Running); Log("info", "进入章节,等待播放器和任务加载。", chapter.Title); if (!useCurrentChapter) await browser.OpenChapterAsync(chapter, token); CurrentSummary = ""; var captions = new StringBuilder(imported); var seenCaptions = new HashSet(StringComparer.Ordinal); var pendingFrames = new List(); var lastCapture = new Dictionary(); var lastTime = -1d; var lastVideo = ""; var noProgress = Stopwatch.StartNew(); var loadWait = Stopwatch.StartNew(); var observedVideo = false; var documents = browser is ILessonDocumentBrowser documentReader ? await documentReader.GetDocumentsAsync(token) : []; var documentPages = 0; var mergedTranscriptions = new HashSet(); async Task MergeAudioAsync(bool waitForAll) { foreach (var entry in transcriptions) { if (mergedTranscriptions.Contains(entry.Key) || (!waitForAll && !entry.Value.IsCompleted)) continue; var transcript = await entry.Value; captions.AppendLine("\n视频音轨自动转写(可能存在识别误差):\n" + transcript.Text); mergedTranscriptions.Add(entry.Key); Log("success", $"音轨已合并:{transcript.Segments.Length} 段带时间戳语音。", chapter.Title); } } while (true) { await CheckpointAsync(token); if (await browser.GetBlockerAsync(token) is { } blocker) throw new AttentionException(blocker); var videos = await browser.GetVideosAsync(token); if (videos.Count == 0) { if (observedVideo) throw new AttentionException("播放页面发生变化,视频在完成前消失,请查看站点提示。"); if (!observedVideo && documents.Count == 0 && loadWait.Elapsed < (initialMediaWait ?? TimeSpan.FromSeconds(20))) { await WaitAsync(token); continue; } break; } observedVideo = true; if (settings.TranscriptionEnabled && transcriber is not null) foreach (var item in videos) if (!transcriptions.ContainsKey(item.Key)) { Log("info", "正在后台下载媒体并提取、转写音轨,视频继续正常播放。", chapter.Title); var task = Task.Run(() => transcriber.TranscribeAsync(item, Path.Combine(directory, "audio-" + SafeName(item.Key)), token), token); transcriptions[item.Key] = task; } await MergeAudioAsync(false); var video = videos.FirstOrDefault(video => !video.Finished); if (video is null) { var ended = videos.Last(); PlaybackChanged?.Invoke(new(chapter.Title, ended.CurrentTime, ended.Duration, ended.Ended, ended.ServerCompleted)); break; } PlaybackChanged?.Invoke(new(chapter.Title, video.CurrentTime, video.Duration, false)); if (video.Key != lastVideo) { lastVideo = video.Key; lastTime = -1; noProgress.Restart(); } if (video.CurrentTime > lastTime + .2) { lastTime = video.CurrentTime; noProgress.Restart(); } if (noProgress.Elapsed > TimeSpan.FromSeconds(settings.StallTimeoutSeconds)) throw new AttentionException("视频长时间未前进,请检查网络、验证码或播放器提示。"); if (video.Paused) { var inline = await browser.GetQuestionsAsync(directory, true, token); if (inline.Count > 0) { await SummarizePendingAsync(chapter.Title, captions.ToString(), pendingFrames, token); await AnswerQuestionsAsync(chapter.Title, CurrentSummary + "\n" + captions, inline, directory, attemptedPapers, token); noProgress.Restart(); } await CheckpointAsync(token); await browser.PlayAsync(video, settings.Muted, token); } var caption = await browser.ReadCaptionsAsync(token); if (!string.IsNullOrWhiteSpace(caption) && seenCaptions.Add(caption)) captions.AppendLine($"[{TimeSpan.FromSeconds(video.CurrentTime):hh\\:mm\\:ss}] {caption}"); if (settings.VisionEnabled && video.CurrentTime > .25 && (!lastCapture.TryGetValue(video.Key, out var previous) || video.CurrentTime - previous >= settings.FrameIntervalSeconds)) { var frame = await browser.CaptureVideoAsync(video, directory, token); if (frame is not null) pendingFrames.Add(frame); lastCapture[video.Key] = video.CurrentTime; } if (pendingFrames.Count >= settings.FramesPerAnalysis) await SummarizePendingAsync(chapter.Title, captions.ToString(), pendingFrames, token); await WaitAsync(token); } if (transcriptions.Count > 0) { SetStatus(LearningStatus.Transcribing); await MergeAudioAsync(true); } await SummarizePendingAsync(chapter.Title, captions.ToString(), pendingFrames, token, transcriptions.Count > 0); if (browser is ILessonDocumentBrowser reader) { documents = await reader.GetDocumentsAsync(token); if (documents.Count > 0 && !settings.VisionEnabled) throw new AttentionException("本章包含图片课件,需要在设置中启用视觉分析后继续。"); foreach (var document in documents) { if (document.PageCount > 300) throw new AttentionException("课件超过 300 页,已保留待检查。"); Log("info", $"正在逐页读取课件《{document.Title}》,共 {document.PageCount} 页。", chapter.Title); var pages = new List(); for (var page = 1; page <= document.PageCount; page++) { await CheckpointAsync(token); pages.Add(await reader.ReadDocumentPageAsync(document, page, directory, token)); documentPages++; if (pages.Count >= settings.FramesPerAnalysis || page == document.PageCount) { SetStatus(LearningStatus.Analyzing); CurrentSummary = await agent.SummarizeAsync(chapter.Title + " / 课件", CurrentSummary, captions.ToString(), pages.ToArray(), token); pages.Clear(); SummaryChanged?.Invoke(CurrentSummary); Log("info", $"课件已分析 {page} / {document.PageCount} 页。", chapter.Title); SetStatus(LearningStatus.Running); } } } } if (observedVideo && seenCaptions.Count == 0 && transcriptions.Count == 0) Log("info", "此视频没有可读字幕;内容分析使用播放画面和已导入的笔记/字幕,未转写音轨。", chapter.Title); await CheckpointAsync(token); var questions = await browser.GetQuestionsAsync(directory, false, token); await File.WriteAllTextAsync(Path.Combine(directory, "questions.json"), JsonSerializer.Serialize(questions), token); if (!observedVideo && documentPages == 0 && questions.Count == 0) throw new AttentionException("本节没有识别到视频或待答题目,保留实际未完成状态。"); QuizSubmission? quizResult = null; if (questions.Count > 0) quizResult = await AnswerQuestionsAsync(chapter.Title, CurrentSummary + "\n" + captions, questions, directory, attemptedPapers, token); await File.WriteAllTextAsync(Path.Combine(directory, "lesson-notes.txt"), CurrentSummary + "\n\n" + captions, token); await File.WriteAllTextAsync(Path.Combine(directory, "result.json"), JsonSerializer.Serialize(new { chapter.Id, chapter.Title, ProcessedAt = DateTimeOffset.Now, ObservedVideo = observedVideo, DocumentPages = documentPages, QuestionCount = questions.Count, Note = "实际播放及可识别任务的本地处理记录;站点学习进度以站点返回为准。", QuizConfirmed = quizResult?.Confirmed, QuizScore = quizResult?.Score }, new JsonSerializerOptions { WriteIndented = true }), token); if (verifyChapterCompletion is not null && !await verifyChapterCompletion(chapter, token)) throw new AttentionException("视频和题目已处理,但站点尚未确认本章全部任务完成,保留实际未完成状态。"); ChapterCompleted?.Invoke(chapter with { Completed = true }); Log("success", "本节视频、课件及可识别题目处理结束。", chapter.Title); return chapter.Title + "\n" + CurrentSummary + "\n" + captions; } finally { chapterStop.Cancel(); var pending = Task.WhenAll(transcriptions.Values); // Observe late failures even if a transcription backend does not promptly honor cancellation. _ = pending.ContinueWith(task => { _ = task.Exception; }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); try { await pending.WaitAsync(TimeSpan.FromSeconds(5)); } catch { } await PauseMediaAsync(); } } private async Task PauseMediaAsync() { using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); try { await browser.PauseAllAsync(timeout.Token).WaitAsync(timeout.Token); } catch { } } private async Task RecordSkipAsync(string kind, string id, string title, string reason, CancellationToken token) { token.ThrowIfCancellationRequested(); var skipped = new LearningTaskSkip(kind, id, title, reason, DateTimeOffset.Now); _skippedTasks.Add(skipped); Log("warning", $"已跳过当前{(kind == "Chapter" ? "章节" : kind == "Homework" ? "作业" : "作业列表")},继续下一项。原因:{reason}", title); TaskSkipped?.Invoke(skipped); await WriteReportAsync("task-skips.json", _skippedTasks, token); } private async Task WriteReportAsync(string name, object value, CancellationToken token) { try { await File.WriteAllTextAsync(Path.Combine(sessionDirectory, name), JsonSerializer.Serialize(value, new JsonSerializerOptions { WriteIndented = true }), token); } catch (Exception error) when (!token.IsCancellationRequested) { Log("warning", "处理记录写入失败,继续队列:" + error.Message); } } private async Task RunHomeworksAsync(IHomeworkBrowser homeworkBrowser, CourseInfo course, string knowledge, IReadOnlySet? ids, CancellationToken token) { await CheckpointAsync(token); var homeworks = await homeworkBrowser.GetHomeworksAsync(course, token); HomeworksChanged?.Invoke(homeworks); var pending = homeworks.Where(h => !h.Completed && h.Available && (ids is null || ids.Contains(h.Id))).DistinctBy(h => h.Id).ToArray(); var results = new List(); Log("info", $"读取作业 {homeworks.Count} 份,开放且未提交 {pending.Length} 份。", course.Title); for (var index = 0; index < pending.Length; index++) { await CheckpointAsync(token); var homework = pending[index]; if (homeworks.Any(h => h.Id == homework.Id && h.Completed)) continue; HomeworkProgress?.Invoke(index + 1, pending.Length, homework.Title); var directory = Path.Combine(sessionDirectory, "Homework-" + SafeName(homework.Id)); try { Directory.CreateDirectory(directory); SetStatus(LearningStatus.Answering); await homeworkBrowser.OpenHomeworkAsync(homework, token); if (await browser.GetBlockerAsync(token) is { } blocker) throw new AttentionException(blocker); var questions = await browser.GetQuestionsAsync(directory, false, token); await File.WriteAllTextAsync(Path.Combine(directory, "questions.json"), JsonSerializer.Serialize(questions), token); if (questions.Count == 0 || questions.Any(q => q.Kind is not (QuestionKind.Single or QuestionKind.Multiple or QuestionKind.TrueFalse))) throw new AttentionException("该作业包含无法自动选择的题型或附件任务,保留实际未提交状态。"); var submission = await AnswerQuestionsAsync(course.Title + " / 作业:" + homework.Title, knowledge, questions, directory, new HashSet(StringComparer.Ordinal), token); var refreshed = await homeworkBrowser.GetHomeworksAsync(course, token); homeworks = refreshed; HomeworksChanged?.Invoke(refreshed); if (!refreshed.Any(h => h.Id == homework.Id && h.Completed)) throw new AttentionException("页面显示提交成功,但作业列表尚未确认,本轮不再重复提交。"); results.Add(new { homework.Id, homework.Title, submission.Confirmed, submission.Score, Status = "Submitted" }); Log("success", "作业列表已确认提交。", homework.Title); } catch (Exception error) when (!token.IsCancellationRequested) { results.Add(new { homework.Id, homework.Title, Confirmed = false, Status = "Skipped", error.Message }); await RecordSkipAsync("Homework", homework.Id, homework.Title, error.Message, token); } await WriteReportAsync("homework-results.json", results, token); } } private async Task SummarizePendingAsync(string chapter, string transcript, List frames, CancellationToken token, bool includeAudio = false) { if (frames.Count == 0 && !includeAudio) return; await CheckpointAsync(token); SetStatus(LearningStatus.Analyzing); CurrentSummary = await agent.SummarizeAsync(chapter, CurrentSummary, Limit(transcript, 40000), frames.ToArray(), token); frames.Clear(); SummaryChanged?.Invoke(CurrentSummary); Log("info", includeAudio ? "已结合音轨转写更新课程内容分析。" : "已分析一批视频画面并更新课程笔记。", chapter); SetStatus(LearningStatus.Running); } private async Task AnswerQuestionsAsync(string chapter, string knowledge, IReadOnlyList questions, string directory, HashSet attemptedPapers, CancellationToken token) { var signature = JsonSerializer.Serialize(questions.Select(q => q.Id).Order(StringComparer.Ordinal)); if (!attemptedPapers.Add(signature)) throw new AttentionException("本任务的同一组题目已处理过,本轮不再重复调用 AI 或提交。"); if (!settings.AutoAnswer) throw new AttentionException("本节包含题目,自动答题已关闭。"); await CheckpointAsync(token); SetStatus(LearningStatus.Answering); var batches = new List(); knowledge = Limit(knowledge, 60000); if (agent is IPaperLearningAgent paperAgent) await paperAgent.PrepareQuestionsAsync(chapter, knowledge, questions, token); var batchIndex = 0; var batchCount = (questions.Count + QuestionBatching.MaximumQuestions - 1) / QuestionBatching.MaximumQuestions; foreach (var batch in questions.Chunk(QuestionBatching.MaximumQuestions)) { await CheckpointAsync(token); Log("info", $"正在分析第 {++batchIndex} / {batchCount} 批题目(本批 {batch.Length} 题,共 {questions.Count} 题)。", chapter); var answerSet = await agent.AnswerAsync(chapter, knowledge, batch, token); batches.Add(answerSet); if ((settings.StopOnUncertainAnswers ? AnswerValidator.Validate(batch, answerSet.Answers, settings.MinimumConfidence) : AnswerValidator.ValidateStructure(batch, answerSet.Answers)) is { } batchError) { await File.WriteAllTextAsync(Path.Combine(directory, $"answers-blocked-{Guid.NewGuid():N}.json"), JsonSerializer.Serialize(answerSet, new JsonSerializerOptions { NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowNamedFloatingPointLiterals }), token); throw new AttentionException(batchError + " 答案已保存在本地供检查。"); } foreach (var warning in (answerSet.Warnings ?? []).Concat(AnswerValidator.GetUncertaintyWarnings(answerSet.Answers, settings.MinimumConfidence)).Distinct()) Log("warning", warning + " 已按设置继续填写与提交。", chapter); Log("info", $"第 {batchIndex} / {batchCount} 批答案校验通过,整份答案通过后再填写与提交。", chapter); } var result = new AgentAnswerSet(batches.SelectMany(b => b.Answers).ToArray(), string.Join('\n', batches.Select(b => b.Summary)), batches.SelectMany(b => b.Reviews ?? []).ToArray(), batches.SelectMany(b => b.Warnings ?? []).ToArray()); await File.WriteAllTextAsync(Path.Combine(directory, $"answers-{DateTime.Now:HHmmssfff}.json"), JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true }), token); if ((settings.StopOnUncertainAnswers ? AnswerValidator.Validate(questions, result.Answers, settings.MinimumConfidence) : AnswerValidator.ValidateStructure(questions, result.Answers)) is { } error) throw new AttentionException(error + " 答案已保存在本地供检查。"); await CheckpointAsync(token); await browser.ApplyAnswersAsync(questions, result.Answers, token); Log("info", result.Summary, chapter); foreach (var answer in result.Answers) Log("info", $"题目 {answer.QuestionId}:{string.Join(",", answer.Choices)}{answer.Text};依据:{answer.Evidence}", chapter); if (!settings.AutoSubmit) throw new AttentionException("答案已填入,自动提交已关闭。"); await CheckpointAsync(token); var submission = await browser.SubmitAsync(questions, token); if (!submission.Submitted || !submission.Confirmed) throw new AttentionException(submission.Message); Log("success", submission.Message, chapter); SetStatus(LearningStatus.Running); return submission; } public async Task PauseAsync() { if (!IsRunning) return; lock (_pauseLock) _pauseGate ??= new(TaskCreationOptions.RunContinuationsAsynchronously); await browser.PauseAllAsync(CancellationToken.None); SetStatus(LearningStatus.Paused); } public void Resume() { TaskCompletionSource? gate; lock (_pauseLock) { gate = _pauseGate; _pauseGate = null; } gate?.TrySetResult(); if (IsRunning && Status == LearningStatus.Paused) SetStatus(LearningStatus.Running); } public void Stop() => _stop?.Cancel(); private async Task CheckpointAsync(CancellationToken token) { token.ThrowIfCancellationRequested(); Task? gate; lock (_pauseLock) gate = _pauseGate?.Task; if (gate is not null) await gate.WaitAsync(token); token.ThrowIfCancellationRequested(); } private Task WaitAsync(CancellationToken token) => Task.Delay(pollInterval ?? TimeSpan.FromSeconds(2), token); private void SetStatus(LearningStatus status) { if (IsPaused && status is LearningStatus.Running or LearningStatus.Analyzing or LearningStatus.Transcribing or LearningStatus.Answering) return; Status = status; StatusChanged?.Invoke(status); } private void Log(string level, string message, string? chapter = null) => Notice?.Invoke(new(DateTimeOffset.Now, level, message, chapter)); private static string Limit(string text, int maximum) => text.Length > maximum ? text[..maximum] : text; private static string SafeName(string value) => string.Concat(value.Select(c => char.IsLetterOrDigit(c) || c is '-' or '_' ? c : '_')); private sealed class AttentionException(string message) : Exception(message); }