ExamAnalysis.php 46 KB

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