ExamAnalysis.php 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  1. <?php
  2. namespace App\Filament\Pages;
  3. use App\Models\OCRRecord;
  4. use App\Models\OCRQuestionResult;
  5. use App\Services\LearningAnalyticsService;
  6. use App\Services\OCRService;
  7. use BackedEnum;
  8. use Filament\Notifications\Notification;
  9. use Filament\Pages\Page;
  10. use Livewire\Attributes\Url;
  11. use UnitEnum;
  12. class ExamAnalysis extends Page
  13. {
  14. protected static ?string $title = '试卷分析详情';
  15. protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-chart-bar';
  16. protected static ?string $navigationLabel = '试卷分析';
  17. protected static string|UnitEnum|null $navigationGroup = '管理';
  18. protected static ?int $navigationSort = 15;
  19. #[Url]
  20. public ?string $recordId = null; // OCR记录ID
  21. #[Url]
  22. public ?string $paperId = null; // 系统生成卷子ID
  23. public array $recordData = [];
  24. public array $analysisData = []; // 整体掌握度分析数据
  25. public array $paperAnalysisData = []; // 本次试卷的分析结果
  26. public array $studentInfo = [];
  27. public bool $loading = true;
  28. public string $recordType = ''; // 'ocr' 或 'generated'
  29. public function mount()
  30. {
  31. // 允许使用 recordId(OCR记录)或 paperId(系统生成卷子)
  32. if (!$this->recordId && !$this->paperId) {
  33. Notification::make()
  34. ->title('错误')
  35. ->body('缺少记录ID或试卷ID')
  36. ->danger()
  37. ->send();
  38. $this->redirectRoute('filament.admin.pages.upload-exam-paper');
  39. return;
  40. }
  41. // 根据记录类型选择不同的视图
  42. if ($this->recordId) {
  43. // OCR记录使用紧凑布局
  44. $this->view = 'filament.pages.exam-analysis-compact';
  45. } elseif ($this->paperId) {
  46. // 系统生成卷子使用标准布局
  47. $this->view = 'filament.pages.exam-analysis-standard';
  48. }
  49. $this->loadAnalysisData();
  50. }
  51. protected function loadAnalysisData()
  52. {
  53. try {
  54. // 处理OCR记录
  55. if ($this->recordId) {
  56. $this->recordType = 'ocr';
  57. $record = OCRRecord::with('student')->find($this->recordId);
  58. if (!$record) {
  59. Notification::make()
  60. ->title('错误')
  61. ->body('未找到指定的上传记录')
  62. ->danger()
  63. ->send();
  64. $this->redirectRoute('filament.admin.pages.upload-exam-paper');
  65. return;
  66. }
  67. $this->recordData = $record->toArray();
  68. $this->studentInfo = $record->student ? $record->student->toArray() : [];
  69. // OCR记录:添加题目统计信息
  70. $ocrQuestionsCount = OCRQuestionResult::where('ocr_record_id', $this->recordId)->count();
  71. $this->recordData['total_questions'] = $ocrQuestionsCount;
  72. $this->recordData['questions'] = $this->getQuestions(); // 提前加载题目数据
  73. // OCR记录如果已完成处理,加载分析数据
  74. if ($record->status === 'completed' && $record->student_id) {
  75. $this->loadLearningAnalysis($record->student_id, $this->recordId);
  76. } else {
  77. $this->analysisData = [];
  78. }
  79. }
  80. // 处理系统生成卷子
  81. elseif ($this->paperId) {
  82. $this->recordType = 'generated';
  83. $paper = \App\Models\Paper::with('student')->find($this->paperId);
  84. if (!$paper) {
  85. Notification::make()
  86. ->title('错误')
  87. ->body('未找到指定的试卷')
  88. ->danger()
  89. ->send();
  90. $this->redirectRoute('filament.admin.pages.upload-exam-paper');
  91. return;
  92. }
  93. // 构造基础数据,视图会安全处理缺失字段
  94. $this->recordData = [
  95. 'id' => $paper->paper_id,
  96. 'paper_id' => $paper->paper_id,
  97. 'student_id' => $paper->student_id,
  98. 'paper_type' => 'system_generated',
  99. 'paper_name' => $paper->paper_name,
  100. 'status' => $paper->status,
  101. 'total_questions' => $paper->question_count,
  102. 'created_at' => $paper->created_at,
  103. 'analysis_id' => $paper->analysis_id, // AI分析记录ID
  104. ];
  105. $this->studentInfo = $paper->student ? $paper->student->toArray() : [];
  106. // 获取试卷题目列表(包含题库API的详细数据)
  107. $this->recordData['questions'] = $this->getQuestions();
  108. // 系统生成卷子也尝试加载学习分析数据
  109. if ($paper->student_id) {
  110. $this->loadLearningAnalysis($paper->student_id, $this->paperId);
  111. } else {
  112. $this->analysisData = [];
  113. }
  114. }
  115. $this->loading = false;
  116. } catch (\Exception $e) {
  117. \Log::error('加载试卷分析数据失败', [
  118. 'record_id' => $this->recordId,
  119. 'paper_id' => $this->paperId,
  120. 'error' => $e->getMessage(),
  121. 'trace' => $e->getTraceAsString()
  122. ]);
  123. Notification::make()
  124. ->title('错误')
  125. ->body('加载分析数据失败:' . $e->getMessage())
  126. ->danger()
  127. ->send();
  128. $this->loading = false;
  129. }
  130. }
  131. /**
  132. * 加载学习分析数据
  133. */
  134. protected function loadLearningAnalysis($studentId, $identifier)
  135. {
  136. try {
  137. // 1. 尝试从数据库加载本次试卷的分析结果
  138. $paperId = null;
  139. if ($this->recordType === 'ocr') {
  140. $paperId = $this->recordData['exam_id'] ?? null;
  141. } elseif ($this->recordType === 'generated') {
  142. $paperId = $this->recordData['paper_id'] ?? null;
  143. }
  144. if ($paperId) {
  145. // 从 paper_analysis_results 表读取分析结果
  146. $paperAnalysis = \DB::table('paper_analysis_results')
  147. ->where('paper_id', $paperId)
  148. ->first();
  149. if ($paperAnalysis && !empty($paperAnalysis->analysis_data)) {
  150. $this->paperAnalysisData = json_decode($paperAnalysis->analysis_data, true);
  151. \Log::info('本次试卷分析结果已从数据库加载', [
  152. 'paper_id' => $paperId,
  153. 'student_id' => $studentId,
  154. 'data_keys' => array_keys($this->paperAnalysisData ?? [])
  155. ]);
  156. } else {
  157. // 如果数据库中没有分析结果,回退到API调用(临时解决方案)
  158. \Log::info('数据库中未找到分析结果,回退到API调用', [
  159. 'paper_id' => $paperId,
  160. 'student_id' => $studentId
  161. ]);
  162. $this->loadLearningAnalysisFromAPI($studentId, $paperId);
  163. return;
  164. }
  165. }
  166. // 2. 尝试从知识点记录表获取整体掌握度数据
  167. $knowledgePointRecords = \DB::table('knowledge_point_records')
  168. ->where('student_id', $studentId)
  169. ->get();
  170. // 处理知识点掌握度数据
  171. if ($knowledgePointRecords->count() > 0) {
  172. // 如果找到了知识点记录数据,使用它
  173. $this->processKnowledgePointRecords($knowledgePointRecords);
  174. } else {
  175. // 如果没有找到知识点记录,回退到API调用
  176. \Log::info('知识点记录表为空,回退到API调用', [
  177. 'student_id' => $studentId
  178. ]);
  179. $this->loadLearningAnalysisFromAPI($studentId, $paperId ?? null);
  180. }
  181. } catch (\Exception $e) {
  182. \Log::warning('加载分析数据失败,回退到API调用', [
  183. 'identifier' => $identifier,
  184. 'student_id' => $studentId,
  185. 'type' => $this->recordType,
  186. 'error' => $e->getMessage()
  187. ]);
  188. // 数据库查询失败时回退到API调用
  189. $this->loadLearningAnalysisFromAPI($studentId, $paperId ?? null);
  190. }
  191. }
  192. /**
  193. * 从API加载学习分析数据(回退方案)
  194. */
  195. protected function loadLearningAnalysisFromAPI($studentId, $paperId = null)
  196. {
  197. try {
  198. $learningService = app(\App\Services\LearningAnalyticsService::class);
  199. // 1. 加载本次试卷的分析结果
  200. $analysisId = null;
  201. if ($this->recordType === 'ocr' && isset($this->recordData['analysis_id'])) {
  202. $analysisId = $this->recordData['analysis_id'];
  203. } elseif ($this->recordType === 'generated' && isset($this->recordData['analysis_id'])) {
  204. $analysisId = $this->recordData['analysis_id'];
  205. }
  206. if ($analysisId) {
  207. $paperAnalysisResponse = $learningService->getAnalysisResult($analysisId);
  208. if (!empty($paperAnalysisResponse) && isset($paperAnalysisResponse['data'])) {
  209. $this->paperAnalysisData = $paperAnalysisResponse['data'];
  210. // 将API的分析结果同步到题目数据
  211. if (isset($this->paperAnalysisData['question_results'])) {
  212. $this->syncApiAnalysisToQuestions($this->paperAnalysisData['question_results']);
  213. }
  214. \Log::info('本次试卷分析结果已从API加载', [
  215. 'analysis_id' => $analysisId,
  216. 'student_id' => $studentId,
  217. 'data_keys' => array_keys($this->paperAnalysisData),
  218. 'question_results_count' => count($this->paperAnalysisData['question_results'] ?? [])
  219. ]);
  220. }
  221. }
  222. // 2. 调用学习分析API获取整体掌握度数据
  223. $masteryResponse = $learningService->getStudentMastery($studentId);
  224. // 转换为页面期望的格式
  225. if (!empty($masteryResponse) && isset($masteryResponse['data'])) {
  226. $masteryList = $masteryResponse['data'];
  227. // 计算整体掌握度
  228. $totalMastery = 0;
  229. $count = count($masteryList);
  230. $weakAreas = [];
  231. $knowledgePoints = [];
  232. foreach ($masteryList as $mastery) {
  233. $masteryLevel = $mastery['mastery_level'] ?? 0;
  234. $totalMastery += $masteryLevel;
  235. // 识别薄弱知识点(掌握度 < 0.6)
  236. if ($masteryLevel < 0.6) {
  237. $weakAreas[] = [
  238. 'kp_code' => $mastery['kp_code'],
  239. 'mastery' => $masteryLevel
  240. ];
  241. }
  242. // 构造知识点数据
  243. $totalAttempts = $mastery['total_attempts'] ?? 0;
  244. $correctAttempts = $mastery['correct_attempts'] ?? 0;
  245. $accuracyRate = $totalAttempts > 0 ? $correctAttempts / $totalAttempts : 0;
  246. $knowledgePoints[] = [
  247. 'kp_code' => $mastery['kp_code'],
  248. 'name' => $mastery['kp_code'], // TODO: 从知识图谱服务获取名称
  249. 'mastery' => $masteryLevel,
  250. 'mastery_level' => $masteryLevel, // 添加模板需要的字段
  251. 'total_attempts' => $totalAttempts,
  252. 'correct_attempts' => $correctAttempts,
  253. 'accuracy_rate' => $accuracyRate
  254. ];
  255. }
  256. $overallMastery = $count > 0 ? $totalMastery / $count : 0;
  257. // 生成学习建议
  258. $recommendations = $this->generateRecommendations($overallMastery, $weakAreas, $knowledgePoints);
  259. // 只显示与当前试卷相关的知识点
  260. $currentPaperKps = $this->getCurrentPaperKnowledgePoints();
  261. $currentPaperKpCodes = array_column($currentPaperKps, 'kp_code');
  262. $filteredKnowledgePoints = array_filter($knowledgePoints, function($kp) use ($currentPaperKpCodes) {
  263. return in_array($kp['kp_code'], $currentPaperKpCodes);
  264. });
  265. $this->analysisData = [
  266. 'overall_mastery' => $overallMastery,
  267. 'weak_areas' => array_filter($weakAreas, function($weak) use ($currentPaperKpCodes) {
  268. return in_array($weak['kp_code'], $currentPaperKpCodes);
  269. }),
  270. 'knowledge_points' => $filteredKnowledgePoints, // 只显示当前试卷相关知识点
  271. 'recommendations' => $recommendations,
  272. 'total_knowledge_points' => count($filteredKnowledgePoints),
  273. 'mastery_distribution' => $this->calculateMasteryDistribution($masteryList)
  274. ];
  275. \Log::info('学习分析数据已从API加载', [
  276. 'student_id' => $studentId,
  277. 'overall_mastery' => $overallMastery,
  278. 'knowledge_points_count' => count($knowledgePoints),
  279. 'filtered_knowledge_points_count' => count($filteredKnowledgePoints),
  280. 'current_paper_kp_codes' => $currentPaperKpCodes,
  281. 'weak_areas_count' => count($weakAreas)
  282. ]);
  283. } else {
  284. \Log::info('API返回数据为空', [
  285. 'student_id' => $studentId,
  286. 'paper_id' => $paperId,
  287. 'type' => $this->recordType
  288. ]);
  289. $this->analysisData = [];
  290. }
  291. } catch (\Exception $apiError) {
  292. \Log::warning('API调用失败', [
  293. 'student_id' => $studentId,
  294. 'paper_id' => $paperId,
  295. 'type' => $this->recordType,
  296. 'error' => $apiError->getMessage()
  297. ]);
  298. // API调用失败时设置空数组,避免页面报错
  299. $this->analysisData = [];
  300. $this->paperAnalysisData = [];
  301. }
  302. }
  303. /**
  304. * 处理知识点记录数据
  305. */
  306. protected function processKnowledgePointRecords($knowledgePointRecords)
  307. {
  308. // 根据实际的knowledge_point_records表结构处理数据
  309. $masteryList = [];
  310. $weakAreas = [];
  311. $knowledgePoints = [];
  312. $totalMastery = 0;
  313. $count = 0;
  314. foreach ($knowledgePointRecords as $record) {
  315. // knowledge_point_records表有不同的字段结构
  316. $kpCode = $record->knowledge_point ?? '';
  317. $masteryLevel = $record->mastery_after ?? $record->mastery_before ?? 0;
  318. if (!empty($kpCode)) {
  319. $masteryList[] = [
  320. 'kp_code' => $kpCode,
  321. 'mastery_level' => $masteryLevel
  322. ];
  323. $totalMastery += $masteryLevel;
  324. $count++;
  325. // 识别薄弱知识点(掌握度 < 0.6)
  326. if ($masteryLevel < 0.6) {
  327. $weakAreas[] = [
  328. 'kp_code' => $kpCode,
  329. 'mastery' => $masteryLevel
  330. ];
  331. }
  332. // 构造知识点数据
  333. $knowledgePoints[] = [
  334. 'kp_code' => $kpCode,
  335. 'name' => $kpCode,
  336. 'mastery' => $masteryLevel,
  337. 'mastery_level' => $masteryLevel, // 添加模板需要的字段
  338. 'total_attempts' => 1, // 默认值
  339. 'correct_attempts' => $masteryLevel > 0.5 ? 1 : 0, // 估算值
  340. 'accuracy_rate' => $masteryLevel
  341. ];
  342. }
  343. }
  344. $overallMastery = $count > 0 ? $totalMastery / $count : 0;
  345. // 生成学习建议
  346. $recommendations = $this->generateRecommendations($overallMastery, $weakAreas, $knowledgePoints);
  347. // 只显示与当前试卷相关的知识点
  348. $currentPaperKps = $this->getCurrentPaperKnowledgePoints();
  349. $currentPaperKpCodes = array_column($currentPaperKps, 'kp_code');
  350. $filteredKnowledgePoints = array_filter($knowledgePoints, function($kp) use ($currentPaperKpCodes) {
  351. return in_array($kp['kp_code'], $currentPaperKpCodes);
  352. });
  353. $this->analysisData = [
  354. 'overall_mastery' => $overallMastery,
  355. 'weak_areas' => array_filter($weakAreas, function($weak) use ($currentPaperKpCodes) {
  356. return in_array($weak['kp_code'], $currentPaperKpCodes);
  357. }),
  358. 'knowledge_points' => $filteredKnowledgePoints, // 只显示当前试卷相关知识点
  359. 'recommendations' => $recommendations,
  360. 'total_knowledge_points' => count($filteredKnowledgePoints),
  361. 'mastery_distribution' => $this->calculateMasteryDistribution($masteryList)
  362. ];
  363. \Log::info('学习分析数据已从knowledge_point_records加载', [
  364. 'student_id' => $knowledgePointRecords->first()->student_id ?? 'unknown',
  365. 'overall_mastery' => $overallMastery,
  366. 'knowledge_points_count' => count($knowledgePoints),
  367. 'filtered_knowledge_points_count' => count($filteredKnowledgePoints),
  368. 'current_paper_kp_codes' => $currentPaperKpCodes,
  369. 'weak_areas_count' => count($weakAreas)
  370. ]);
  371. }
  372. /**
  373. * 生成学习建议
  374. */
  375. protected function generateRecommendations($overallMastery, $weakAreas, $knowledgePoints)
  376. {
  377. $recommendations = [];
  378. if ($overallMastery >= 0.8) {
  379. $recommendations[] = '整体掌握情况良好,继续保持!可以尝试更有挑战性的题目。';
  380. } elseif ($overallMastery >= 0.6) {
  381. $recommendations[] = '基础掌握较好,建议加强薄弱知识点的练习。';
  382. } else {
  383. $recommendations[] = '需要系统复习基础知识,建议从简单题目开始逐步提升。';
  384. }
  385. // 针对薄弱知识点的建议
  386. if (count($weakAreas) > 0) {
  387. $weakKpCodes = array_slice(array_column($weakAreas, 'kp_code'), 0, 3);
  388. $recommendations[] = '重点加强以下知识点: ' . implode('、', $weakKpCodes);
  389. }
  390. // 根据答题次数给建议
  391. $lowAttempts = array_filter($knowledgePoints, function($kp) {
  392. return ($kp['total_attempts'] ?? 0) < 5;
  393. });
  394. if (count($lowAttempts) > 0) {
  395. $recommendations[] = '部分知识点练习次数较少,建议增加练习量以巩固掌握。';
  396. }
  397. return $recommendations;
  398. }
  399. /**
  400. * 计算掌握度分布
  401. */
  402. protected function calculateMasteryDistribution($masteryList)
  403. {
  404. $distribution = [
  405. 'high' => 0, // >= 0.7
  406. 'medium' => 0, // 0.4 - 0.7
  407. 'low' => 0 // < 0.4
  408. ];
  409. foreach ($masteryList as $mastery) {
  410. $level = $mastery['mastery_level'] ?? 0;
  411. if ($level >= 0.7) {
  412. $distribution['high']++;
  413. } elseif ($level >= 0.4) {
  414. $distribution['medium']++;
  415. } else {
  416. $distribution['low']++;
  417. }
  418. }
  419. return $distribution;
  420. }
  421. public function getPaperTypeLabel(): string
  422. {
  423. if ($this->recordType === 'ocr' && isset($this->recordData['paper_type'])) {
  424. return match($this->recordData['paper_type']) {
  425. 'unit_test' => '单元测试',
  426. 'midterm' => '期中考试',
  427. 'final' => '期末考试',
  428. 'homework' => '家庭作业',
  429. 'quiz' => '随堂测验',
  430. 'other' => '其他',
  431. default => '未分类',
  432. };
  433. }
  434. return $this->recordData['paper_type'] ?? '未知';
  435. }
  436. public function getStatusBadge(): string
  437. {
  438. $status = $this->recordData['status'] ?? 'unknown';
  439. return match($status) {
  440. 'pending' => '<span class="badge badge-ghost">待处理</span>',
  441. 'processing' => '<span class="badge badge-info gap-2"><span class="loading loading-spinner loading-xs"></span>处理中</span>',
  442. 'completed' => '<span class="badge badge-success">已完成</span>',
  443. 'failed' => '<span class="badge badge-error">失败</span>',
  444. default => '<span class="badge badge-ghost">未知</span>',
  445. };
  446. }
  447. /**
  448. * 判断是否为 OCR 场景
  449. */
  450. public function isOcrRecord(): bool
  451. {
  452. return $this->recordType === 'ocr';
  453. }
  454. /**
  455. * 获取OCR记录的题目数据
  456. * 从OCRQuestionResult表加载并格式化为组件期望的格式
  457. */
  458. protected function getOcrQuestions(): array
  459. {
  460. $recordId = $this->recordId ?? null;
  461. if (!$recordId) {
  462. \Log::warning('OCR记录缺少recordId', ['recordId' => $recordId]);
  463. return [];
  464. }
  465. try {
  466. // 从OCRQuestionResult表加载题目数据
  467. $ocrQuestions = OCRQuestionResult::where('ocr_record_id', $recordId)
  468. ->orderBy('question_number')
  469. ->get();
  470. \Log::info('加载OCR题目数据', [
  471. 'record_id' => $recordId,
  472. 'questions_count' => $ocrQuestions->count()
  473. ]);
  474. if ($ocrQuestions->isEmpty()) {
  475. \Log::warning('OCR记录没有题目数据', ['record_id' => $recordId]);
  476. return [];
  477. }
  478. // 创建API分析结果的映射(如果有)
  479. $analysisMap = [];
  480. if (!empty($this->paperAnalysisData['question_results'])) {
  481. foreach ($this->paperAnalysisData['question_results'] as $result) {
  482. if (isset($result['question_id'])) {
  483. $analysisMap[$result['question_id']] = $result;
  484. }
  485. }
  486. }
  487. $questions = [];
  488. foreach ($ocrQuestions as $oq) {
  489. // 获取API分析结果(如果有)
  490. $aiAnalysis = null;
  491. if (isset($analysisMap[$oq->question_number])) {
  492. $analysis = $analysisMap[$oq->question_number];
  493. $aiAnalysis = [
  494. 'analysis' => $analysis['reason'] ?? '',
  495. 'mistake_type' => $analysis['mistake_type'] ?? '',
  496. 'mistake_category' => $analysis['mistake_category'] ?? '',
  497. 'suggestions' => [$analysis['suggestions'] ?? ''],
  498. 'correct_solution' => $analysis['correct_solution'] ?? '',
  499. ];
  500. } elseif (!empty($oq->ai_feedback)) {
  501. // 如果没有API分析,使用OCR记录的AI反馈
  502. $aiAnalysis = [
  503. 'analysis' => $oq->ai_feedback,
  504. 'mistake_type' => '',
  505. 'mistake_category' => '',
  506. 'suggestions' => [$oq->ai_feedback],
  507. 'correct_solution' => '',
  508. ];
  509. }
  510. // 学生答案:优先使用老师校准的答案(manual_answer),如果没有则使用OCR识别的答案
  511. $ocrAnswer = trim($oq->student_answer ?? '');
  512. $manualAnswer = trim($oq->manual_answer ?? '');
  513. $studentAnswer = !empty($manualAnswer) ? $manualAnswer : $ocrAnswer;
  514. // 判断是否有答案(OCR识别或老师校准)
  515. $hasAnswer = !empty($studentAnswer);
  516. $displayAnswer = $hasAnswer ? ($studentAnswer ?: '空') : '未作答';
  517. // 从AI分析结果中获取正确答案和判断
  518. $correctAnswer = null;
  519. $isCorrect = false;
  520. if (isset($analysisMap[$oq->question_number])) {
  521. $analysis = $analysisMap[$oq->question_number];
  522. $correctAnswer = $analysis['correct_answer'] ?? $analysis['correct_solution'] ?? null;
  523. $isCorrect = $analysis['is_correct'] ?? false;
  524. }
  525. // 显示答案对比(如果有AI分析的正确答案)
  526. $answerComparison = null;
  527. if (!empty($correctAnswer) && $studentAnswer !== $correctAnswer && $hasAnswer) {
  528. $answerComparison = [
  529. 'student' => $studentAnswer,
  530. 'correct' => $correctAnswer
  531. ];
  532. }
  533. $questions[] = [
  534. 'id' => $oq->id,
  535. 'question_number' => $oq->question_number,
  536. 'question_bank_id' => 'ocr_' . $oq->question_number, // OCR题目没有题库ID,用前缀标识
  537. 'question_type' => 'unknown',
  538. 'question_text' => $oq->question_text ?? '题目内容缺失',
  539. 'content' => $oq->question_text ?? '题目内容缺失',
  540. 'stem' => $oq->question_text ?? '题目内容缺失',
  541. 'answer' => $correctAnswer ?? '', // 正确答案(从AI分析获取)
  542. 'reference_answer' => $correctAnswer ?? '',
  543. 'score_total' => $oq->score_total ?? null, // OCR题目的分数可能为空
  544. 'score_obtained' => $oq->score_obtained ?? null, // OCR题目的分数可能为空
  545. 'student_answer' => $displayAnswer, // 学生答案:未作答/空/实际答案(校准后)
  546. 'is_correct' => $isCorrect,
  547. 'kp_code' => $oq->kp_code ?? null, // OCR题目的知识点可能为空
  548. 'ai_analysis' => $aiAnalysis,
  549. 'answer_comparison' => $answerComparison, // 答案对比信息
  550. ];
  551. }
  552. \Log::info('OCR题目数据格式化完成', [
  553. 'record_id' => $recordId,
  554. 'formatted_questions_count' => count($questions),
  555. 'has_ai_analysis_count' => count(array_filter($questions, fn($q) => !empty($q['ai_analysis'])))
  556. ]);
  557. return $questions;
  558. } catch (\Exception $e) {
  559. \Log::error('获取OCR题目数据失败', [
  560. 'record_id' => $recordId,
  561. 'error' => $e->getMessage(),
  562. 'trace' => $e->getTraceAsString()
  563. ]);
  564. return [];
  565. }
  566. }
  567. /**
  568. * 获取题目列表(根据场景返回不同数据,包含AI分析解析)
  569. */
  570. public function getQuestions(): array
  571. {
  572. // OCR记录:从OCRQuestionResult表加载题目数据
  573. if ($this->recordType === 'ocr') {
  574. return $this->getOcrQuestions();
  575. }
  576. // 系统生成卷子:从PaperQuestion表加载题目数据
  577. $paperId = $this->recordData['paper_id'] ?? null;
  578. if (!$paperId) {
  579. return [];
  580. }
  581. try {
  582. // 直接查询题目数据
  583. $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paperId)
  584. ->orderBy('question_number')
  585. ->get();
  586. if ($paperQuestions->isEmpty()) {
  587. return [];
  588. }
  589. // 获取题库题目详情
  590. $questionBankService = app(\App\Services\QuestionBankService::class);
  591. $questionBankIds = $paperQuestions->pluck('question_bank_id')->unique()->filter()->toArray();
  592. $questionDetails = collect([]);
  593. \Log::info('准备调用题库服务', [
  594. 'question_bank_ids' => $questionBankIds,
  595. 'ids_count' => count($questionBankIds)
  596. ]);
  597. if (!empty($questionBankIds)) {
  598. try {
  599. \Log::info('开始调用题库服务getQuestionsByIds');
  600. $details = $questionBankService->getQuestionsByIds($questionBankIds);
  601. \Log::info('题库服务调用结果', [
  602. 'response' => $details,
  603. 'has_data' => isset($details['data']),
  604. 'data_type' => gettype($details['data'] ?? null)
  605. ]);
  606. if (isset($details['data']) && is_array($details['data'])) {
  607. $questionDetails = collect($details['data'])->keyBy('id');
  608. \Log::info('题库数据处理成功', [
  609. 'details_count' => $questionDetails->count(),
  610. 'first_key' => $questionDetails->keys()->first()
  611. ]);
  612. } else {
  613. \Log::warning('题库服务返回数据格式不正确', ['details' => $details]);
  614. }
  615. } catch (\Exception $e) {
  616. \Log::error('获取题库数据失败', [
  617. 'error' => $e->getMessage(),
  618. 'trace' => $e->getTraceAsString()
  619. ]);
  620. }
  621. } else {
  622. \Log::info('没有有效的题库ID');
  623. }
  624. // 构建题目数据 - 合并paper_questions表和题库API数据
  625. $questions = [];
  626. // 创建API分析结果的映射(如果有)
  627. $analysisMap = [];
  628. if (!empty($this->paperAnalysisData['question_results'])) {
  629. foreach ($this->paperAnalysisData['question_results'] as $result) {
  630. if (isset($result['question_id'])) {
  631. $analysisMap[$result['question_id']] = $result;
  632. }
  633. }
  634. }
  635. foreach ($paperQuestions as $pq) {
  636. // 从题库API获取详细数据
  637. $detail = $questionDetails->get($pq->question_bank_id);
  638. \Log::info('构建题目数据', [
  639. 'question_bank_id' => $pq->question_bank_id,
  640. 'has_detail' => $detail ? 'Yes' : 'No',
  641. 'detail_id' => $detail['id'] ?? 'null',
  642. 'stem_preview' => $detail ? substr($detail['stem'] ?? '', 50) : 'null',
  643. 'kp_code_from_db' => $pq->knowledge_point,
  644. 'kp_code_from_api' => $detail['kp_code'] ?? 'null',
  645. 'has_analysis' => isset($analysisMap[$pq->question_bank_id]) ? 'Yes' : 'No'
  646. ]);
  647. // 优先使用题库API返回的stem,如果没有则使用paper_questions中的question_text
  648. $questionText = $detail['stem'] ?? $detail['content'] ?? $pq->question_text ?? '题目内容缺失';
  649. // 优先使用题库API返回的kp_code,如果没有则使用paper_questions中的knowledge_point
  650. $kpCode = $detail['kp_code'] ?? $pq->knowledge_point ?? 'N/A';
  651. // 获取API分析结果(如果有)
  652. $aiAnalysis = null;
  653. if (isset($analysisMap[$pq->question_bank_id])) {
  654. $analysis = $analysisMap[$pq->question_bank_id];
  655. $aiAnalysis = [
  656. 'analysis' => $analysis['reason'] ?? '',
  657. 'mistake_type' => $analysis['mistake_type'] ?? '',
  658. 'mistake_category' => $analysis['mistake_category'] ?? '',
  659. 'suggestions' => [$analysis['suggestions'] ?? ''],
  660. 'correct_solution' => $analysis['correct_solution'] ?? '',
  661. ];
  662. }
  663. $questions[] = [
  664. 'id' => $pq->id,
  665. 'question_number' => $pq->question_number,
  666. 'question_bank_id' => $pq->question_bank_id,
  667. 'question_type' => $pq->question_type,
  668. 'question_text' => $questionText,
  669. 'content' => $questionText,
  670. 'stem' => $questionText,
  671. 'answer' => $detail['answer'] ?? '',
  672. 'reference_answer' => $detail['answer'] ?? '',
  673. 'score_total' => $pq->score ?? 5,
  674. 'score_obtained' => $pq->score_obtained ?? 0,
  675. 'student_answer' => $pq->student_answer ?? '未作答',
  676. 'is_correct' => $pq->is_correct ?? false,
  677. 'kp_code' => $kpCode,
  678. 'ai_analysis' => $aiAnalysis,
  679. ];
  680. }
  681. return $questions;
  682. } catch (\Exception $e) {
  683. \Log::error('获取题目列表失败', [
  684. 'paper_id' => $paperId,
  685. 'error' => $e->getMessage()
  686. ]);
  687. return [];
  688. }
  689. }
  690. /**
  691. * 重新处理OCR
  692. */
  693. public function reprocessOCR()
  694. {
  695. if (!$this->recordId) {
  696. return;
  697. }
  698. try {
  699. $record = OCRRecord::find($this->recordId);
  700. if (!$record) {
  701. throw new \Exception('记录不存在');
  702. }
  703. $ocrService = app(OCRService::class);
  704. $ocrService->reprocess($record);
  705. Notification::make()
  706. ->title('已提交重新处理')
  707. ->body('OCR识别任务已重新加入队列')
  708. ->success()
  709. ->send();
  710. $this->loadAnalysisData(); // 刷新数据
  711. } catch (\Exception $e) {
  712. Notification::make()
  713. ->title('操作失败')
  714. ->body($e->getMessage())
  715. ->danger()
  716. ->send();
  717. }
  718. }
  719. /**
  720. * 重新提交分析
  721. */
  722. public function reanalyze()
  723. {
  724. if (!$this->recordId) {
  725. return;
  726. }
  727. try {
  728. $record = OCRRecord::find($this->recordId);
  729. if (!$record) {
  730. throw new \Exception('记录不存在');
  731. }
  732. // 获取当前的题目数据(包含可能的人工校准)
  733. $questions = OCRQuestionResult::where('ocr_record_id', $this->recordId)
  734. ->orderBy('question_number')
  735. ->get()
  736. ->map(function ($q) {
  737. return [
  738. 'question_number' => $q->question_number,
  739. 'content' => $q->question_text,
  740. 'student_answer' => $q->student_answer,
  741. 'manual_answer' => $q->manual_answer,
  742. 'answer_verified' => $q->answer_verified,
  743. 'confidence' => $q->score_confidence,
  744. 'kp_code' => $q->kp_code,
  745. 'score_value' => $q->score_value,
  746. ];
  747. })->toArray();
  748. if (empty($questions)) {
  749. throw new \Exception('没有可分析的题目数据');
  750. }
  751. // 构造分析请求数据
  752. $analysisData = [
  753. 'exam_id' => $record->exam_id,
  754. 'student_id' => $record->student_id,
  755. 'ocr_record_id' => $record->id,
  756. 'teacher_name' => auth()->user()->name ?? 'Teacher',
  757. 'analysis_type' => 'mastery',
  758. 'questions' => array_map(function($q) {
  759. // 优先使用人工校准的答案
  760. $studentAnswer = $q['student_answer'] ?? '';
  761. if (isset($q['manual_answer']) && !empty($q['manual_answer'])) {
  762. $studentAnswer = $q['manual_answer'];
  763. }
  764. return [
  765. 'question_id' => $q['question_number'],
  766. 'question_number' => (string)$q['question_number'],
  767. 'kp_code' => $q['kp_code'] ?? null,
  768. 'score_value' => $q['score_value'] ?? 0,
  769. 'student_answer' => $studentAnswer,
  770. 'ocr_confidence' => $q['confidence'] ?? 0,
  771. 'question_text' => $q['content'] ?? '',
  772. 'teacher_validated' => $q['answer_verified'] ?? false,
  773. ];
  774. }, $questions)
  775. ];
  776. // 调用分析服务
  777. $learningService = app(LearningAnalyticsService::class);
  778. $result = $learningService->submitOCRAnalysis($analysisData);
  779. if (isset($result['success']) && $result['success']) {
  780. $record->update([
  781. 'ai_analyzed_at' => now(),
  782. 'ai_analysis_count' => ($record->ai_analysis_count ?? 0) + 1
  783. ]);
  784. Notification::make()
  785. ->title('分析请求已提交')
  786. ->body('系统正在重新分析试卷,请稍后刷新查看结果')
  787. ->success()
  788. ->send();
  789. $this->loadAnalysisData(); // 刷新数据
  790. } else {
  791. throw new \Exception($result['message'] ?? '提交分析失败');
  792. }
  793. } catch (\Exception $e) {
  794. Notification::make()
  795. ->title('操作失败')
  796. ->body($e->getMessage())
  797. ->danger()
  798. ->send();
  799. }
  800. }
  801. /**
  802. * 从当前试卷数据中提取知识点信息
  803. */
  804. protected function extractKnowledgePointsFromCurrentPaper(): array
  805. {
  806. $knowledgePoints = [];
  807. $questions = $this->getQuestions();
  808. foreach ($questions as $question) {
  809. $kpCode = $question['kp_code'] ?? null;
  810. if ($kpCode && $kpCode !== 'N/A') {
  811. $isCorrect = $question['is_correct'] ?? false;
  812. if (!isset($knowledgePoints[$kpCode])) {
  813. $knowledgePoints[$kpCode] = [
  814. 'kp_code' => $kpCode,
  815. 'name' => $kpCode,
  816. 'total_attempts' => 0,
  817. 'correct_attempts' => 0,
  818. 'mastery_level' => 0,
  819. 'accuracy_rate' => 0
  820. ];
  821. }
  822. $knowledgePoints[$kpCode]['total_attempts']++;
  823. if ($isCorrect) {
  824. $knowledgePoints[$kpCode]['correct_attempts']++;
  825. }
  826. }
  827. }
  828. // 计算准确率和掌握度
  829. foreach ($knowledgePoints as &$kp) {
  830. if ($kp['total_attempts'] > 0) {
  831. $kp['accuracy_rate'] = $kp['correct_attempts'] / $kp['total_attempts'];
  832. $kp['mastery_level'] = $kp['accuracy_rate'];
  833. }
  834. }
  835. return array_values($knowledgePoints);
  836. }
  837. /**
  838. * 获取当前试卷的知识点掌握情况
  839. */
  840. protected function getCurrentPaperKnowledgePoints(): array
  841. {
  842. // 首先尝试从当前试卷数据中提取
  843. $currentPaperKps = $this->extractKnowledgePointsFromCurrentPaper();
  844. // 如果有历史分析数据,合并以提供更准确的掌握度
  845. if (!empty($this->analysisData['knowledge_points'])) {
  846. $historicalKps = $this->analysisData['knowledge_points'];
  847. foreach ($currentPaperKps as &$currentKp) {
  848. $kpCode = $currentKp['kp_code'];
  849. // 查找历史数据
  850. $historicalData = collect($historicalKps)->firstWhere('kp_code', $kpCode);
  851. if ($historicalData && isset($historicalData['mastery_level'])) {
  852. // 使用历史数据的掌握度,但保留试卷的实际表现
  853. $currentKp['historical_mastery_level'] = $historicalData['mastery_level'];
  854. $currentKp['total_attempts'] = $historicalData['total_attempts'] ?? $currentKp['total_attempts'];
  855. $currentKp['correct_attempts'] = $historicalData['correct_attempts'] ?? $currentKp['correct_attempts'];
  856. $currentKp['accuracy_rate'] = $historicalData['accuracy_rate'] ?? $currentKp['accuracy_rate'];
  857. // 优先使用历史的掌握度,但考虑试卷表现做微调
  858. $paperPerformance = $currentKp['accuracy_rate'];
  859. $historicalPerformance = $historicalData['mastery_level'] ?? 0;
  860. // 综合计算:70%历史 + 30%本试卷
  861. $currentKp['mastery_level'] = ($historicalPerformance * 0.7 + $paperPerformance * 0.3);
  862. }
  863. }
  864. }
  865. return $currentPaperKps;
  866. }
  867. /**
  868. * 将API的分析结果同步到题目数据和数据库
  869. */
  870. protected function syncApiAnalysisToQuestions(array $questionResults)
  871. {
  872. try {
  873. \Log::info('开始同步API分析结果到题目数据', [
  874. 'paper_id' => $this->paperId,
  875. 'question_results_count' => count($questionResults)
  876. ]);
  877. // 创建question_id到分析结果的映射
  878. $analysisMap = [];
  879. foreach ($questionResults as $result) {
  880. $questionId = $result['question_id'] ?? null;
  881. if ($questionId) {
  882. $analysisMap[$questionId] = $result;
  883. }
  884. }
  885. // 获取当前试卷的题目
  886. $paper = \App\Models\Paper::find($this->paperId);
  887. if ($paper) {
  888. $paperQuestions = $paper->questions()->get();
  889. $updatedCount = 0;
  890. foreach ($paperQuestions as $pq) {
  891. // 查找对应的API分析结果
  892. if (isset($analysisMap[$pq->question_bank_id])) {
  893. $analysis = $analysisMap[$pq->question_bank_id];
  894. // 更新数据库字段
  895. $pq->is_correct = $analysis['correct'] ?? false;
  896. $pq->score_obtained = $analysis['score'] ?? 0;
  897. $pq->save();
  898. $updatedCount++;
  899. \Log::info('更新题目分析结果', [
  900. 'question_bank_id' => $pq->question_bank_id,
  901. 'is_correct' => $pq->is_correct,
  902. 'score_obtained' => $pq->score_obtained
  903. ]);
  904. }
  905. }
  906. \Log::info('API分析结果同步完成', [
  907. 'updated_count' => $updatedCount,
  908. 'total_questions' => $paperQuestions->count()
  909. ]);
  910. // 刷新recordData中的questions数据
  911. $this->recordData['questions'] = $this->getQuestions();
  912. }
  913. } catch (\Exception $e) {
  914. \Log::error('同步API分析结果失败', [
  915. 'paper_id' => $this->paperId,
  916. 'error' => $e->getMessage()
  917. ]);
  918. }
  919. }
  920. /**
  921. * 提交OCR记录到AI分析API(与系统卷子使用统一接口)
  922. */
  923. protected function submitOcrForAnalysis($record)
  924. {
  925. try {
  926. // 获取OCR题目结果(使用校准后的答案)
  927. $ocrQuestions = OCRQuestionResult::where('ocr_record_id', $record->id)
  928. ->orderBy('question_number')
  929. ->get();
  930. if ($ocrQuestions->isEmpty()) {
  931. \Log::warning('OCR记录没有题目,无法提交分析', ['record_id' => $record->id]);
  932. return;
  933. }
  934. // 构建答题数据(与系统卷子格式一致)
  935. $answers = [];
  936. foreach ($ocrQuestions as $oq) {
  937. // 使用校准后的答案(manual_answer),如果没有则使用OCR识别的答案
  938. $studentAnswer = !empty(trim($oq->manual_answer ?? ''))
  939. ? trim($oq->manual_answer)
  940. : trim($oq->student_answer ?? '');
  941. $answers[] = [
  942. 'question_bank_id' => 'ocr_q' . $oq->question_number, // OCR题目没有题库ID,生成临时ID
  943. 'question_text' => $oq->question_text ?? '', // 添加题目内容
  944. 'student_answer' => $studentAnswer,
  945. 'is_correct' => null, // 让AI分析判断
  946. 'score' => null, // OCR题目可能没有分数
  947. 'max_score' => $oq->score_total ?? null,
  948. 'kp_code' => $oq->kp_code ?? null,
  949. ];
  950. }
  951. // 使用与系统卷子相同的接口提交
  952. $submissionData = [
  953. 'paper_id' => 'ocr_' . $record->id, // OCR记录ID作为paper_id
  954. 'answers' => $answers,
  955. ];
  956. \Log::info('提交OCR数据到AI分析(统一接口)', [
  957. 'record_id' => $record->id,
  958. 'student_id' => $record->student_id,
  959. 'question_count' => count($answers),
  960. 'api_endpoint' => '/api/v1/attempts/batch/student/' . $record->student_id
  961. ]);
  962. // 调用学习分析服务(与系统卷子使用相同的方法)
  963. $learningService = app(\App\Services\LearningAnalyticsService::class);
  964. $response = $learningService->submitBatchAttempts($record->student_id, $submissionData);
  965. if (!empty($response) && !isset($response['error'])) {
  966. // 从响应中获取analysis_id(如果API返回)
  967. $analysisId = $response['analysis_id'] ?? $response['data']['analysis_id'] ?? ('batch_' . $record->id . '_' . time());
  968. // 更新OCR记录的analysis_id
  969. $record->analysis_id = $analysisId;
  970. $record->save();
  971. \Log::info('OCR分析提交成功(统一接口)', [
  972. 'record_id' => $record->id,
  973. 'analysis_id' => $analysisId,
  974. 'response_keys' => array_keys($response)
  975. ]);
  976. // 更新recordData
  977. $this->recordData['analysis_id'] = $analysisId;
  978. } else {
  979. \Log::error('OCR分析提交失败', [
  980. 'record_id' => $record->id,
  981. 'response' => $response
  982. ]);
  983. }
  984. } catch (\Exception $e) {
  985. \Log::error('提交OCR分析异常', [
  986. 'record_id' => $record->id,
  987. 'error' => $e->getMessage(),
  988. 'trace' => $e->getTraceAsString()
  989. ]);
  990. }
  991. }
  992. }