IntelligentExamController.php 19 KB

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