ExamAnalysis.php 45 KB

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