ProcessOCRRecord.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. Log::info('OCR: 开始处理任务', [
  36. 'record_id' => $this->recordId,
  37. 'paper_title' => $record->paper_title,
  38. 'file_path' => $record->file_path,
  39. 'student_id' => $record->student_id,
  40. 'analysis_id' => $record->analysis_id
  41. ]);
  42. try {
  43. // 使用本地OCR服务处理
  44. $ocrService->reprocess($record);
  45. Log::info('OCR处理任务已完成', ['record_id' => $this->recordId]);
  46. } catch (\Exception $e) {
  47. Log::error('OCR处理失败', [
  48. 'record_id' => $this->recordId,
  49. 'error' => $e->getMessage(),
  50. ]);
  51. $record->update([
  52. 'status' => 'failed',
  53. 'error_message' => $e->getMessage(),
  54. ]);
  55. throw $e;
  56. }
  57. }
  58. /**
  59. * Handle a job failure.
  60. */
  61. public function failed(\Throwable $exception): void
  62. {
  63. $record = OCRRecord::find($this->recordId);
  64. if ($record) {
  65. $record->update([
  66. 'status' => 'failed',
  67. 'error_message' => '处理失败: ' . $exception->getMessage(),
  68. ]);
  69. }
  70. Log::error('OCR处理Job失败', [
  71. 'record_id' => $this->recordId,
  72. 'error' => $exception->getMessage(),
  73. ]);
  74. }
  75. }