ImageArrJob.php 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace app\job;
  3. use think\Db;
  4. use think\queue\Job;
  5. use think\Queue;
  6. /**
  7. * ImageArrJob 图像任务初始化队列
  8. * 用于将批量图像任务按类型分发至下游子队列(图生文/文生文/文生图)
  9. */
  10. class ImageArrJob
  11. {
  12. /**
  13. * 队列任务执行函数
  14. *
  15. * @param Job $job 当前队列任务对象
  16. * @param array $data 传入的数据,包含 task_id 和图像列表 data
  17. * task_id:队列id
  18. * data:队列数据
  19. */
  20. public function fire(Job $job, $data)
  21. {
  22. $task_id = $data['task_id'];
  23. $images = $data['data'];
  24. foreach ($images as $value) {
  25. $value['task_id'] = $task_id;
  26. // 清理路径:去除末尾 Preview 目录
  27. $sourceDir = rtrim($value["sourceDir"], '/\\');
  28. $dirParts = explode('/', str_replace('\\', '/', $sourceDir));
  29. if (end($dirParts) === 'Preview') {
  30. array_pop($dirParts);
  31. }
  32. $cleanedSourceDir = implode('/', $dirParts);
  33. // 获取文件名并拼接最终路径
  34. $fileName = basename($value['file_name']);
  35. $fullPath = $cleanedSourceDir . '/' . $fileName;
  36. // 写入 image_task_log 队列明细日志记录
  37. $log_id = Db::name('image_task_log')->insertGetId([
  38. 'task_id' => $task_id,
  39. 'file_name' => $fullPath,
  40. 'model_name' => $value['type'] ?? '',
  41. 'status' => 0,
  42. 'log' => '队列中',
  43. 'create_time' => date('Y-m-d H:i:s')
  44. ]);
  45. $value['log_id'] = $log_id;
  46. //若有链式任务,传递下去
  47. $chain_next = $value['chain_next'] ?? [];
  48. switch (trim($value['type'])) {
  49. case '图生文':
  50. Queue::push('app\job\ImageJob', array_merge($value, ['chain_next' => $chain_next]), 'imgtotxt');
  51. break;
  52. case '文生文':
  53. Queue::push('app\job\TextToTextJob', array_merge($value, ['chain_next' => $chain_next]), 'txttotxt');
  54. break;
  55. case '文生图':
  56. Queue::push('app\job\TextToImageJob', array_merge($value, ['chain_next' => $chain_next]), 'txttoimg');
  57. break;
  58. case '图生图':
  59. Queue::push('app\job\ImageToImageJob', array_merge($value, ['chain_next' => $chain_next]), 'imgtoimg');
  60. break;
  61. case '高清放大':
  62. Queue::push('app\job\ImageToSingleJob', array_merge($value, ['chain_next' => $chain_next]), 'single');
  63. break;
  64. default:
  65. \think\Log::warning("未识别的任务类型:" . json_encode($value, JSON_UNESCAPED_UNICODE));
  66. break;
  67. }
  68. }
  69. //更新任务状态为已启动
  70. Db::name('queue_logs')->where('id', $task_id)->update(['status' => '已启动队列']);
  71. echo date('Y-m-d H:i:s') . " 队列已启动\n";
  72. //删除当前队列任务
  73. $job->delete();
  74. }
  75. /**
  76. * 任务执行失败回调
  77. *
  78. * @param array $data 原始任务数据
  79. */
  80. public function failed($data)
  81. {
  82. \think\Log::error("ImageArrJob 任务失败:" . json_encode($data, JSON_UNESCAPED_UNICODE));
  83. }
  84. }