AnswerParser.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace App\Services\OCR;
  3. class AnswerParser
  4. {
  5. /**
  6. * Parse answer letters from OCR text
  7. * Expected format: "A\nB\nC\nD" or "A B C D" or similar
  8. *
  9. * @param string $text OCR recognized text from answer area
  10. * @return array Array of answer letters, indexed by question number
  11. */
  12. public function parseAnswers(string $text): array
  13. {
  14. $answers = [];
  15. // Remove extra whitespace and normalize
  16. $text = trim($text);
  17. // Split by common delimiters: newline, backslash, space, comma
  18. $parts = preg_split('/[\n\r\\\\\s,]+/', $text);
  19. $questionNumber = 1;
  20. foreach ($parts as $part) {
  21. $part = trim($part);
  22. // Check if it's a valid answer letter (A, B, C, D, or lowercase)
  23. if (preg_match('/^[A-Da-d]$/', $part)) {
  24. $answers[$questionNumber] = strtoupper($part);
  25. $questionNumber++;
  26. }
  27. }
  28. \Log::info('Parsed answers from OCR text', [
  29. 'raw_text' => $text,
  30. 'parsed_answers' => $answers,
  31. 'count' => count($answers)
  32. ]);
  33. return $answers;
  34. }
  35. /**
  36. * Parse a single answer letter from OCR text
  37. *
  38. * @param string $text OCR text from a single question's answer area
  39. * @return string|null The answer letter (A/B/C/D) or null if not found
  40. */
  41. public function parseSingleAnswer(string $text): ?string
  42. {
  43. $text = trim($text);
  44. // Look for A, B, C, or D (case insensitive)
  45. if (preg_match('/[A-Da-d]/', $text, $matches)) {
  46. return strtoupper($matches[0]);
  47. }
  48. return null;
  49. }
  50. /**
  51. * Match parsed answers to questions
  52. *
  53. * @param array $questions Array of question data
  54. * @param array $answers Array of answers indexed by question number
  55. * @return array Updated questions with student_answer filled
  56. */
  57. public function matchAnswersToQuestions(array $questions, array $answers): array
  58. {
  59. foreach ($questions as &$question) {
  60. $questionNumber = $question['question_number'];
  61. if (isset($answers[$questionNumber])) {
  62. $question['student_answer'] = $answers[$questionNumber];
  63. }
  64. }
  65. return $questions;
  66. }
  67. }