ProcessOCRRecord.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace App\Jobs;
  3. use App\Models\OCRRecord;
  4. use App\Services\OCRService;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. use Illuminate\Foundation\Queue\Queueable;
  7. use Illuminate\Support\Facades\Log;
  8. class ProcessOCRRecord implements ShouldQueue
  9. {
  10. use Queueable;
  11. public int $tries = 3;
  12. public int $timeout = 300;
  13. protected int $recordId;
  14. /**
  15. * Create a new job instance.
  16. */
  17. public function __construct(int $recordId)
  18. {
  19. $this->recordId = $recordId;
  20. }
  21. /**
  22. * Execute the job.
  23. */
  24. public function handle(\App\Services\OCRService $ocrService): void
  25. {
  26. $record = OCRRecord::find($this->recordId);
  27. if (!$record) {
  28. Log::error('OCR记录不存在', ['record_id' => $this->recordId]);
  29. return;
  30. }
  31. if ($record->status === 'completed') {
  32. Log::info('OCR记录已处理完成,跳过', ['record_id' => $this->recordId]);
  33. return;
  34. }
  35. try {
  36. // 使用本地OCR服务处理
  37. $ocrService->reprocess($record);
  38. Log::info('OCR处理任务已完成', ['record_id' => $this->recordId]);
  39. } catch (\Exception $e) {
  40. Log::error('OCR处理失败', [
  41. 'record_id' => $this->recordId,
  42. 'error' => $e->getMessage(),
  43. ]);
  44. $record->update([
  45. 'status' => 'failed',
  46. 'error_message' => $e->getMessage(),
  47. ]);
  48. throw $e;
  49. }
  50. }
  51. /**
  52. * Handle a job failure.
  53. */
  54. public function failed(\Throwable $exception): void
  55. {
  56. $record = OCRRecord::find($this->recordId);
  57. if ($record) {
  58. $record->update([
  59. 'status' => 'failed',
  60. 'error_message' => '处理失败: ' . $exception->getMessage(),
  61. ]);
  62. }
  63. Log::error('OCR处理Job失败', [
  64. 'record_id' => $this->recordId,
  65. 'error' => $exception->getMessage(),
  66. ]);
  67. }
  68. }