OCRService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. <?php
  2. namespace App\Services;
  3. use App\Models\OCRRecord;
  4. use App\Models\OCRQuestionResult;
  5. use Illuminate\Http\UploadedFile;
  6. use Illuminate\Support\Facades\Http;
  7. use Illuminate\Support\Facades\Storage;
  8. use Illuminate\Support\Str;
  9. class OCRService
  10. {
  11. protected $ocrDriver;
  12. protected $learningAnalyticsService;
  13. public function __construct(LearningAnalyticsService $learningAnalyticsService)
  14. {
  15. $this->ocrDriver = \App\Services\OCR\OCRFactory::create();
  16. $this->learningAnalyticsService = $learningAnalyticsService;
  17. }
  18. /**
  19. * 上传卷子照片并创建OCR记录
  20. */
  21. public function uploadExamPaper(UploadedFile $image, string $studentId): OCRRecord
  22. {
  23. // 验证图片
  24. $this->validateImage($image);
  25. // 生成唯一ID
  26. $recordId = 'ocr_' . Str::uuid()->toString();
  27. $examId = 'exam_' . now()->format('YmdHis') . '_' . Str::random(8);
  28. // 获取图片信息
  29. $imageInfo = getimagesize($image->getPathName());
  30. $imageWidth = $imageInfo[0] ?? 0;
  31. $imageHeight = $imageInfo[1] ?? 0;
  32. $imageSize = filesize($image->getPathName());
  33. // 保存图片
  34. $extension = $image->getClientOriginalExtension();
  35. $filename = $recordId . '.' . $extension;
  36. $imagePath = 'uploads/ocr/' . $filename;
  37. Storage::disk('public')->put($imagePath, file_get_contents($image->getPathName()));
  38. // 创建OCR记录
  39. $ocrRecord = OCRRecord::create([
  40. 'id' => $recordId,
  41. 'exam_id' => $examId,
  42. 'student_id' => $studentId,
  43. 'image_path' => $imagePath,
  44. 'image_filename' => $image->getClientOriginalName(),
  45. 'image_size' => $imageSize,
  46. 'image_width' => $imageWidth,
  47. 'image_height' => $imageHeight,
  48. 'status' => 'pending',
  49. ]);
  50. // 发送到OCR服务处理
  51. $this->dispatchToOcrService($ocrRecord);
  52. return $ocrRecord;
  53. }
  54. /**
  55. * 验证上传的图片
  56. */
  57. protected function validateImage(UploadedFile $image): void
  58. {
  59. $maxSize = config('ocr.upload.max_size', 10 * 1024 * 1024);
  60. $allowedTypes = config('ocr.upload.allowed_types', ['jpg', 'jpeg', 'png', 'webp']);
  61. if (!$image->isValid()) {
  62. throw new \Exception('文件上传失败');
  63. }
  64. if ($image->getSize() > $maxSize) {
  65. throw new \Exception('文件大小超出限制(' . ($maxSize / 1024 / 1024) . 'MB)');
  66. }
  67. $extension = strtolower($image->getClientOriginalExtension());
  68. if (!in_array($extension, $allowedTypes)) {
  69. throw new \Exception('不支持的文件类型,仅支持:' . implode(', ', $allowedTypes));
  70. }
  71. }
  72. /**
  73. * 发送到OCR服务处理
  74. */
  75. protected function dispatchToOcrService(OCRRecord $ocrRecord): void
  76. {
  77. try {
  78. // 读取图片文件
  79. $imagePath = Storage::disk($this->getDisk())->path($ocrRecord->image_path);
  80. if (!file_exists($imagePath)) {
  81. throw new \Exception('图片文件不存在: ' . $imagePath);
  82. }
  83. // 更新状态为processing
  84. $ocrRecord->update(['status' => 'processing']);
  85. // Single API call with cutType: answer (returns both question and answer)
  86. \Log::info('OCR: Extracting questions and answers', ['record_id' => $ocrRecord->id]);
  87. $result = $this->ocrDriver->recognize($imagePath, [
  88. 'cutType' => 'answer',
  89. 'subject' => 'Math'
  90. ]);
  91. $items = $result['questions'] ?? [];
  92. \Log::info('OCR extraction complete', ['item_count' => count($items)]);
  93. // Step 2: Parse student answers from the answer_list data
  94. // Each item in answer_list contains the full question+answer text
  95. // The student's answer is typically the last letter (A/B/C/D) in the text
  96. \Log::info('Parsing student answers from question text');
  97. $parsedQuestions = [];
  98. foreach ($items as $item) {
  99. $questionNumber = $item['question_number'];
  100. $fullText = $item['content'] ?? '';
  101. $questionText = $fullText;
  102. $studentAnswer = '';
  103. // Smart parsing: extract the last single letter (A/B/C/D) as student answer
  104. // Pattern: "题目内容...选项D[学生答案]"
  105. // The student answer is usually the very last character if it's A/B/C/D
  106. if (preg_match('/([A-D])\s*$/u', $fullText, $matches)) {
  107. $studentAnswer = $matches[1];
  108. // Remove the answer from question text
  109. $questionText = preg_replace('/\s*[A-D]\s*$/', '', $fullText);
  110. \Log::info('Extracted student answer', [
  111. 'question_number' => $questionNumber,
  112. 'answer' => $studentAnswer,
  113. 'original_text_length' => mb_strlen($fullText),
  114. 'cleaned_text_length' => mb_strlen($questionText)
  115. ]);
  116. }
  117. $parsedQuestions[] = [
  118. 'question_number' => $questionNumber,
  119. 'content' => trim($questionText),
  120. 'student_answer' => $studentAnswer,
  121. 'confidence' => $item['confidence'] ?? 0.0,
  122. 'raw_data' => $item['raw_data'] ?? null
  123. ];
  124. }
  125. // 处理结果
  126. $this->processOcrResult($ocrRecord, [
  127. 'questions' => $parsedQuestions,
  128. 'raw' => $result
  129. ]);
  130. } catch (\Exception $e) {
  131. \Log::error('OCR服务调用失败', [
  132. 'record_id' => $ocrRecord->id,
  133. 'error' => $e->getMessage(),
  134. ]);
  135. // 标记为失败
  136. $ocrRecord->update([
  137. 'status' => 'failed',
  138. 'error_message' => 'OCR服务调用失败:' . $e->getMessage(),
  139. ]);
  140. }
  141. }
  142. /**
  143. * Match answers to questions by question number
  144. */
  145. protected function matchAnswersToQuestions(array $questions, array $answers): array
  146. {
  147. // Create a map of answers by question number
  148. $answerMap = [];
  149. foreach ($answers as $answer) {
  150. $questionNumber = $answer['question_number'] ?? null;
  151. if ($questionNumber) {
  152. $answerMap[$questionNumber] = $answer['content'] ?? '';
  153. }
  154. }
  155. // Match answers to questions
  156. $matched = [];
  157. foreach ($questions as $question) {
  158. $questionNumber = $question['question_number'];
  159. $matched[] = [
  160. 'question_number' => $questionNumber,
  161. 'content' => $question['content'],
  162. 'student_answer' => $answerMap[$questionNumber] ?? '',
  163. 'confidence' => $question['confidence'] ?? 0.0,
  164. 'raw_data' => $question['raw_data'] ?? null
  165. ];
  166. }
  167. return $matched;
  168. }
  169. /**
  170. * 处理OCR结果
  171. */
  172. protected function processOcrResult(OCRRecord $ocrRecord, array $result): void
  173. {
  174. // Log the raw result for debugging
  175. \Log::info('OCR Result received', ['question_count' => count($result['questions'] ?? [])]);
  176. // Get matched questions from two-pass OCR
  177. $questions = $result['questions'] ?? [];
  178. // 使用 LaTeX 清理服务预处理所有公式
  179. $latexCleaner = app(\App\Services\LatexCleanerService::class);
  180. $questions = $latexCleaner->cleanArray($questions, ['content', 'student_answer']);
  181. \Log::info('LaTeX formulas cleaned', ['question_count' => count($questions)]);
  182. $processedCount = 0;
  183. foreach ($questions as $question) {
  184. // 再次确保清理(双重保险)
  185. $questionText = $latexCleaner->clean($question['content'] ?? '');
  186. $studentAnswer = $latexCleaner->clean($question['student_answer'] ?? '');
  187. // 验证清理后的内容
  188. $validation = $latexCleaner->validate($questionText);
  189. if (!$validation['valid']) {
  190. \Log::warning('LaTeX validation warnings', [
  191. 'question_number' => $question['question_number'],
  192. 'errors' => $validation['errors']
  193. ]);
  194. }
  195. OCRQuestionResult::create([
  196. 'ocr_record_id' => $ocrRecord->id,
  197. 'question_number' => $question['question_number'],
  198. 'question_text' => $questionText,
  199. 'student_answer' => $studentAnswer,
  200. 'score_value' => 0, // Will be filled by AI grading
  201. 'mark_detected' => null,
  202. 'score_confidence' => $question['confidence'] ?? 0,
  203. ]);
  204. $processedCount++;
  205. }
  206. $ocrRecord->update([
  207. 'status' => 'completed',
  208. 'processed_at' => now(),
  209. 'total_questions' => $processedCount,
  210. 'processed_questions' => $processedCount,
  211. 'confidence_avg' => collect($questions)->avg('confidence') ?? 0,
  212. ]);
  213. \Log::info('OCR processing complete', [
  214. 'record_id' => $ocrRecord->id,
  215. 'questions_processed' => $processedCount
  216. ]);
  217. // 发送分析请求到 LearningAnalytics
  218. if ($processedCount > 0) {
  219. $this->submitToAnalysis($ocrRecord, $questions);
  220. }
  221. }
  222. /**
  223. * 提交到分析服务
  224. */
  225. protected function submitToAnalysis(OCRRecord $ocrRecord, array $questions): void
  226. {
  227. try {
  228. $analysisData = [
  229. 'exam_id' => $ocrRecord->exam_id,
  230. 'student_id' => $ocrRecord->student_id,
  231. 'ocr_record_id' => $ocrRecord->id,
  232. 'teacher_name' => 'System', // 或者是上传者的名字
  233. 'analysis_type' => 'mastery',
  234. 'questions' => array_map(function($q) {
  235. // 优先使用人工校准的答案
  236. $studentAnswer = $q['student_answer'] ?? '';
  237. if (isset($q['manual_answer']) && !empty($q['manual_answer'])) {
  238. $studentAnswer = $q['manual_answer'];
  239. }
  240. return [
  241. 'question_id' => $q['question_number'], // 使用题号作为临时ID
  242. 'question_number' => (string)$q['question_number'],
  243. 'kp_code' => $q['kp_code'] ?? null,
  244. 'score_value' => $q['score_value'] ?? 0,
  245. 'student_answer' => $studentAnswer,
  246. 'ocr_confidence' => $q['confidence'] ?? 0,
  247. 'question_text' => $q['content'] ?? '', // 传递题目内容供AI分析
  248. 'teacher_validated' => $q['answer_verified'] ?? false,
  249. ];
  250. }, $questions)
  251. ];
  252. $result = $this->learningAnalyticsService->submitOCRAnalysis($analysisData);
  253. if (isset($result['success']) && $result['success']) {
  254. $ocrRecord->update([
  255. 'ai_analyzed_at' => now(),
  256. 'ai_analysis_count' => ($ocrRecord->ai_analysis_count ?? 0) + 1
  257. ]);
  258. }
  259. } catch (\Exception $e) {
  260. \Log::error('Failed to submit to analysis service', [
  261. 'record_id' => $ocrRecord->id,
  262. 'error' => $e->getMessage()
  263. ]);
  264. // 不抛出异常,以免影响OCR流程的完成状态
  265. }
  266. }
  267. /**
  268. * 重新处理OCR记录
  269. */
  270. public function reprocess(OCRRecord $ocrRecord): bool
  271. {
  272. // 重置状态
  273. $ocrRecord->update([
  274. 'status' => 'pending',
  275. 'error_message' => null,
  276. 'processed_at' => null,
  277. 'total_questions' => 0,
  278. 'processed_questions' => 0,
  279. 'confidence_avg' => null,
  280. ]);
  281. // 删除旧的题目结果
  282. OCRQuestionResult::where('ocr_record_id', $ocrRecord->id)->delete();
  283. // 重新发送到OCR服务
  284. $this->dispatchToOcrService($ocrRecord);
  285. return true;
  286. }
  287. /**
  288. * 获取OCR记录的统计信息
  289. */
  290. public function getStatistics(): array
  291. {
  292. $total = OCRRecord::count();
  293. $pending = OCRRecord::where('status', 'pending')->count();
  294. $processing = OCRRecord::where('status', 'processing')->count();
  295. $completed = OCRRecord::where('status', 'completed')->count();
  296. $failed = OCRRecord::where('status', 'failed')->count();
  297. return [
  298. 'total' => $total,
  299. 'pending' => $pending,
  300. 'processing' => $processing,
  301. 'completed' => $completed,
  302. 'failed' => $failed,
  303. ];
  304. }
  305. /**
  306. * 获取存储磁盘名称
  307. */
  308. protected function getDisk(): string
  309. {
  310. return 'public'; // OCR uploads are stored in public disk
  311. }
  312. }