ExamAnswerAnalysisService.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\DB;
  4. use Illuminate\Support\Facades\Log;
  5. use Illuminate\Support\Collection;
  6. /**
  7. * 考试答题分析服务(步骤级分析)
  8. * 基于卷子分析思考文档的思路实现
  9. *
  10. * 核心流程:
  11. * 1. 接收卷子ID和每道题的对错、简答题的分步骤对错
  12. * 2. 将原子信息映射到知识点/技能
  13. * 3. 计算知识点掌握度向量
  14. * 4. 生成详细分析报告
  15. * 5. 提供智能出卷推荐依据
  16. */
  17. class ExamAnswerAnalysisService
  18. {
  19. public function __construct(
  20. private readonly MasteryCalculator $masteryCalculator,
  21. private readonly KnowledgeMasteryService $knowledgeMasteryService,
  22. private readonly LocalAIAnalysisService $aiAnalysisService
  23. ) {}
  24. /**
  25. * 分析考试答题数据
  26. *
  27. * @param array $examData 考试数据
  28. * [
  29. * 'paper_id' => 'exam_001',
  30. * 'student_id' => 'student_001',
  31. * 'questions' => [
  32. * [
  33. * 'question_id' => 'Q1',
  34. * 'score' => 5,
  35. * 'score_obtained' => 5,
  36. * 'steps' => [
  37. * ['step_index' => 1, 'is_correct' => true, 'kp_id' => 'K-SQRT-SIMPLE'],
  38. * ['step_index' => 2, 'is_correct' => true, 'kp_id' => 'K-NUM-ADD-SUB']
  39. * ]
  40. * ]
  41. * ]
  42. * ]
  43. *
  44. * @return array 分析结果
  45. */
  46. public function analyzeExamAnswers(array $examData): array
  47. {
  48. Log::info('开始分析考试答题', [
  49. 'paper_id' => $examData['paper_id'] ?? 'unknown',
  50. 'student_id' => $examData['student_id'] ?? 'unknown',
  51. 'question_count' => count($examData['questions'] ?? [])
  52. ]);
  53. $studentId = $examData['student_id'];
  54. $questions = $examData['questions'] ?? [];
  55. // 1. 保存答题记录到数据库
  56. $this->saveExamAnswerRecords($examData);
  57. // 2. 获取题目知识点映射
  58. $questionMappings = $this->getQuestionKnowledgeMappings($questions);
  59. // 3. 计算每个知识点的加权掌握度
  60. $knowledgeMasteryVector = $this->calculateKnowledgeMasteryVector($questions, $questionMappings);
  61. // 4. 更新学生掌握度
  62. $updatedMastery = $this->updateStudentMastery($studentId, $knowledgeMasteryVector);
  63. // 5. 生成题目维度分析
  64. $questionAnalysis = $this->analyzeQuestions($questions, $questionMappings);
  65. // 6. 生成知识点维度分析
  66. $knowledgePointAnalysis = $this->analyzeKnowledgePoints($knowledgeMasteryVector, $questionMappings);
  67. // 7. 生成整体掌握度总结
  68. $overallSummary = $this->generateOverallSummary($updatedMastery);
  69. // 8. 生成智能出卷推荐依据
  70. $smartQuizRecommendation = $this->generateSmartQuizRecommendation($updatedMastery);
  71. // 9. 保存分析结果
  72. $analysisResult = [
  73. 'paper_id' => $examData['paper_id'],
  74. 'student_id' => $studentId,
  75. 'timestamp' => now()->toISOString(),
  76. 'question_analysis' => $questionAnalysis,
  77. 'knowledge_point_analysis' => $knowledgePointAnalysis,
  78. 'overall_summary' => $overallSummary,
  79. 'smart_quiz_recommendation' => $smartQuizRecommendation,
  80. 'mastery_vector' => $updatedMastery,
  81. ];
  82. $this->saveAnalysisResult($studentId, $examData['paper_id'], $analysisResult);
  83. Log::info('考试答题分析完成', [
  84. 'student_id' => $studentId,
  85. 'paper_id' => $examData['paper_id'],
  86. 'analyzed_knowledge_points' => count($knowledgeMasteryVector)
  87. ]);
  88. return $analysisResult;
  89. }
  90. /**
  91. * 获取题目知识点映射
  92. */
  93. private function getQuestionKnowledgeMappings(array $questions): array
  94. {
  95. $mappings = [];
  96. // 直接从题目数据中提取知识点信息(不再调用外部服务)
  97. foreach ($questions as $question) {
  98. $questionId = $question['question_id'] ?? null;
  99. if (!$questionId) continue;
  100. // 提取知识点信息(优先使用请求数据中的字段)
  101. $kpMapping = [];
  102. // 尝试多个可能的知识点字段
  103. $kpCode = $question['kp_code']
  104. ?? $question['knowledge_point']
  105. ?? $question['kp_code']
  106. ?? null;
  107. if (!empty($kpCode)) {
  108. $kpMapping[] = [
  109. 'kp_id' => $kpCode,
  110. 'kp_name' => $question['kp_name'] ?? $kpCode,
  111. 'weight' => 1.0
  112. ];
  113. } else {
  114. // 如果没有知识点信息,使用默认的综合知识点
  115. $kpMapping[] = [
  116. 'kp_id' => 'K-GENERAL',
  117. 'kp_name' => '综合',
  118. 'weight' => 1.0
  119. ];
  120. }
  121. $mappings[$questionId] = [
  122. 'question_id' => $questionId,
  123. 'kp_mapping' => $kpMapping
  124. ];
  125. }
  126. Log::info('题目知识点映射构建完成', [
  127. 'total_questions' => count($questions),
  128. 'mapped_questions' => count($mappings),
  129. ]);
  130. return $mappings;
  131. }
  132. /**
  133. * 计算知识点掌握度向量
  134. * 【修复】集成MasteryCalculator的BKT模型进行精确计算
  135. *
  136. * 核心算法说明:
  137. * 1. 从考试答题中提取每个知识点的答题记录
  138. * 2. 调用MasteryCalculator计算掌握度(包含:正确率、难度加权、时间效率、遗忘曲线)
  139. * 3. 返回包含掌握度、置信度、趋势等完整信息的向量
  140. */
  141. private function calculateKnowledgeMasteryVector(array $questions, array $questionMappings): array
  142. {
  143. // 按知识点聚合答题记录
  144. $knowledgeAttempts = [];
  145. foreach ($questions as $question) {
  146. $questionId = $question['question_id'];
  147. $score = floatval($question['score_obtained'] ?? 0);
  148. $maxScore = floatval($question['score'] ?? $score);
  149. $steps = $question['steps'] ?? [];
  150. $isCorrect = $question['is_correct'] ?? ($score >= $maxScore);
  151. $mapping = $questionMappings[$questionId] ?? null;
  152. if (!$mapping || !isset($mapping['kp_mapping'])) {
  153. continue;
  154. }
  155. // 构建答题记录(用于MasteryCalculator)
  156. $attemptRecord = [
  157. 'question_id' => $questionId,
  158. 'is_correct' => $isCorrect,
  159. 'partial_score' => $maxScore > 0 ? $score / $maxScore : 0,
  160. 'question_difficulty' => $question['difficulty'] ?? 0.6,
  161. 'attempt_time_seconds' => $question['time_spent'] ?? 120,
  162. 'completed_at' => now()->toISOString(),
  163. 'created_at' => now()->toISOString(),
  164. ];
  165. // 如果有步骤级分析,使用步骤分析
  166. if (!empty($steps)) {
  167. foreach ($steps as $step) {
  168. $kpId = $step['kp_id'] ?? 'K-GENERAL';
  169. if (!isset($knowledgeAttempts[$kpId])) {
  170. $knowledgeAttempts[$kpId] = [
  171. 'attempts' => [],
  172. 'step_details' => [],
  173. ];
  174. }
  175. // 每个步骤作为独立答题记录
  176. $stepAttempt = $attemptRecord;
  177. $stepAttempt['is_correct'] = $step['is_correct'];
  178. $stepAttempt['step_index'] = $step['step_index'];
  179. $knowledgeAttempts[$kpId]['attempts'][] = $stepAttempt;
  180. $knowledgeAttempts[$kpId]['step_details'][] = [
  181. 'question_id' => $questionId,
  182. 'step_index' => $step['step_index'],
  183. 'score' => $step['score'] ?? ($maxScore / count($steps)),
  184. 'is_correct' => $step['is_correct'],
  185. ];
  186. }
  187. } else {
  188. // 题目整体分析
  189. foreach ($mapping['kp_mapping'] as $kpMapping) {
  190. $kpId = $kpMapping['kp_id'];
  191. if (!isset($knowledgeAttempts[$kpId])) {
  192. $knowledgeAttempts[$kpId] = [
  193. 'attempts' => [],
  194. 'step_details' => [],
  195. ];
  196. }
  197. $knowledgeAttempts[$kpId]['attempts'][] = $attemptRecord;
  198. $knowledgeAttempts[$kpId]['step_details'][] = [
  199. 'question_id' => $questionId,
  200. 'score' => $score,
  201. 'max_score' => $maxScore,
  202. 'is_correct' => $isCorrect,
  203. ];
  204. }
  205. }
  206. }
  207. // 【核心】使用MasteryCalculator计算每个知识点的掌握度
  208. $masteryVector = [];
  209. foreach ($knowledgeAttempts as $kpId => $data) {
  210. $attempts = $data['attempts'];
  211. // 调用MasteryCalculator的核心算法
  212. // 该算法包含:正确率、难度加权、时间效率、技能熟练度、遗忘曲线衰减
  213. $masteryResult = $this->masteryCalculator->calculateMasteryLevel(
  214. '', // studentId在此不需要,因为直接传入attempts
  215. $kpId,
  216. $attempts
  217. );
  218. $masteryVector[$kpId] = [
  219. 'kp_id' => $kpId,
  220. 'mastery' => $masteryResult['mastery'],
  221. 'confidence' => $masteryResult['confidence'],
  222. 'trend' => $masteryResult['trend'],
  223. 'total_attempts' => $masteryResult['total_attempts'],
  224. 'correct_attempts' => $masteryResult['correct_attempts'],
  225. 'accuracy_rate' => $masteryResult['accuracy_rate'],
  226. 'step_details' => $data['step_details'],
  227. // 计算细节(用于调试和分析)
  228. 'calculation_details' => $masteryResult['details'] ?? [],
  229. ];
  230. }
  231. Log::info('知识点掌握度向量计算完成', [
  232. 'knowledge_points_count' => count($masteryVector),
  233. 'sample' => array_slice($masteryVector, 0, 3, true),
  234. ]);
  235. return $masteryVector;
  236. }
  237. /**
  238. * 更新学生掌握度(与历史数据合并)
  239. */
  240. private function updateStudentMastery(string $studentId, array $knowledgeMasteryVector): array
  241. {
  242. $updatedMastery = [];
  243. foreach ($knowledgeMasteryVector as $kpId => $data) {
  244. // 获取历史掌握度
  245. $historyMastery = DB::connection('mysql')
  246. ->table('student_knowledge_mastery')
  247. ->where('student_id', $studentId)
  248. ->where('kp_code', $kpId)
  249. ->first();
  250. $historyMasteryLevel = $historyMastery->mastery_level ?? 0.5;
  251. $historyWeight = $historyMastery->total_attempts ?? 0;
  252. $currentWeight = $data['total_attempts'] ?? 1;
  253. // 合并计算:历史权重 + 当前权重
  254. $newMastery = $historyWeight > 0
  255. ? ($historyWeight * $historyMasteryLevel + $currentWeight * $data['mastery'])
  256. / ($historyWeight + $currentWeight)
  257. : $data['mastery'];
  258. $newConfidence = $data['confidence'];
  259. // 保存到数据库
  260. DB::connection('mysql')
  261. ->table('student_knowledge_mastery')
  262. ->updateOrInsert(
  263. ['student_id' => $studentId, 'kp_code' => $kpId],
  264. [
  265. 'mastery_level' => $newMastery,
  266. 'confidence_level' => $newConfidence,
  267. 'total_attempts' => ($historyMastery->total_attempts ?? 0) + 1,
  268. 'correct_attempts' => ($historyMastery->correct_attempts ?? 0) + intval($data['correct_attempts'] > 0),
  269. 'mastery_trend' => $this->determineMasteryTrend($historyMasteryLevel, $newMastery),
  270. 'last_mastery_update' => now(),
  271. 'updated_at' => now(),
  272. ]
  273. );
  274. $updatedMastery[$kpId] = [
  275. 'kp_id' => $kpId,
  276. 'current_mastery' => $newMastery,
  277. 'previous_mastery' => $historyMasteryLevel,
  278. 'confidence' => $newConfidence,
  279. 'change' => $newMastery - $historyMasteryLevel,
  280. 'weight' => $currentWeight
  281. ];
  282. }
  283. return $updatedMastery;
  284. }
  285. /**
  286. * 生成题目维度分析(包含AI分析和解题思路)
  287. */
  288. private function analyzeQuestions(array $questions, array $questionMappings): array
  289. {
  290. $analysis = [];
  291. foreach ($questions as $question) {
  292. $questionId = $question['question_id'];
  293. $score = floatval($question['score_obtained'] ?? 0);
  294. $maxScore = floatval($question['score'] ?? $score);
  295. $steps = $question['steps'] ?? [];
  296. $isCorrect = $question['is_correct'] ?? ($score >= $maxScore);
  297. $mapping = $questionMappings[$questionId] ?? ['kp_mapping' => []];
  298. $kpCode = $mapping['kp_mapping'][0]['kp_id'] ?? 'K-GENERAL';
  299. // 步骤分析
  300. $stepAnalysis = [];
  301. if (!empty($steps)) {
  302. foreach ($steps as $step) {
  303. $kpId = $step['kp_id'] ?? 'K-GENERAL';
  304. $stepAnalysis[] = [
  305. 'step_index' => $step['step_index'],
  306. 'is_correct' => $step['is_correct'],
  307. 'kp_id' => $kpId,
  308. 'description' => $step['description'] ?? ''
  309. ];
  310. }
  311. }
  312. // 知识点关联
  313. $knowledgePoints = array_map(function($kp) {
  314. return [
  315. 'kp_id' => $kp['kp_id'],
  316. 'kp_name' => $kp['kp_name'] ?? $kp['kp_id'],
  317. 'weight' => $kp['weight'] ?? 1.0
  318. ];
  319. }, $mapping['kp_mapping']);
  320. // 【集成】调用AI分析服务,获取解题思路和错误分析
  321. $aiAnalysis = $this->getQuestionAIAnalysis($question, $mapping);
  322. $analysis[] = [
  323. 'question_id' => $questionId,
  324. 'score_obtained' => $score,
  325. 'max_score' => $maxScore,
  326. 'accuracy_rate' => $maxScore > 0 ? $score / $maxScore : 0,
  327. 'is_correct' => $isCorrect,
  328. 'step_analysis' => $stepAnalysis,
  329. 'knowledge_points' => $knowledgePoints,
  330. 'performance_summary' => $this->generateQuestionPerformanceSummary($question, $stepAnalysis),
  331. // 【新增】解题思路和错误分析
  332. 'solution_process' => $aiAnalysis['solution_process'] ?? '',
  333. 'error_analysis' => $aiAnalysis['error_analysis'] ?? '',
  334. 'mistake_type' => $aiAnalysis['mistake_type'] ?? '',
  335. 'suggestions' => $aiAnalysis['suggestions'] ?? '',
  336. 'next_steps' => $aiAnalysis['next_steps'] ?? [],
  337. ];
  338. }
  339. return $analysis;
  340. }
  341. /**
  342. * 获取题目的AI分析(解题思路、错误分析)
  343. */
  344. private function getQuestionAIAnalysis(array $question, array $mapping): array
  345. {
  346. $isCorrect = $question['is_correct'] ?? false;
  347. $score = floatval($question['score_obtained'] ?? 0);
  348. $maxScore = floatval($question['score'] ?? 10);
  349. $kpCode = $mapping['kp_mapping'][0]['kp_id'] ?? 'K-GENERAL';
  350. // 调用LocalAIAnalysisService进行分析
  351. try {
  352. $analysisResult = $this->aiAnalysisService->analyzeAnswer([
  353. 'question_id' => $question['question_id'],
  354. 'question_text' => $question['question_text'] ?? '',
  355. 'student_answer' => $question['student_answer'] ?? '',
  356. 'correct_answer' => $question['correct_answer'] ?? '',
  357. 'score' => $score,
  358. 'max_score' => $maxScore,
  359. 'kp_code' => $kpCode,
  360. ]);
  361. $data = $analysisResult['data'] ?? [];
  362. // 根据正确性生成不同的解题思路
  363. if ($isCorrect) {
  364. return [
  365. 'solution_process' => $data['correct_solution'] ?? '该题作答正确,解题思路清晰',
  366. 'error_analysis' => '',
  367. 'mistake_type' => '',
  368. 'suggestions' => $data['suggestions'] ?? '继续保持良好的解题习惯',
  369. 'next_steps' => $data['next_steps'] ?? ['尝试更高难度的同类题目'],
  370. ];
  371. }
  372. // 错误题目:返回详细分析
  373. return [
  374. 'solution_process' => $data['correct_solution'] ?? '请参考标准解题步骤',
  375. 'error_analysis' => $data['reason'] ?? '解题过程中存在错误',
  376. 'mistake_type' => $data['mistake_type'] ?? '计算或理解错误',
  377. 'suggestions' => $data['suggestions'] ?? '建议针对薄弱知识点进行专项练习',
  378. 'next_steps' => $data['next_steps'] ?? ['复习相关知识点', '做同类型练习题'],
  379. ];
  380. } catch (\Exception $e) {
  381. Log::warning('AI分析失败,使用默认分析', [
  382. 'question_id' => $question['question_id'],
  383. 'error' => $e->getMessage(),
  384. ]);
  385. // 回退到基础分析
  386. return $this->getFallbackAnalysis($question, $isCorrect);
  387. }
  388. }
  389. /**
  390. * 回退分析(当AI分析失败时)
  391. */
  392. private function getFallbackAnalysis(array $question, bool $isCorrect): array
  393. {
  394. if ($isCorrect) {
  395. return [
  396. 'solution_process' => '该题作答正确',
  397. 'error_analysis' => '',
  398. 'mistake_type' => '',
  399. 'suggestions' => '继续保持',
  400. 'next_steps' => ['尝试更高难度的题目'],
  401. ];
  402. }
  403. $scoreRatio = floatval($question['score_obtained'] ?? 0) / max(floatval($question['score'] ?? 1), 1);
  404. return [
  405. 'solution_process' => '请参考标准答案和解题步骤',
  406. 'error_analysis' => $scoreRatio < 0.3 ? '知识点理解存在偏差' : '解题过程中出现错误',
  407. 'mistake_type' => $scoreRatio < 0.3 ? '概念错误' : '计算/步骤错误',
  408. 'suggestions' => '建议复习相关知识点,加强练习',
  409. 'next_steps' => ['复习基础概念', '做同类型练习题', '请教老师或同学'],
  410. ];
  411. }
  412. /**
  413. * 生成知识点维度分析
  414. */
  415. private function analyzeKnowledgePoints(array $knowledgeMasteryVector, array $questionMappings): array
  416. {
  417. $analysis = [];
  418. foreach ($knowledgeMasteryVector as $kpId => $data) {
  419. $analysis[] = [
  420. 'kp_id' => $kpId,
  421. 'mastery_level' => $data['mastery'],
  422. 'confidence_level' => $data['confidence'],
  423. 'performance_in_exam' => $this->evaluatePerformanceLevel($data['mastery']),
  424. 'evidence_count' => count($data['step_details']),
  425. 'step_evidence' => $data['step_details'],
  426. 'recommendation' => $this->generateKnowledgePointRecommendation($data)
  427. ];
  428. }
  429. return $analysis;
  430. }
  431. /**
  432. * 生成整体掌握度总结
  433. */
  434. private function generateOverallSummary(array $updatedMastery): array
  435. {
  436. $knowledgePoints = array_values($updatedMastery);
  437. if (empty($knowledgePoints)) {
  438. return [
  439. 'total_knowledge_points' => 0,
  440. 'average_mastery' => 0,
  441. 'mastery_distribution' => [
  442. 'mastered' => 0,
  443. 'good' => 0,
  444. 'weak' => 0
  445. ],
  446. 'top_strengths' => [],
  447. 'top_weaknesses' => []
  448. ];
  449. }
  450. // 计算平均掌握度
  451. $averageMastery = array_sum(array_column($knowledgePoints, 'current_mastery')) / count($knowledgePoints);
  452. // 掌握度分布
  453. $mastered = array_filter($knowledgePoints, fn($kp) => $kp['current_mastery'] >= 0.85);
  454. $good = array_filter($knowledgePoints, fn($kp) => $kp['current_mastery'] >= 0.70 && $kp['current_mastery'] < 0.85);
  455. $weak = array_filter($knowledgePoints, fn($kp) => $kp['current_mastery'] < 0.70);
  456. // 排序找出优势和薄弱点
  457. usort($knowledgePoints, fn($a, $b) => $b['current_mastery'] <=> $a['current_mastery']);
  458. $topStrengths = array_slice($knowledgePoints, 0, 3);
  459. $topWeaknesses = array_slice(array_reverse($knowledgePoints), 0, 3);
  460. return [
  461. 'total_knowledge_points' => count($knowledgePoints),
  462. 'average_mastery' => round($averageMastery, 4),
  463. 'mastery_distribution' => [
  464. 'mastered' => count($mastered),
  465. 'good' => count($good),
  466. 'weak' => count($weak)
  467. ],
  468. 'top_strengths' => $topStrengths,
  469. 'top_weaknesses' => $topWeaknesses,
  470. 'overall_performance' => $this->evaluateOverallPerformance($averageMastery)
  471. ];
  472. }
  473. /**
  474. * 生成智能出卷推荐依据
  475. * 基于文档中的推荐优先级算法
  476. */
  477. private function generateSmartQuizRecommendation(array $updatedMastery): array
  478. {
  479. $recommendations = [];
  480. foreach ($updatedMastery as $kpId => $data) {
  481. $mastery = $data['current_mastery'];
  482. $confidence = $data['confidence'];
  483. $weight = $data['weight'];
  484. // 推荐优先级 = (1 - 掌握度) * 重要性 * 覆盖需求
  485. // 重要性可以根据知识点在中考/阶段考试中的权重,这里简化为1.0
  486. $importance = 1.0;
  487. // 覆盖需求:最近没考过或考得少,值大
  488. $coverageNeed = max(1.0, 1.5 - ($weight / 10));
  489. $priority = (1 - $mastery) * $importance * $coverageNeed;
  490. $recommendations[] = [
  491. 'kp_id' => $kpId,
  492. 'current_mastery' => $mastery,
  493. 'priority' => $priority,
  494. 'recommended_questions' => $this->calculateRecommendedQuestions($mastery),
  495. 'focus_type' => $this->determineFocusType($mastery)
  496. ];
  497. }
  498. // 按优先级排序
  499. usort($recommendations, fn($a, $b) => $b['priority'] <=> $a['priority']);
  500. // 控制难度节奏:40%巩固型 + 40%修补型 + 20%挑战型
  501. $totalRecommendations = count($recommendations);
  502. $consolidation = array_slice($recommendations, 0, intval($totalRecommendations * 0.4));
  503. $remediation = array_slice($recommendations, intval($totalRecommendations * 0.4), intval($totalRecommendations * 0.4));
  504. $challenge = array_slice($recommendations, intval($totalRecommendations * 0.8));
  505. return [
  506. 'priority_list' => $recommendations,
  507. 'quiz_structure' => [
  508. 'consolidation_type' => $consolidation,
  509. 'remediation_type' => $remediation,
  510. 'challenge_type' => $challenge
  511. ],
  512. 'total_recommended_questions' => array_sum(array_column($recommendations, 'recommended_questions'))
  513. ];
  514. }
  515. /**
  516. * 保存考试答题记录
  517. */
  518. private function saveExamAnswerRecords(array $examData): void
  519. {
  520. $studentId = $examData['student_id'];
  521. $examId = $examData['paper_id'];
  522. // 【修复】先清理该考试的所有答题记录(支持重复考试)
  523. DB::connection('mysql')->table('student_answer_questions')
  524. ->where('student_id', $studentId)
  525. ->where('exam_id', $examId)
  526. ->delete();
  527. DB::connection('mysql')->table('student_answer_steps')
  528. ->where('student_id', $studentId)
  529. ->where('exam_id', $examId)
  530. ->delete();
  531. foreach ($examData['questions'] as $question) {
  532. $questionId = $question['question_id'];
  533. $steps = $question['steps'] ?? [];
  534. // 保存步骤级记录
  535. if (!empty($steps)) {
  536. foreach ($steps as $step) {
  537. DB::connection('mysql')->table('student_answer_steps')->insert([
  538. 'student_id' => $studentId,
  539. 'exam_id' => $examId,
  540. 'question_id' => $questionId,
  541. 'step_index' => $step['step_index'],
  542. 'kp_id' => $step['kp_id'] ?? 'K-GENERAL',
  543. 'is_correct' => $step['is_correct'],
  544. 'step_score' => $step['score'] ?? 0,
  545. 'created_at' => now(),
  546. 'updated_at' => now(),
  547. ]);
  548. }
  549. } else {
  550. // 保存题目级记录
  551. DB::connection('mysql')->table('student_answer_questions')->insert([
  552. 'student_id' => $studentId,
  553. 'exam_id' => $examId,
  554. 'question_id' => $questionId,
  555. 'score_obtained' => $question['score_obtained'] ?? 0,
  556. 'max_score' => $question['score'] ?? 0,
  557. 'created_at' => now(),
  558. 'updated_at' => now(),
  559. ]);
  560. }
  561. }
  562. Log::info('答题记录保存完成', [
  563. 'student_id' => $studentId,
  564. 'exam_id' => $examId,
  565. 'question_count' => count($examData['questions']),
  566. ]);
  567. }
  568. /**
  569. * 保存分析结果并创建掌握度快照
  570. */
  571. private function saveAnalysisResult(string $studentId, string $paperId, array $result): void
  572. {
  573. // 【修复】支持重复分析:先删除旧的分析结果
  574. DB::connection('mysql')->table('exam_analysis_results')
  575. ->where('student_id', $studentId)
  576. ->where('paper_id', $paperId)
  577. ->delete();
  578. // 插入新的分析结果
  579. DB::connection('mysql')->table('exam_analysis_results')->insert([
  580. 'student_id' => $studentId,
  581. 'paper_id' => $paperId,
  582. 'analysis_data' => json_encode($result),
  583. 'created_at' => now(),
  584. 'updated_at' => now(),
  585. ]);
  586. Log::info('分析结果保存完成', [
  587. 'student_id' => $studentId,
  588. 'paper_id' => $paperId,
  589. 'data_size' => strlen(json_encode($result)),
  590. ]);
  591. // 【集成】创建知识点掌握度快照
  592. $this->createMasterySnapshot($studentId, $paperId, $result);
  593. // 【新增】异步生成学情分析PDF
  594. try {
  595. Log::info('开始异步生成学情分析PDF', [
  596. 'student_id' => $studentId,
  597. 'paper_id' => $paperId,
  598. ]);
  599. // 使用队列异步生成PDF,避免阻塞主流程
  600. dispatch(new \App\Jobs\GenerateAnalysisPdfJob($paperId, $studentId, null));
  601. Log::info('PDF生成任务已加入队列', [
  602. 'student_id' => $studentId,
  603. 'paper_id' => $paperId,
  604. ]);
  605. } catch (\Exception $e) {
  606. Log::error('PDF生成任务加入队列失败', [
  607. 'student_id' => $studentId,
  608. 'paper_id' => $paperId,
  609. 'error' => $e->getMessage(),
  610. ]);
  611. }
  612. }
  613. /**
  614. * 创建知识点掌握度快照
  615. * 【集成】使用LocalAIAnalysisService的快照功能
  616. *
  617. * 快照用途:
  618. * 1. 追踪学生掌握度变化趋势
  619. * 2. 生成学情报告时对比历史数据
  620. * 3. 为智能出卷提供决策依据
  621. */
  622. private function createMasterySnapshot(string $studentId, string $paperId, array $analysisResult): void
  623. {
  624. try {
  625. // 计算快照数据
  626. $masteryVector = $analysisResult['mastery_vector'] ?? [];
  627. $overallMastery = 0;
  628. $weakCount = 0;
  629. $strongCount = 0;
  630. foreach ($masteryVector as $kpData) {
  631. $mastery = $kpData['current_mastery'] ?? $kpData['mastery'] ?? 0;
  632. $overallMastery += $mastery;
  633. if ($mastery < 0.6) {
  634. $weakCount++;
  635. } elseif ($mastery >= 0.85) {
  636. $strongCount++;
  637. }
  638. }
  639. $kpCount = count($masteryVector);
  640. $overallMastery = $kpCount > 0 ? round($overallMastery / $kpCount, 4) : 0;
  641. // 生成快照ID
  642. $snapshotId = 'snap_' . $paperId . '_' . now()->format('YmdHis');
  643. // 保存到快照表
  644. DB::connection('mysql')->table('knowledge_point_mastery_snapshots')->insert([
  645. 'snapshot_id' => $snapshotId,
  646. 'student_id' => $studentId,
  647. 'paper_id' => $paperId,
  648. 'answer_record_id' => null,
  649. 'mastery_data' => json_encode($masteryVector),
  650. 'overall_mastery' => $overallMastery,
  651. 'weak_knowledge_points_count' => $weakCount,
  652. 'strong_knowledge_points_count' => $strongCount,
  653. 'snapshot_time' => now(),
  654. 'analysis_id' => null,
  655. 'created_at' => now(),
  656. 'updated_at' => now(),
  657. ]);
  658. Log::info('掌握度快照创建成功', [
  659. 'snapshot_id' => $snapshotId,
  660. 'student_id' => $studentId,
  661. 'paper_id' => $paperId,
  662. 'overall_mastery' => $overallMastery,
  663. 'weak_count' => $weakCount,
  664. 'strong_count' => $strongCount,
  665. ]);
  666. } catch (\Exception $e) {
  667. // 快照创建失败不影响主流程
  668. Log::warning('掌握度快照创建失败', [
  669. 'student_id' => $studentId,
  670. 'paper_id' => $paperId,
  671. 'error' => $e->getMessage(),
  672. ]);
  673. }
  674. }
  675. /**
  676. * 判断掌握度趋势
  677. */
  678. private function determineMasteryTrend(float $previous, float $current): string
  679. {
  680. $change = $current - $previous;
  681. if ($change > 0.1) {
  682. return 'improving';
  683. } elseif ($change < -0.1) {
  684. return 'declining';
  685. } else {
  686. return 'stable';
  687. }
  688. }
  689. /**
  690. * 评估表现水平
  691. */
  692. private function evaluatePerformanceLevel(float $mastery): string
  693. {
  694. if ($mastery >= 0.85) {
  695. return 'excellent';
  696. } elseif ($mastery >= 0.70) {
  697. return 'good';
  698. } elseif ($mastery >= 0.50) {
  699. return 'fair';
  700. } else {
  701. return 'poor';
  702. }
  703. }
  704. /**
  705. * 生成题目表现总结
  706. */
  707. private function generateQuestionPerformanceSummary(array $question, array $stepAnalysis): string
  708. {
  709. if (empty($stepAnalysis)) {
  710. return '整题作答';
  711. }
  712. $correctSteps = count(array_filter($stepAnalysis, fn($s) => $s['is_correct']));
  713. $totalSteps = count($stepAnalysis);
  714. if ($correctSteps === $totalSteps) {
  715. return '所有步骤正确';
  716. } elseif ($correctSteps > 0) {
  717. return "部分正确 ({$correctSteps}/{$totalSteps} 步骤正确)";
  718. } else {
  719. return '所有步骤错误';
  720. }
  721. }
  722. /**
  723. * 生成知识点建议
  724. */
  725. private function generateKnowledgePointRecommendation(array $data): string
  726. {
  727. $mastery = $data['mastery'];
  728. if ($mastery >= 0.85) {
  729. return '掌握良好,可安排综合练习';
  730. } elseif ($mastery >= 0.70) {
  731. return '基本掌握,建议加强练习';
  732. } elseif ($mastery >= 0.50) {
  733. return '需要重点练习,建议安排专项训练';
  734. } else {
  735. return '薄弱知识点,建议系统学习和大量练习';
  736. }
  737. }
  738. /**
  739. * 评估整体表现
  740. */
  741. private function evaluateOverallPerformance(float $averageMastery): string
  742. {
  743. if ($averageMastery >= 0.85) {
  744. return '优秀';
  745. } elseif ($averageMastery >= 0.70) {
  746. return '良好';
  747. } elseif ($averageMastery >= 0.50) {
  748. return '一般';
  749. } else {
  750. return '需加强';
  751. }
  752. }
  753. /**
  754. * 计算推荐题目数量
  755. */
  756. private function calculateRecommendedQuestions(float $mastery): int
  757. {
  758. if ($mastery >= 0.85) {
  759. return 1; // 巩固型:1题
  760. } elseif ($mastery >= 0.50) {
  761. return 2; // 修补型:2题
  762. } else {
  763. return 3; // 挑战型:3题
  764. }
  765. }
  766. /**
  767. * 确定重点类型
  768. */
  769. private function determineFocusType(float $mastery): string
  770. {
  771. if ($mastery >= 0.70 && $mastery < 0.85) {
  772. return 'consolidation'; // 巩固型
  773. } elseif ($mastery < 0.70) {
  774. return 'remediation'; // 修补型
  775. } else {
  776. return 'challenge'; // 挑战型
  777. }
  778. }
  779. }