IntelligentExamController.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use App\Models\Paper;
  5. use App\Models\PaperQuestion;
  6. use App\Services\LearningAnalyticsService;
  7. use App\Services\ExamPdfExportService;
  8. use App\Services\QuestionBankService;
  9. use Illuminate\Http\JsonResponse;
  10. use Illuminate\Http\Request;
  11. use Illuminate\Support\Facades\Log;
  12. use Illuminate\Support\Facades\URL;
  13. class IntelligentExamController extends Controller
  14. {
  15. private LearningAnalyticsService $learningAnalyticsService;
  16. private QuestionBankService $questionBankService;
  17. private ExamPdfExportService $pdfExportService;
  18. public function __construct(
  19. LearningAnalyticsService $learningAnalyticsService,
  20. QuestionBankService $questionBankService,
  21. ExamPdfExportService $pdfExportService
  22. ) {
  23. $this->learningAnalyticsService = $learningAnalyticsService;
  24. $this->questionBankService = $questionBankService;
  25. $this->pdfExportService = $pdfExportService;
  26. }
  27. /**
  28. * 外部API:生成智能试卷,保存并返回 PDF/判卷链接
  29. */
  30. public function store(Request $request): JsonResponse
  31. {
  32. $normalized = $this->normalizePayload($request->all());
  33. $validator = validator($normalized, [
  34. 'student_id' => 'required|string',
  35. 'teacher_id' => 'required|string',
  36. 'paper_name' => 'nullable|string|max:255',
  37. 'grade' => 'nullable|string|max:50',
  38. 'total_questions' => 'required|integer|min:6|max:100',
  39. 'difficulty_category' => 'nullable|string',
  40. 'kp_codes' => 'nullable|array',
  41. 'kp_codes.*' => 'string',
  42. 'skills' => 'array',
  43. 'skills.*' => 'string',
  44. 'question_type_ratio' => 'array',
  45. 'difficulty_ratio' => 'array',
  46. 'total_score' => 'nullable|numeric|min:1|max:1000',
  47. ]);
  48. if ($validator->fails()) {
  49. return response()->json([
  50. 'success' => false,
  51. 'message' => '参数错误',
  52. 'errors' => $validator->errors()->toArray(),
  53. ], 422);
  54. }
  55. $data = $validator->validated();
  56. // 确保 kp_codes 是数组,如果为空则设置为空数组
  57. $data['kp_codes'] = $data['kp_codes'] ?? [];
  58. if (!is_array($data['kp_codes'])) {
  59. $data['kp_codes'] = [];
  60. }
  61. $questionTypeRatio = $this->normalizeQuestionTypeRatio($data['question_type_ratio'] ?? []);
  62. $difficultyRatio = $this->normalizeDifficultyRatio($data['difficulty_ratio'] ?? []);
  63. $paperName = $data['paper_name'] ?? ('智能试卷_' . now()->format('Ymd_His'));
  64. $difficultyCategory = $this->normalizeDifficultyCategory($data['difficulty_category'] ?? null);
  65. try {
  66. $result = $this->learningAnalyticsService->generateIntelligentExam([
  67. 'student_id' => $data['student_id'],
  68. 'grade' => $data['grade'] ?? null,
  69. 'total_questions' => $data['total_questions'],
  70. 'kp_codes' => $data['kp_codes'],
  71. 'skills' => $data['skills'] ?? [],
  72. 'question_type_ratio' => $questionTypeRatio,
  73. 'difficulty_ratio' => $difficultyRatio,
  74. ]);
  75. if (empty($result['success'])) {
  76. return response()->json([
  77. 'success' => false,
  78. 'message' => $result['message'] ?? '智能出卷失败',
  79. ], 400);
  80. }
  81. $questions = $this->hydrateQuestions($result['questions'] ?? [], $data['kp_codes']);
  82. if (empty($questions)) {
  83. return response()->json([
  84. 'success' => false,
  85. 'message' => '未能生成有效题目,请检查知识点或题库数据',
  86. ], 400);
  87. }
  88. $totalScore = array_sum(array_column($questions, 'score'));
  89. $paperId = $this->questionBankService->saveExamToDatabase([
  90. 'paper_name' => $paperName,
  91. 'student_id' => $data['student_id'],
  92. 'teacher_id' => $data['teacher_id'],
  93. 'difficulty_category' => $difficultyCategory,
  94. 'total_score' => $data['total_score'] ?? $totalScore,
  95. 'questions' => $questions,
  96. ]);
  97. if (!$paperId) {
  98. return response()->json([
  99. 'success' => false,
  100. 'message' => '试卷保存失败',
  101. ], 500);
  102. }
  103. // 生成真实 PDF(试卷 + 判卷),若失败则回退到 HTML 预览
  104. $pdfUrl = $this->pdfExportService->generateExamPdf($paperId)
  105. ?? $this->questionBankService->exportExamToPdf($paperId)
  106. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']);
  107. $gradingUrl = $this->pdfExportService->generateGradingPdf($paperId)
  108. ?? route('filament.admin.auth.intelligent-exam.grading', ['paper_id' => $paperId]);
  109. // 生成判卷PDF URL(带答案版本)
  110. $gradingPdfUrl = $this->pdfExportService->generateGradingPdf($paperId)
  111. ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'true']);
  112. // 构建包含完整信息的试卷内容
  113. $examContent = $this->buildCompleteExamContent($paperId);
  114. $payload = [
  115. 'success' => true,
  116. 'message' => '智能试卷生成成功',
  117. 'data' => [
  118. // 第一部分:组成卷子的所有内容
  119. 'exam_content' => $examContent,
  120. // 第二部分:卷面和判卷的URL
  121. 'urls' => [
  122. 'grading_url' => route('filament.admin.auth.intelligent-exam.grading', ['paper_id' => $paperId]),
  123. 'student_exam_url' => route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']),
  124. ],
  125. // 第三部分:卷面和判卷的PDF
  126. 'pdfs' => [
  127. 'exam_paper_pdf' => $pdfUrl, // 纯试卷PDF(无答案)
  128. 'grading_pdf' => $gradingPdfUrl, // 判卷PDF(带答案和解析)
  129. ],
  130. // 额外信息
  131. 'stats' => $result['stats'] ?? null,
  132. 'generated_at' => now()->toISOString(),
  133. ],
  134. ];
  135. // 返回不转义的完整 URL
  136. return response()->json($payload, 200, [], JSON_UNESCAPED_SLASHES);
  137. } catch (\Exception $e) {
  138. Log::error('Intelligent exam API failed', [
  139. 'error' => $e->getMessage(),
  140. 'trace' => $e->getTraceAsString(),
  141. ]);
  142. return response()->json([
  143. 'success' => false,
  144. 'message' => '服务异常,请稍后重试',
  145. ], 500);
  146. }
  147. }
  148. /**
  149. * 兼容字符串/数组入参
  150. */
  151. private function normalizePayload(array $payload): array
  152. {
  153. // 处理 kp_codes:空字符串或null转换为空数组
  154. if (isset($payload['kp_codes'])) {
  155. if (is_string($payload['kp_codes'])) {
  156. $kpCodes = trim($payload['kp_codes']);
  157. if (empty($kpCodes)) {
  158. $payload['kp_codes'] = [];
  159. } else {
  160. $payload['kp_codes'] = array_values(array_filter(array_map('trim', explode(',', $kpCodes))));
  161. }
  162. } elseif (!is_array($payload['kp_codes'])) {
  163. $payload['kp_codes'] = [];
  164. }
  165. } else {
  166. $payload['kp_codes'] = [];
  167. }
  168. if (isset($payload['skills']) && is_string($payload['skills'])) {
  169. $payload['skills'] = array_values(array_filter(array_map('trim', explode(',', $payload['skills']))));
  170. }
  171. return $payload;
  172. }
  173. private function normalizeQuestionTypeRatio(array $input): array
  174. {
  175. // 默认按 4:2:4
  176. $defaults = [
  177. '选择题' => 40,
  178. '填空题' => 20,
  179. '解答题' => 40,
  180. ];
  181. $normalized = [];
  182. foreach ($input as $key => $value) {
  183. if (!is_numeric($value)) {
  184. continue;
  185. }
  186. $type = $this->normalizeQuestionTypeKey($key);
  187. if ($type) {
  188. $normalized[$type] = (float) $value;
  189. }
  190. }
  191. $merged = array_merge($defaults, $normalized);
  192. // 归一化到 100%
  193. $sum = array_sum($merged);
  194. if ($sum > 0) {
  195. foreach ($merged as $k => $v) {
  196. $merged[$k] = round(($v / $sum) * 100, 2);
  197. }
  198. }
  199. return $merged;
  200. }
  201. private function normalizeQuestionTypeKey(string $key): ?string
  202. {
  203. $key = trim($key);
  204. if (in_array($key, ['choice', '选择题', 'single_choice', 'multiple_choice'])) {
  205. return '选择题';
  206. }
  207. if (in_array($key, ['fill', '填空题', 'blank'])) {
  208. return '填空题';
  209. }
  210. if (in_array($key, ['answer', '解答题', '计算题'])) {
  211. return '解答题';
  212. }
  213. return null;
  214. }
  215. private function normalizeDifficultyRatio(array $input): array
  216. {
  217. $defaults = [
  218. '基础' => 50,
  219. '中等' => 35,
  220. '拔高' => 15,
  221. ];
  222. $normalized = [];
  223. foreach ($input as $key => $value) {
  224. if (!is_numeric($value)) {
  225. continue;
  226. }
  227. $label = trim($key);
  228. if (in_array($label, ['基础', 'easy', '简单'])) {
  229. $normalized['基础'] = (float) $value;
  230. } elseif (in_array($label, ['中等', 'medium'])) {
  231. $normalized['中等'] = (float) $value;
  232. } elseif (in_array($label, ['拔高', 'hard', '困难', '竞赛'])) {
  233. $normalized['拔高'] = (float) $value;
  234. }
  235. }
  236. return array_merge($defaults, $normalized);
  237. }
  238. private function normalizeDifficultyCategory(?string $category): string
  239. {
  240. if (!$category) {
  241. return '基础';
  242. }
  243. $category = trim($category);
  244. if (in_array($category, ['基础', '进阶', '中等', 'easy'])) {
  245. return $category === 'easy' ? '基础' : $category;
  246. }
  247. if (in_array($category, ['拔高', '困难', 'hard', '竞赛'])) {
  248. return '拔高';
  249. }
  250. return '基础';
  251. }
  252. private function hydrateQuestions(array $questions, array $kpCodes): array
  253. {
  254. $normalized = [];
  255. foreach ($questions as $question) {
  256. $type = $this->normalizeQuestionTypeKey($question['question_type'] ?? $question['type'] ?? '') ?? $this->guessType($question);
  257. $score = $question['score'] ?? $this->defaultScore($type);
  258. $normalized[] = [
  259. 'id' => $question['id'] ?? $question['question_id'] ?? null,
  260. 'question_id' => $question['question_id'] ?? null,
  261. 'question_type' => $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer'),
  262. 'stem' => $question['stem'] ?? $question['content'] ?? ($question['question_text'] ?? ''),
  263. 'content' => $question['content'] ?? $question['stem'] ?? '',
  264. 'options' => $question['options'] ?? ($question['choices'] ?? []),
  265. 'answer' => $question['answer'] ?? $question['correct_answer'] ?? '',
  266. 'solution' => $question['solution'] ?? '',
  267. 'difficulty' => isset($question['difficulty']) ? (float) $question['difficulty'] : 0.5,
  268. 'score' => $score,
  269. 'estimated_time' => $question['estimated_time'] ?? 300,
  270. 'kp' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  271. 'kp_code' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
  272. ];
  273. }
  274. return array_values(array_filter($normalized, fn ($q) => !empty($q['id'])));
  275. }
  276. private function guessType(array $question): string
  277. {
  278. if (!empty($question['options']) && is_array($question['options'])) {
  279. return '选择题';
  280. }
  281. $content = $question['stem'] ?? $question['content'] ?? '';
  282. if (is_string($content) && (strpos($content, '____') !== false || strpos($content, '()') !== false)) {
  283. return '填空题';
  284. }
  285. return '解答题';
  286. }
  287. private function defaultScore(string $type): int
  288. {
  289. if ($type === '选择题' || $type === '填空题') {
  290. return 5;
  291. }
  292. return 10;
  293. }
  294. /**
  295. * 构建完整的试卷信息(包含所有题目详情)
  296. */
  297. private function buildCompleteExamContent(string $paperId): array
  298. {
  299. $paper = Paper::with('questions')->find($paperId);
  300. $questions = $paper ? $paper->questions : collect();
  301. return [
  302. // 试卷基本信息
  303. 'paper_info' => [
  304. 'paper_id' => $paperId,
  305. 'paper_name' => $paper?->paper_name ?? '',
  306. 'student_id' => $paper?->student_id ?? '',
  307. 'teacher_id' => $paper?->teacher_id ?? '',
  308. 'total_questions' => $questions->count(),
  309. 'total_score' => $paper?->total_score ?? 0,
  310. 'difficulty_category' => $paper?->difficulty_category ?? '基础',
  311. 'created_at' => $paper?->created_at?->toISOString(),
  312. 'updated_at' => $paper?->updated_at?->toISOString(),
  313. ],
  314. // 完整题目信息
  315. 'questions' => $questions->map(function (PaperQuestion $q) {
  316. // 构建选择题选项(如果适用)
  317. $options = [];
  318. if ($q->question_type === 'choice') {
  319. // 从题目文本中提取选项
  320. $questionText = $q->question_text ?? '';
  321. preg_match_all('/([A-D])\s*[\.\、\:]\s*([^A-D]+?)(?=[A-D]\s*[\.\、\:]|$)/u', $questionText, $matches, PREG_SET_ORDER);
  322. foreach ($matches as $match) {
  323. $options[] = [
  324. 'label' => $match[1],
  325. 'content' => trim($match[2]),
  326. ];
  327. }
  328. }
  329. return [
  330. // 基本信息
  331. 'question_number' => $q->question_number,
  332. 'question_id' => $q->question_id,
  333. 'question_bank_id' => $q->question_bank_id,
  334. 'question_type' => $q->question_type,
  335. 'knowledge_point' => $q->knowledge_point,
  336. 'difficulty' => $q->difficulty,
  337. 'score' => $q->score,
  338. 'estimated_time' => $q->estimated_time,
  339. // 题目内容
  340. 'stem' => $q->question_text ?? '',
  341. 'options' => $options,
  342. // 答案和解析
  343. 'correct_answer' => $q->correct_answer ?? '',
  344. 'solution' => $q->solution ?? '',
  345. // 元数据
  346. 'student_answer' => $q->student_answer,
  347. 'is_correct' => $q->is_correct,
  348. 'score_obtained' => $q->score_obtained,
  349. 'score_ratio' => $q->score_ratio,
  350. 'teacher_comment' => $q->teacher_comment,
  351. 'graded_at' => $q->graded_at?->toISOString(),
  352. 'graded_by' => $q->graded_by,
  353. // 题目属性
  354. 'metadata' => [
  355. 'has_solution' => !empty($q->solution),
  356. 'is_choice' => $q->question_type === 'choice',
  357. 'is_fill' => $q->question_type === 'fill',
  358. 'is_answer' => $q->question_type === 'answer',
  359. 'difficulty_label' => $this->getDifficultyLabel($q->difficulty),
  360. 'question_type_label' => $this->getQuestionTypeLabel($q->question_type),
  361. ],
  362. ];
  363. })->toArray(),
  364. // 统计信息
  365. 'statistics' => [
  366. 'type_distribution' => $this->getTypeDistribution($questions),
  367. 'difficulty_distribution' => $this->getDifficultyDistribution($questions),
  368. 'knowledge_point_distribution' => $this->getKnowledgePointDistribution($questions),
  369. 'total_score' => $questions->sum('score'),
  370. 'average_difficulty' => $questions->avg('difficulty'),
  371. 'total_estimated_time' => $questions->sum('estimated_time'),
  372. ],
  373. // 知识点和技能标签
  374. 'knowledge_points' => $questions->pluck('knowledge_point')->unique()->filter()->values()->toArray(),
  375. 'skills' => $this->extractSkillsFromQuestions($questions),
  376. ];
  377. }
  378. /**
  379. * 获取题型中文标签
  380. */
  381. private function getQuestionTypeLabel(string $type): string
  382. {
  383. return match($type) {
  384. 'choice' => '选择题',
  385. 'fill' => '填空题',
  386. 'answer' => '解答题',
  387. default => '未知题型'
  388. };
  389. }
  390. /**
  391. * 获取难度中文标签
  392. */
  393. private function getDifficultyLabel(?float $difficulty): string
  394. {
  395. if ($difficulty === null) return '未知';
  396. if ($difficulty <= 0.4) return '基础';
  397. if ($difficulty <= 0.7) return '中等';
  398. return '拔高';
  399. }
  400. /**
  401. * 获取题型分布
  402. */
  403. private function getTypeDistribution($questions): array
  404. {
  405. $distribution = [];
  406. foreach ($questions as $q) {
  407. $type = $q->question_type;
  408. $distribution[$type] = ($distribution[$type] ?? 0) + 1;
  409. }
  410. return $distribution;
  411. }
  412. /**
  413. * 获取难度分布
  414. */
  415. private function getDifficultyDistribution($questions): array
  416. {
  417. $distribution = [];
  418. foreach ($questions as $q) {
  419. $label = $this->getDifficultyLabel($q->difficulty);
  420. $distribution[$label] = ($distribution[$label] ?? 0) + 1;
  421. }
  422. return $distribution;
  423. }
  424. /**
  425. * 获取知识点分布
  426. */
  427. private function getKnowledgePointDistribution($questions): array
  428. {
  429. $distribution = [];
  430. foreach ($questions as $q) {
  431. $kp = $q->knowledge_point;
  432. if ($kp) {
  433. $distribution[$kp] = ($distribution[$kp] ?? 0) + 1;
  434. }
  435. }
  436. return $distribution;
  437. }
  438. /**
  439. * 从题目中提取技能标签
  440. */
  441. private function extractSkillsFromQuestions($questions): array
  442. {
  443. $skills = [];
  444. // 注意:由于题库在PostgreSQL中,MySQL的questions表可能不存在
  445. // 我们从PaperQuestion的solution或metadata中提取技能信息
  446. foreach ($questions as $q) {
  447. // 从解题过程中提取技能关键词
  448. $solution = $q->solution ?? '';
  449. if ($solution) {
  450. // 简单的技能提取(基于常见关键词)
  451. $skillKeywords = ['代入法', '配方法', '因式分解', '换元法', '判别式', '求根公式', '韦达定理'];
  452. foreach ($skillKeywords as $keyword) {
  453. if (strpos($solution, $keyword) !== false) {
  454. $skills[] = $keyword;
  455. }
  456. }
  457. }
  458. // 从题目文本中提取技能标签(如果存在)
  459. $stem = $q->question_text ?? '';
  460. if ($stem) {
  461. // 尝试从题干中提取技能信息(格式如:{技能1,技能2})
  462. preg_match_all('/\{([^}]+)\}/', $stem, $matches);
  463. foreach ($matches[1] as $match) {
  464. $skillList = array_map('trim', explode(',', $match));
  465. $skills = array_merge($skills, $skillList);
  466. }
  467. }
  468. }
  469. return array_unique(array_filter($skills));
  470. }
  471. }