ExternalOCRDriver.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace App\Services\OCR\Drivers;
  3. use App\Services\OCR\OCRInterface;
  4. use Illuminate\Support\Facades\Http;
  5. use Illuminate\Support\Facades\Log;
  6. class ExternalOCRDriver implements OCRInterface
  7. {
  8. protected $url;
  9. protected $timeout;
  10. public function __construct(array $config)
  11. {
  12. $this->url = $config['url'];
  13. $this->timeout = $config['timeout'];
  14. }
  15. public function recognize(string $imagePath, array $options = []): array
  16. {
  17. try {
  18. if (!file_exists($imagePath)) {
  19. throw new \Exception('Image file not found: ' . $imagePath);
  20. }
  21. $multipart = [
  22. [
  23. 'name' => 'image',
  24. 'contents' => fopen($imagePath, 'r'),
  25. 'filename' => basename($imagePath),
  26. ],
  27. ];
  28. if (isset($options['student_id'])) {
  29. $multipart[] = [
  30. 'name' => 'student_id',
  31. 'contents' => $options['student_id'],
  32. ];
  33. }
  34. $response = Http::timeout($this->timeout)
  35. ->asMultipart()
  36. ->post($this->url . '/ocr/analyze-paper', $multipart);
  37. if ($response->failed()) {
  38. throw new \Exception('External OCR service failed: ' . $response->body());
  39. }
  40. return $response->json();
  41. } catch (\Exception $e) {
  42. Log::error('External OCR Error', [
  43. 'message' => $e->getMessage(),
  44. ]);
  45. throw $e;
  46. }
  47. }
  48. }