TextToImageJob.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. <?php
  2. namespace app\job;
  3. use app\service\AIGatewayService;
  4. use think\Db;
  5. use think\Queue;
  6. use think\queue\Job;
  7. /**
  8. * 文生图任务处理类
  9. * 描述:接收提示词,通过模型生成图像,保存图像并记录数据库信息,是链式任务中的最后一环
  10. */
  11. class TextToImageJob
  12. {
  13. /**
  14. * 队列入口方法
  15. * @param Job $job 队列任务对象
  16. * @param array $data 任务传参,包含图像文件名、路径、尺寸、提示词等
  17. */
  18. public function fire(Job $job, $data)
  19. {
  20. $logId = $data['log_id'] ?? null;
  21. try {
  22. // 任务类型校验(必须是文生图)
  23. if (!isset($data['type']) || $data['type'] !== '文生图') {
  24. $job->delete();
  25. return;
  26. }
  27. $startTime = date('Y-m-d H:i:s');
  28. echo "━━━━━━━━━━ ▶ 文生图任务开始处理━━━━━━━━━━\n";
  29. echo "处理时间:{$startTime}\n";
  30. // 更新日志状态:处理中
  31. if ($logId) {
  32. Db::name('image_task_log')->where('id', $logId)->update([
  33. 'status' => 1,
  34. 'log' => '文生图处理中',
  35. 'update_time' => $startTime
  36. ]);
  37. }
  38. //拼接原图文件路径 + 图片名称
  39. $old_image_url = rtrim($data['sourceDir'], '/') . '/' . ltrim($data['file_name'], '/');
  40. $list = Db::name("text_to_image")
  41. ->where('old_image_url', $old_image_url)
  42. ->where('img_name', '<>', '')
  43. ->where('status', 0)
  44. ->select();
  45. if (!empty($list)) {
  46. $total = count($list);
  47. echo "📊 共需处理:{$total} 条记录\n\n";
  48. foreach ($list as $index => $row) {
  49. $currentIndex = $index + 1;
  50. $begin = date('Y-m-d H:i:s');
  51. echo "处理时间:{$begin}\n";
  52. echo "👉 正在处理第 {$currentIndex} 条,ID: {$row['id']}\n";
  53. // 调用生成图像方法
  54. $result = $this->textToImage(
  55. $data["file_name"],
  56. $data["outputDir"],
  57. $data["width"],
  58. $data["height"],
  59. $row["english_description"],
  60. $row["img_name"],
  61. $data["selectedOption"]
  62. );
  63. $resultText = ($result === true || $result === 1 || $result === '成功') ? '成功' : '失败或无返回';
  64. echo "✅ 处理结果:{$resultText}\n";
  65. $end = date('Y-m-d H:i:s');
  66. echo "完成时间:{$end}\n";
  67. echo "Processed: " . static::class . "\n";
  68. echo "文生图已处理完成\n\n";
  69. }
  70. // 更新日志状态:成功
  71. if ($logId) {
  72. Db::name('image_task_log')->where('id', $logId)->update([
  73. 'status' => 2,
  74. 'log' => '文生图处理成功',
  75. 'update_time' => date('Y-m-d H:i:s')
  76. ]);
  77. }
  78. echo date('Y-m-d H:i:s') . " ✅ 文生图任务全部完成\n";
  79. } else {
  80. echo "⚠ 未找到可处理的数据,跳过执行\n";
  81. if ($logId) {
  82. Db::name('image_task_log')->where('id', $logId)->update([
  83. 'status' => 2,
  84. 'log' => '无数据可处理,已跳过'.$old_image_url,
  85. 'update_time' => date('Y-m-d H:i:s')
  86. ]);
  87. }
  88. }
  89. // 如果还有链式任务,继续推送
  90. if (!empty($data['chain_next'])) {
  91. $nextType = array_shift($data['chain_next']);
  92. $data['type'] = $nextType;
  93. Queue::push('app\job\ImageArrJob', [
  94. 'task_id' => $data['task_id'],
  95. 'data' => [$data]
  96. ], 'arrimage');
  97. }
  98. $job->delete();
  99. } catch (\Exception $e) {
  100. echo "❌ 异常信息: " . $e->getMessage() . "\n";
  101. echo "📄 文件: " . $e->getFile() . "\n";
  102. echo "📍 行号: " . $e->getLine() . "\n";
  103. if ($logId) {
  104. Db::name('image_task_log')->where('id', $logId)->update([
  105. 'status' => -1,
  106. 'log' => '文生图失败:' . $e->getMessage(),
  107. 'update_time' => date('Y-m-d H:i:s')
  108. ]);
  109. }
  110. $job->delete();
  111. }
  112. }
  113. /**
  114. * 任务失败时的处理
  115. */
  116. public function failed($data)
  117. {
  118. // 记录失败日志或发送通知
  119. echo "ImageJob failed: " . json_encode($data);
  120. }
  121. /**
  122. * 文生图处理函数
  123. * 描述:根据提示词调用图像生成接口,保存图像文件,并更新数据库
  124. */
  125. public function textToImage($fileName, $outputDirRaw, $width, $height, $prompt, $img_name,$selectedOption)
  126. {
  127. $rootPath = str_replace('\\', '/', ROOT_PATH);
  128. $outputDir = rtrim($rootPath . 'public/' . $outputDirRaw, '/') . '/';
  129. $dateDir = date('Y-m-d') . '/';
  130. $fullBaseDir = $outputDir . $dateDir;
  131. // 创建所需的输出目录
  132. foreach ([$fullBaseDir, $fullBaseDir . '1024x1024/', $fullBaseDir . "{$width}x{$height}/"] as $dir) {
  133. if (!is_dir($dir)) {
  134. mkdir($dir, 0755, true);
  135. }
  136. }
  137. // 查询数据库记录
  138. $record = Db::name('text_to_image')
  139. ->where('old_image_url', 'like', "%{$fileName}")
  140. ->order('id desc')
  141. ->find();
  142. if (!$record) {
  143. return '没有找到匹配的图像记录';
  144. }
  145. // 写入 prompt 日志
  146. $logDir = $rootPath . 'runtime/logs/';
  147. if (!is_dir($logDir)) mkdir($logDir, 0755, true);
  148. // 调用文生图模型接口生成图像
  149. $startTime = microtime(true);
  150. // 清理 prompt 的换行
  151. $prompt = preg_replace('/[\r\n\t]+/', ' ', $prompt);
  152. // 定义要跳过的关键词(可按需扩展)
  153. $skipKeywords = ['几何', 'geometry', 'geometric'];
  154. foreach ($skipKeywords as $keyword) {
  155. // 判断提示词中是否包含关键词(不区分大小写)
  156. if (stripos($prompt, $keyword) !== false) {
  157. $skipId = $record['id'];
  158. echo "🚫 跳过生成:提示词中包含关键词“{$keyword}”,记录 ID:{$skipId}\n";
  159. $updateRes = Db::name('text_to_image')->where('id', $skipId)->update([
  160. 'status' => 3,
  161. 'error_msg' => "提示词中包含关键词".$keyword,
  162. 'update_time' => date('Y-m-d H:i:s')
  163. ]);
  164. return "跳过生成:记录 ID {$skipId},包含关键词 - {$keyword}";
  165. }
  166. }
  167. //文生图调用
  168. $ai = new AIGatewayService();
  169. $dalle1024 = $ai->callDalleApi($prompt,$selectedOption);
  170. //检测查询接口调用时长
  171. $endTime = microtime(true);
  172. $executionTime = $endTime - $startTime;
  173. echo "API调用耗时: " . round($executionTime, 3) . " 秒\n";
  174. // 检查 URL 返回是否成功
  175. if (!isset($dalle1024['data'][0]['url']) || empty($dalle1024['data'][0]['url'])) {
  176. $errorText = $dalle1024['error']['message'] ?? '未知错误';
  177. Db::name('text_to_image')->where('id', $record['id'])->update([
  178. 'error_msg' => '生成失败:' . $errorText,
  179. 'status' => 0
  180. ]);
  181. return '生成失败:' . $errorText;
  182. }
  183. // 下载图像
  184. $imgUrl1024 = $dalle1024['data'][0]['url'];
  185. $imgData1024 = @file_get_contents($imgUrl1024);
  186. if (!$imgData1024 || strlen($imgData1024) < 1000) {
  187. return "下载图像失败或内容异常";
  188. }
  189. // 保存原图(1024x1024)
  190. $img_name = preg_replace('/[^\x{4e00}-\x{9fa5}A-Za-z0-9_\- ]/u', '', $img_name);
  191. $img_name = mb_substr($img_name, 0, 30); // 限制为前30个字符(避免路径过长)
  192. $filename1024 = $img_name . '.png';
  193. $savePath1024 = $fullBaseDir . '1024x1024/' . $filename1024;
  194. file_put_contents($savePath1024, $imgData1024);
  195. // 图像裁剪生成自定义尺寸图
  196. $im = @imagecreatefromstring($imgData1024);
  197. if (!$im) return "图像损坏或格式不支持";
  198. $srcWidth = imagesx($im);
  199. $srcHeight = imagesy($im);
  200. $srcRatio = $srcWidth / $srcHeight;
  201. $dstRatio = $width / $height;
  202. // 居中裁剪逻辑
  203. if ($srcRatio > $dstRatio) {
  204. $cropHeight = $srcHeight;
  205. $cropWidth = intval($srcHeight * $dstRatio);
  206. $srcX = intval(($srcWidth - $cropWidth) / 2);
  207. $srcY = 0;
  208. } else {
  209. $cropWidth = $srcWidth;
  210. $cropHeight = intval($srcWidth / $dstRatio);
  211. $srcX = 0;
  212. $srcY = intval(($srcHeight - $cropHeight) / 2);
  213. }
  214. $dstImg = imagecreatetruecolor($width, $height);
  215. imagecopyresampled($dstImg, $im, 0, 0, $srcX, $srcY, $width, $height, $cropWidth, $cropHeight);
  216. // 保存裁剪后图像
  217. $filenameCustom = $img_name . ".png";
  218. $savePathCustom = $fullBaseDir . "{$width}x{$height}/" . $filenameCustom;
  219. imagepng($dstImg, $savePathCustom);
  220. imagedestroy($im);
  221. imagedestroy($dstImg);
  222. // 成功写入数据库记录
  223. $status = trim($img_name) === '' ? 0 : 1;
  224. // 根据 selectedOption 设置 quality 和 style
  225. $quality = 'hd';
  226. $style = 'vivid';
  227. if ($selectedOption === 'dall-e-3') {
  228. $quality = 'standard';
  229. $style = 'vivid';
  230. }
  231. $updateRes = Db::name('text_to_image')->where('id', $record['id'])->update([
  232. 'new_image_url' => str_replace($rootPath . 'public/', '', $savePath1024),
  233. 'custom_image_url' => str_replace($rootPath . 'public/', '', $savePathCustom),
  234. 'img_name' => $img_name,
  235. 'model' => $selectedOption,
  236. 'status' => $status,
  237. 'status_name' => "文生图",
  238. 'size' => "{$width}x{$height}",
  239. 'quality' => $quality,
  240. 'style' => $style,
  241. 'error_msg' => '',
  242. 'update_time' => date('Y-m-d H:i:s')
  243. ]);
  244. return 0;
  245. }
  246. }