ExamAnswerAnalysisService.php 40 KB

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