ExamAnalysis.php 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  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. $solution = null;
  498. if (isset($analysisMap[$oq->question_number])) {
  499. $analysis = $analysisMap[$oq->question_number];
  500. $correctAnswer = $analysis['correct_answer'] ?? $analysis['correct_solution'] ?? null;
  501. $isCorrect = $analysis['is_correct'] ?? false;
  502. $solution = $analysis['correct_solution'] ?? null;
  503. }
  504. // 显示答案对比(如果有AI分析的正确答案)
  505. $answerComparison = null;
  506. if (!empty($correctAnswer) && $studentAnswer !== $correctAnswer && $hasAnswer) {
  507. $answerComparison = [
  508. 'student' => $studentAnswer,
  509. 'correct' => $correctAnswer
  510. ];
  511. }
  512. $questions[] = [
  513. 'id' => $oq->id,
  514. 'question_number' => $oq->question_number,
  515. 'question_bank_id' => 'ocr_' . $oq->question_number, // OCR题目没有题库ID,用前缀标识
  516. 'question_type' => 'unknown',
  517. 'question_text' => $oq->question_text ?? '题目内容缺失',
  518. 'content' => $oq->question_text ?? '题目内容缺失',
  519. 'stem' => $oq->question_text ?? '题目内容缺失',
  520. 'answer' => $correctAnswer ?? '', // 正确答案(从AI分析获取)
  521. 'reference_answer' => $correctAnswer ?? '',
  522. 'solution' => $solution, // 解题步骤
  523. 'score_total' => $oq->score_total ?? null, // OCR题目的分数可能为空
  524. 'score_obtained' => $oq->score_obtained ?? null, // OCR题目的分数可能为空
  525. 'student_answer' => $displayAnswer, // 学生答案:未作答/空/实际答案(校准后)
  526. 'is_correct' => $isCorrect,
  527. 'kp_code' => $oq->kp_code ?? null, // OCR题目的知识点可能为空
  528. 'ai_analysis' => $aiAnalysis,
  529. 'answer_comparison' => $answerComparison, // 答案对比信息
  530. ];
  531. }
  532. \Log::info('OCR题目数据格式化完成', [
  533. 'record_id' => $recordId,
  534. 'formatted_questions_count' => count($questions),
  535. 'has_ai_analysis_count' => count(array_filter($questions, fn($q) => !empty($q['ai_analysis'])))
  536. ]);
  537. return $questions;
  538. } catch (\Exception $e) {
  539. \Log::error('获取OCR题目数据失败', [
  540. 'record_id' => $recordId,
  541. 'error' => $e->getMessage(),
  542. 'trace' => $e->getTraceAsString()
  543. ]);
  544. return [];
  545. }
  546. }
  547. /**
  548. * 获取题目列表(根据场景返回不同数据,包含AI分析解析)
  549. */
  550. public function getQuestions(): array
  551. {
  552. // OCR记录:从OCRQuestionResult表加载题目数据
  553. if ($this->recordType === 'ocr') {
  554. $questions = $this->getOcrQuestions();
  555. // 丰富知识点信息
  556. return $this->enrichQuestionsWithKnowledgePoints($questions);
  557. }
  558. // 系统生成卷子:从PaperQuestion表加载题目数据
  559. $paperId = $this->recordData['paper_id'] ?? null;
  560. if (!$paperId) {
  561. return [];
  562. }
  563. try {
  564. // 直接查询题目数据
  565. $paperQuestions = \App\Models\PaperQuestion::where('paper_id', $paperId)
  566. ->orderBy('question_number')
  567. ->get();
  568. if ($paperQuestions->isEmpty()) {
  569. return [];
  570. }
  571. // 获取题库题目详情
  572. $questionBankService = app(\App\Services\QuestionBankService::class);
  573. $questionBankIds = $paperQuestions->pluck('question_bank_id')->unique()->filter()->toArray();
  574. $questionDetails = collect([]);
  575. \Log::info('准备调用题库服务', [
  576. 'question_bank_ids' => $questionBankIds,
  577. 'ids_count' => count($questionBankIds)
  578. ]);
  579. if (!empty($questionBankIds)) {
  580. try {
  581. \Log::info('开始调用题库服务getQuestionsByIds');
  582. $details = $questionBankService->getQuestionsByIds($questionBankIds);
  583. \Log::info('题库服务调用结果', [
  584. 'response' => $details,
  585. 'has_data' => isset($details['data']),
  586. 'data_type' => gettype($details['data'] ?? null)
  587. ]);
  588. if (isset($details['data']) && is_array($details['data'])) {
  589. $questionDetails = collect($details['data'])->keyBy('id');
  590. \Log::info('题库数据处理成功', [
  591. 'details_count' => $questionDetails->count(),
  592. 'first_key' => $questionDetails->keys()->first()
  593. ]);
  594. } else {
  595. \Log::warning('题库服务返回数据格式不正确', ['details' => $details]);
  596. }
  597. } catch (\Exception $e) {
  598. \Log::error('获取题库数据失败', [
  599. 'error' => $e->getMessage(),
  600. 'trace' => $e->getTraceAsString()
  601. ]);
  602. }
  603. } else {
  604. \Log::info('没有有效的题库ID');
  605. }
  606. // 构建题目数据 - 合并paper_questions表和题库API数据
  607. $questions = [];
  608. // 创建API分析结果的映射(如果有)
  609. $analysisMap = [];
  610. if (!empty($this->paperAnalysisData['question_results'])) {
  611. foreach ($this->paperAnalysisData['question_results'] as $result) {
  612. if (isset($result['question_id'])) {
  613. $analysisMap[$result['question_id']] = $result;
  614. }
  615. }
  616. }
  617. foreach ($paperQuestions as $pq) {
  618. // 从题库API获取详细数据
  619. $detail = $questionDetails->get($pq->question_bank_id);
  620. \Log::info('构建题目数据', [
  621. 'question_bank_id' => $pq->question_bank_id,
  622. 'has_detail' => $detail ? 'Yes' : 'No',
  623. 'detail_id' => $detail['id'] ?? 'null',
  624. 'stem_preview' => $detail ? substr($detail['stem'] ?? '', 50) : 'null',
  625. 'kp_code_from_db' => $pq->knowledge_point,
  626. 'kp_code_from_api' => $detail['kp_code'] ?? 'null',
  627. 'has_analysis' => isset($analysisMap[$pq->question_bank_id]) ? 'Yes' : 'No'
  628. ]);
  629. // 优先使用题库API返回的stem,如果没有则使用paper_questions中的question_text
  630. $questionText = $detail['stem'] ?? $detail['content'] ?? $pq->question_text ?? '题目内容缺失';
  631. // 优先使用题库API返回的kp_code,如果没有则使用paper_questions中的knowledge_point
  632. $kpCode = $detail['kp_code'] ?? $pq->knowledge_point ?? 'N/A';
  633. // 获取API分析结果(如果有)
  634. $aiAnalysis = null;
  635. if (isset($analysisMap[$pq->question_bank_id])) {
  636. $analysis = $analysisMap[$pq->question_bank_id];
  637. $aiAnalysis = [
  638. 'analysis' => $analysis['reason'] ?? '',
  639. 'mistake_type' => $analysis['mistake_type'] ?? '',
  640. 'mistake_category' => $analysis['mistake_category'] ?? '',
  641. 'suggestions' => [$analysis['suggestions'] ?? ''],
  642. 'correct_solution' => $analysis['correct_solution'] ?? '',
  643. ];
  644. }
  645. // 获取解题步骤solution(从Question Bank或AI分析)
  646. $solution = $detail['solution'] ?? $detail['correct_solution'] ?? null;
  647. if (!$solution && isset($analysisMap[$pq->question_bank_id])) {
  648. $analysis = $analysisMap[$pq->question_bank_id];
  649. $solution = $analysis['correct_solution'] ?? null;
  650. }
  651. $questions[] = [
  652. 'id' => $pq->id,
  653. 'question_number' => $pq->question_number,
  654. 'question_bank_id' => $pq->question_bank_id,
  655. 'question_type' => $pq->question_type,
  656. 'question_text' => $questionText,
  657. 'content' => $questionText,
  658. 'stem' => $questionText,
  659. 'answer' => $detail['answer'] ?? '',
  660. 'reference_answer' => $detail['answer'] ?? '',
  661. 'solution' => $solution, // 解题步骤
  662. 'score_total' => $pq->score ?? 5,
  663. 'score_obtained' => $pq->score_obtained ?? 0,
  664. 'student_answer' => '老师已评分', // 隐藏学生答案,显示老师评分状态
  665. 'is_correct' => $pq->is_correct ?? false,
  666. 'kp_code' => $kpCode,
  667. 'ai_analysis' => $aiAnalysis,
  668. ];
  669. }
  670. // 丰富知识点信息
  671. return $this->enrichQuestionsWithKnowledgePoints($questions);
  672. } catch (\Exception $e) {
  673. \Log::error('获取题目列表失败', [
  674. 'paper_id' => $paperId,
  675. 'error' => $e->getMessage()
  676. ]);
  677. return [];
  678. }
  679. }
  680. /**
  681. * 丰富题目数据,添加知识点详细信息
  682. */
  683. protected function enrichQuestionsWithKnowledgePoints(array $questions): array
  684. {
  685. // 收集所有知识点代码
  686. $kpCodes = [];
  687. foreach ($questions as $question) {
  688. if (!empty($question['kp_code']) && $question['kp_code'] !== 'N/A') {
  689. $kpCodes[] = $question['kp_code'];
  690. }
  691. }
  692. if (empty($kpCodes)) {
  693. return $questions;
  694. }
  695. // 获取知识点详细信息
  696. $knowledgeService = app(\App\Services\KnowledgeGraphService::class);
  697. $knowledgePointsList = $knowledgeService->listKnowledgePoints(1, 1000);
  698. $knowledgePoints = [];
  699. if (isset($knowledgePointsList['data']) && !empty($knowledgePointsList['data'])) {
  700. foreach ($knowledgePointsList['data'] as $kp) {
  701. $knowledgePoints[$kp['kp_code']] = $kp;
  702. }
  703. }
  704. // 获取技能点信息
  705. $skillsList = [];
  706. foreach ($kpCodes as $kpCode) {
  707. $skills = $knowledgeService->getSkillsByKnowledgePoint($kpCode);
  708. if (!empty($skills)) {
  709. $skillsList[$kpCode] = $skills;
  710. }
  711. }
  712. // 丰富题目数据
  713. foreach ($questions as &$question) {
  714. $kpCode = $question['kp_code'] ?? null;
  715. if ($kpCode && isset($knowledgePoints[$kpCode])) {
  716. $kp = $knowledgePoints[$kpCode];
  717. $question['knowledge_point'] = [
  718. 'code' => $kpCode,
  719. 'name' => $kp['cn_name'] ?? $kpCode,
  720. 'category' => $kp['category'] ?? '',
  721. 'phase' => $kp['phase'] ?? '',
  722. 'grade' => $kp['grade'] ?? '',
  723. 'description' => $kp['description'] ?? '',
  724. ];
  725. // 添加技能点
  726. if (isset($skillsList[$kpCode])) {
  727. $question['knowledge_point']['skills'] = $skillsList[$kpCode];
  728. }
  729. }
  730. }
  731. return $questions;
  732. }
  733. /**
  734. * 重新处理OCR
  735. */
  736. public function reprocessOCR()
  737. {
  738. if (!$this->recordId) {
  739. return;
  740. }
  741. try {
  742. $record = OCRRecord::find($this->recordId);
  743. if (!$record) {
  744. throw new \Exception('记录不存在');
  745. }
  746. $ocrService = app(OCRService::class);
  747. $ocrService->reprocess($record);
  748. Notification::make()
  749. ->title('已提交重新处理')
  750. ->body('OCR识别任务已重新加入队列')
  751. ->success()
  752. ->send();
  753. $this->loadAnalysisData(); // 刷新数据
  754. } catch (\Exception $e) {
  755. Notification::make()
  756. ->title('操作失败')
  757. ->body($e->getMessage())
  758. ->danger()
  759. ->send();
  760. }
  761. }
  762. /**
  763. * 重新提交分析
  764. */
  765. public function reanalyze()
  766. {
  767. if (!$this->recordId) {
  768. return;
  769. }
  770. try {
  771. $record = OCRRecord::find($this->recordId);
  772. if (!$record) {
  773. throw new \Exception('记录不存在');
  774. }
  775. // 获取当前的题目数据(包含可能的人工校准)
  776. $questions = OCRQuestionResult::where('ocr_record_id', $this->recordId)
  777. ->orderBy('question_number')
  778. ->get()
  779. ->map(function ($q) {
  780. return [
  781. 'question_number' => $q->question_number,
  782. 'content' => $q->question_text,
  783. 'student_answer' => $q->student_answer,
  784. 'manual_answer' => $q->manual_answer,
  785. 'answer_verified' => $q->answer_verified,
  786. 'confidence' => $q->score_confidence,
  787. 'kp_code' => $q->kp_code,
  788. 'score_value' => $q->score_value,
  789. ];
  790. })->toArray();
  791. if (empty($questions)) {
  792. throw new \Exception('没有可分析的题目数据');
  793. }
  794. // 构造分析请求数据
  795. $analysisData = [
  796. 'exam_id' => $record->exam_id,
  797. 'student_id' => $record->student_id,
  798. 'ocr_record_id' => $record->id,
  799. 'teacher_name' => auth()->user()->name ?? 'Teacher',
  800. 'analysis_type' => 'mastery',
  801. 'questions' => array_map(function($q) {
  802. // 优先使用人工校准的答案
  803. $studentAnswer = $q['student_answer'] ?? '';
  804. if (isset($q['manual_answer']) && !empty($q['manual_answer'])) {
  805. $studentAnswer = $q['manual_answer'];
  806. }
  807. return [
  808. 'question_id' => $q['question_number'],
  809. 'question_number' => (string)$q['question_number'],
  810. 'kp_code' => $q['kp_code'] ?? null,
  811. 'score_value' => $q['score_value'] ?? 0,
  812. 'student_answer' => $studentAnswer,
  813. 'ocr_confidence' => $q['confidence'] ?? 0,
  814. 'question_text' => $q['content'] ?? '',
  815. 'teacher_validated' => $q['answer_verified'] ?? false,
  816. ];
  817. }, $questions)
  818. ];
  819. // 调用分析服务
  820. $learningService = app(LearningAnalyticsService::class);
  821. $result = $learningService->submitOCRAnalysis($analysisData);
  822. if (isset($result['success']) && $result['success']) {
  823. $record->update([
  824. 'ai_analyzed_at' => now(),
  825. 'ai_analysis_count' => ($record->ai_analysis_count ?? 0) + 1
  826. ]);
  827. Notification::make()
  828. ->title('分析请求已提交')
  829. ->body('系统正在重新分析试卷,请稍后刷新查看结果')
  830. ->success()
  831. ->send();
  832. $this->loadAnalysisData(); // 刷新数据
  833. } else {
  834. throw new \Exception($result['message'] ?? '提交分析失败');
  835. }
  836. } catch (\Exception $e) {
  837. Notification::make()
  838. ->title('操作失败')
  839. ->body($e->getMessage())
  840. ->danger()
  841. ->send();
  842. }
  843. }
  844. /**
  845. * 从当前试卷数据中提取知识点信息
  846. */
  847. protected function extractKnowledgePointsFromCurrentPaper(): array
  848. {
  849. $knowledgePoints = [];
  850. $questions = $this->getQuestions();
  851. foreach ($questions as $question) {
  852. $kpCode = $question['kp_code'] ?? null;
  853. if ($kpCode && $kpCode !== 'N/A') {
  854. $isCorrect = $question['is_correct'] ?? false;
  855. if (!isset($knowledgePoints[$kpCode])) {
  856. $knowledgePoints[$kpCode] = [
  857. 'kp_code' => $kpCode,
  858. 'name' => $kpCode,
  859. 'total_attempts' => 0,
  860. 'correct_attempts' => 0,
  861. 'mastery_level' => 0,
  862. 'accuracy_rate' => 0
  863. ];
  864. }
  865. $knowledgePoints[$kpCode]['total_attempts']++;
  866. if ($isCorrect) {
  867. $knowledgePoints[$kpCode]['correct_attempts']++;
  868. }
  869. }
  870. }
  871. // 计算准确率和掌握度
  872. foreach ($knowledgePoints as &$kp) {
  873. if ($kp['total_attempts'] > 0) {
  874. $kp['accuracy_rate'] = $kp['correct_attempts'] / $kp['total_attempts'];
  875. $kp['mastery_level'] = $kp['accuracy_rate'];
  876. }
  877. }
  878. return array_values($knowledgePoints);
  879. }
  880. /**
  881. * 获取当前试卷的知识点掌握情况
  882. */
  883. protected function getCurrentPaperKnowledgePoints(): array
  884. {
  885. // 首先尝试从当前试卷数据中提取
  886. $currentPaperKps = $this->extractKnowledgePointsFromCurrentPaper();
  887. // 如果有历史分析数据,合并以提供更准确的掌握度
  888. if (!empty($this->analysisData['knowledge_points'])) {
  889. $historicalKps = $this->analysisData['knowledge_points'];
  890. foreach ($currentPaperKps as &$currentKp) {
  891. $kpCode = $currentKp['kp_code'];
  892. // 查找历史数据
  893. $historicalData = collect($historicalKps)->firstWhere('kp_code', $kpCode);
  894. if ($historicalData && isset($historicalData['mastery_level'])) {
  895. // 使用历史数据的掌握度,但保留试卷的实际表现
  896. $currentKp['historical_mastery_level'] = $historicalData['mastery_level'];
  897. $currentKp['total_attempts'] = $historicalData['total_attempts'] ?? $currentKp['total_attempts'];
  898. $currentKp['correct_attempts'] = $historicalData['correct_attempts'] ?? $currentKp['correct_attempts'];
  899. $currentKp['accuracy_rate'] = $historicalData['accuracy_rate'] ?? $currentKp['accuracy_rate'];
  900. // 优先使用历史的掌握度,但考虑试卷表现做微调
  901. $paperPerformance = $currentKp['accuracy_rate'];
  902. $historicalPerformance = $historicalData['mastery_level'] ?? 0;
  903. // 综合计算:70%历史 + 30%本试卷
  904. $currentKp['mastery_level'] = ($historicalPerformance * 0.7 + $paperPerformance * 0.3);
  905. }
  906. }
  907. }
  908. return $currentPaperKps;
  909. }
  910. /**
  911. * 将API的分析结果同步到题目数据和数据库
  912. */
  913. protected function syncApiAnalysisToQuestions(array $questionResults)
  914. {
  915. try {
  916. \Log::info('开始同步API分析结果到题目数据', [
  917. 'paper_id' => $this->paperId,
  918. 'question_results_count' => count($questionResults)
  919. ]);
  920. // 创建question_id到分析结果的映射
  921. $analysisMap = [];
  922. foreach ($questionResults as $result) {
  923. $questionId = $result['question_id'] ?? null;
  924. if ($questionId) {
  925. $analysisMap[$questionId] = $result;
  926. }
  927. }
  928. // 获取当前试卷的题目
  929. $paper = \App\Models\Paper::find($this->paperId);
  930. if ($paper) {
  931. $paperQuestions = $paper->questions()->get();
  932. $updatedCount = 0;
  933. foreach ($paperQuestions as $pq) {
  934. // 查找对应的API分析结果
  935. if (isset($analysisMap[$pq->question_bank_id])) {
  936. $analysis = $analysisMap[$pq->question_bank_id];
  937. // 更新数据库字段
  938. $pq->is_correct = $analysis['correct'] ?? false;
  939. $pq->score_obtained = $analysis['score'] ?? 0;
  940. $pq->save();
  941. $updatedCount++;
  942. \Log::info('更新题目分析结果', [
  943. 'question_bank_id' => $pq->question_bank_id,
  944. 'is_correct' => $pq->is_correct,
  945. 'score_obtained' => $pq->score_obtained
  946. ]);
  947. }
  948. }
  949. \Log::info('API分析结果同步完成', [
  950. 'updated_count' => $updatedCount,
  951. 'total_questions' => $paperQuestions->count()
  952. ]);
  953. // 刷新recordData中的questions数据
  954. $this->recordData['questions'] = $this->getQuestions();
  955. }
  956. } catch (\Exception $e) {
  957. \Log::error('同步API分析结果失败', [
  958. 'paper_id' => $this->paperId,
  959. 'error' => $e->getMessage()
  960. ]);
  961. }
  962. }
  963. /**
  964. * 提交OCR记录到AI分析API(与系统卷子使用统一接口)
  965. */
  966. protected function submitOcrForAnalysis($record)
  967. {
  968. try {
  969. // 获取OCR题目结果(使用校准后的答案)
  970. $ocrQuestions = OCRQuestionResult::where('ocr_record_id', $record->id)
  971. ->orderBy('question_number')
  972. ->get();
  973. if ($ocrQuestions->isEmpty()) {
  974. \Log::warning('OCR记录没有题目,无法提交分析', ['record_id' => $record->id]);
  975. return;
  976. }
  977. // 构建答题数据(与系统卷子格式一致)
  978. $answers = [];
  979. foreach ($ocrQuestions as $oq) {
  980. // 使用校准后的答案(manual_answer),如果没有则使用OCR识别的答案
  981. $studentAnswer = !empty(trim($oq->manual_answer ?? ''))
  982. ? trim($oq->manual_answer)
  983. : trim($oq->student_answer ?? '');
  984. $answers[] = [
  985. 'question_bank_id' => 'ocr_q' . $oq->question_number, // OCR题目没有题库ID,生成临时ID
  986. 'question_text' => $oq->question_text ?? '', // 添加题目内容
  987. 'student_answer' => $studentAnswer,
  988. 'is_correct' => null, // 让AI分析判断
  989. 'score' => null, // OCR题目可能没有分数
  990. 'max_score' => $oq->score_total ?? null,
  991. 'kp_code' => $oq->kp_code ?? null,
  992. ];
  993. }
  994. // 使用与系统卷子相同的接口提交
  995. $submissionData = [
  996. 'paper_id' => 'ocr_' . $record->id, // OCR记录ID作为paper_id
  997. 'answers' => $answers,
  998. ];
  999. \Log::info('提交OCR数据到AI分析(统一接口)', [
  1000. 'record_id' => $record->id,
  1001. 'student_id' => $record->student_id,
  1002. 'question_count' => count($answers),
  1003. 'api_endpoint' => '/api/v1/attempts/batch/student/' . $record->student_id
  1004. ]);
  1005. // 调用学习分析服务(与系统卷子使用相同的方法)
  1006. $learningService = app(\App\Services\LearningAnalyticsService::class);
  1007. $response = $learningService->submitBatchAttempts($record->student_id, $submissionData);
  1008. if (!empty($response) && !isset($response['error'])) {
  1009. // 从响应中获取analysis_id(如果API返回)
  1010. $analysisId = $response['analysis_id'] ?? $response['data']['analysis_id'] ?? ('batch_' . $record->id . '_' . time());
  1011. // 更新OCR记录的analysis_id
  1012. $record->analysis_id = $analysisId;
  1013. $record->save();
  1014. \Log::info('OCR分析提交成功(统一接口)', [
  1015. 'record_id' => $record->id,
  1016. 'analysis_id' => $analysisId,
  1017. 'response_keys' => array_keys($response)
  1018. ]);
  1019. // 更新recordData
  1020. $this->recordData['analysis_id'] = $analysisId;
  1021. } else {
  1022. \Log::error('OCR分析提交失败', [
  1023. 'record_id' => $record->id,
  1024. 'response' => $response
  1025. ]);
  1026. }
  1027. } catch (\Exception $e) {
  1028. \Log::error('提交OCR分析异常', [
  1029. 'record_id' => $record->id,
  1030. 'error' => $e->getMessage(),
  1031. 'trace' => $e->getTraceAsString()
  1032. ]);
  1033. }
  1034. }
  1035. }