TextToImageJob.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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";
  48. foreach ($list as $index => $row) {
  49. $currentIndex = $index + 1;
  50. $begin = date('Y-m-d H:i:s');
  51. echo "👉 正在处理第 {$currentIndex} 条,ID: {$row['id']}\n";
  52. // 图像生成
  53. $result = $this->textToImage(
  54. $data["file_name"],
  55. $data["outputDir"],
  56. $data["width"],
  57. $data["height"],
  58. $row["english_description"],
  59. $row["img_name"],
  60. $data["selectedOption"]
  61. );
  62. // 标准化结果文本
  63. if ($result === true || $result === 1 || $result === '成功') {
  64. $resultText = '成功';
  65. } else {
  66. $resultText = (string) $result ?: '失败或无返回';
  67. }
  68. echo "✅ 处理结果:{$resultText}\n";
  69. echo "完成时间:" . date('Y-m-d H:i:s') . "\n";
  70. echo "Processed: " . static::class . "\n";
  71. echo "文生图已处理完成\n\n";
  72. // 若包含关键词,日志状态标为失败(-1)
  73. if (strpos($resultText, '包含关键词') !== false) {
  74. // 命中关键词类错误,状态设为失败
  75. if ($logId) {
  76. Db::name('image_task_log')->where('id', $logId)->update([
  77. 'status' => -1,
  78. 'log' => $resultText,
  79. 'update_time' => date('Y-m-d H:i:s')
  80. ]);
  81. }
  82. }else{
  83. // 日志状态设置为成功(仅在未提前失败时)
  84. if ($logId) {
  85. Db::name('image_task_log')->where('id', $logId)->update([
  86. 'status' => 2,
  87. 'log' => '文生图处理成功',
  88. 'update_time' => date('Y-m-d H:i:s')
  89. ]);
  90. }
  91. }
  92. continue; //跳过当前记录的后续处理
  93. }
  94. echo date('Y-m-d H:i:s') . " ✅ 文生图任务全部完成\n";
  95. }
  96. // 处理链式任务(如果有)
  97. if (!empty($data['chain_next'])) {
  98. $nextType = array_shift($data['chain_next']);
  99. $data['type'] = $nextType;
  100. Queue::push('app\job\ImageArrJob', [
  101. 'task_id' => $data['task_id'],
  102. 'data' => [$data]
  103. ], 'arrimage');
  104. }
  105. $job->delete();
  106. } catch (\Exception $e) {
  107. echo "❌ 异常信息: " . $e->getMessage() . "\n";
  108. echo "📄 文件: " . $e->getFile() . "\n";
  109. echo "📍 行号: " . $e->getLine() . "\n";
  110. if ($logId) {
  111. Db::name('image_task_log')->where('id', $logId)->update([
  112. 'status' => -1,
  113. 'log' => '文生图失败:' . $e->getMessage(),
  114. 'update_time' => date('Y-m-d H:i:s')
  115. ]);
  116. }
  117. $job->delete();
  118. }
  119. }
  120. /**
  121. * 任务失败时的处理
  122. */
  123. public function failed($data)
  124. {
  125. // 记录失败日志或发送通知
  126. echo "ImageJob failed: " . json_encode($data);
  127. }
  128. /**
  129. * 文生图处理函数
  130. * 描述:根据提示词调用图像生成接口,保存图像文件,并更新数据库
  131. */
  132. public function textToImage($fileName, $outputDirRaw, $width, $height, $prompt, $img_name,$selectedOption)
  133. {
  134. $rootPath = str_replace('\\', '/', ROOT_PATH);
  135. $outputDir = rtrim($rootPath . 'public/' . $outputDirRaw, '/') . '/';
  136. $dateDir = date('Y-m-d') . '/';
  137. $fullBaseDir = $outputDir . $dateDir;
  138. // 创建所需的输出目录
  139. foreach ([$fullBaseDir, $fullBaseDir . '1024x1024/', $fullBaseDir . "{$width}x{$height}/"] as $dir) {
  140. if (!is_dir($dir)) {
  141. mkdir($dir, 0755, true);
  142. }
  143. }
  144. // 查询数据库记录
  145. $record = Db::name('text_to_image')
  146. ->where('old_image_url', 'like', "%{$fileName}")
  147. ->order('id desc')
  148. ->find();
  149. if (!$record) {
  150. return '没有找到匹配的图像记录';
  151. }
  152. // 写入 prompt 日志
  153. $logDir = $rootPath . 'runtime/logs/';
  154. if (!is_dir($logDir)) mkdir($logDir, 0755, true);
  155. // 调用文生图模型接口生成图像
  156. $startTime = microtime(true);
  157. // 清理 prompt 的换行
  158. $prompt = preg_replace('/[\r\n\t]+/', ' ', $prompt);
  159. // 定义要跳过的关键词(可按需扩展)
  160. $skipKeywords = ['几何', 'geometry', 'geometric'];
  161. foreach ($skipKeywords as $keyword) {
  162. // 判断提示词中是否包含关键词(不区分大小写)
  163. if (stripos($prompt, $keyword) !== false) {
  164. $skipId = $record['id'];
  165. echo "🚫 跳过生成:包含关键词“{$keyword}”,记录 ID:{$skipId}\n";
  166. Db::name('text_to_image')->where('id', $skipId)->update([
  167. 'status' => 3,
  168. 'error_msg' => "包含关键词".$keyword,
  169. 'update_time' => date('Y-m-d H:i:s')
  170. ]);
  171. return "包含关键词 - {$keyword}";
  172. }
  173. }
  174. //文生图调用
  175. $startTime = microtime(true);
  176. $ai = new AIGatewayService();
  177. $dalle1024 = $ai->callDalleApi($prompt,$selectedOption);
  178. $endTime = microtime(true);
  179. $executionTime = $endTime - $startTime;
  180. echo "✅ API 调用耗时: " . round($executionTime, 3) . " 秒\n";
  181. // 错误检查
  182. if (isset($dalle1024['error'])) {
  183. throw new \Exception("❌ 图像生成接口错误:" . ($dalle1024['error']['message'] ?? '未知错误'));
  184. }
  185. // 提取 url 图像
  186. // $base64Image = $dalle1024['data'][0]['url'] ?? null;
  187. // 提取 base64 图像
  188. $base64Image = $dalle1024['data'][0]['b64_json'] ?? null;
  189. if (!$base64Image || strlen($base64Image) < 1000) {
  190. file_put_contents('/tmp/empty_image_base64.txt', json_encode($dalle1024, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
  191. throw new \Exception("❌ 图像内容为空或异常,详情写入 /tmp/empty_image_base64.txt");
  192. }
  193. // 解码图片
  194. $imgData = base64_decode($base64Image);
  195. // 判断是否为图像
  196. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  197. $mimeType = finfo_buffer($finfo, $imgData);
  198. finfo_close($finfo);
  199. // 保存图片路径
  200. $img_name = mb_substr(preg_replace('/[^\x{4e00}-\x{9fa5}A-Za-z0-9_\- ]/u', '', $img_name), 0, 30);
  201. $filename = $img_name . '.png';
  202. $saveDir1024 = $fullBaseDir . '1024x1024/';
  203. $saveDirCustom = $fullBaseDir . "{$width}x{$height}/";
  204. @mkdir($saveDir1024, 0755, true);
  205. @mkdir($saveDirCustom, 0755, true);
  206. $path1024 = $saveDir1024 . $filename;
  207. $pathCustom = $saveDirCustom . $filename;
  208. file_put_contents($path1024, $imgData);
  209. // 解析图像内容
  210. try {
  211. $im = \imagecreatefromstring($imgData);
  212. if (!$im) {
  213. file_put_contents('/tmp/corrupted.png', $imgData);
  214. throw new \Exception("❌ 图像无法解析,写入 /tmp/corrupted.png");
  215. }
  216. } catch (\Throwable $e) {
  217. file_put_contents('/tmp/corrupted.png', $imgData);
  218. throw new \Exception("❌ 图像处理异常:" . $e->getMessage());
  219. }
  220. // 裁剪
  221. $srcW = imagesx($im);
  222. $srcH = imagesy($im);
  223. $srcRatio = $srcW / $srcH;
  224. $dstRatio = $width / $height;
  225. if ($srcRatio > $dstRatio) {
  226. $cropW = intval($srcH * $dstRatio);
  227. $cropH = $srcH;
  228. $srcX = intval(($srcW - $cropW) / 2);
  229. $srcY = 0;
  230. } else {
  231. $cropW = $srcW;
  232. $cropH = intval($srcW / $dstRatio);
  233. $srcX = 0;
  234. $srcY = intval(($srcH - $cropH) / 2);
  235. }
  236. $dstImg = imagecreatetruecolor($width, $height);
  237. imagecopyresampled($dstImg, $im, 0, 0, $srcX, $srcY, $width, $height, $cropW, $cropH);
  238. // 保存裁剪图
  239. imagepng($dstImg, $pathCustom);
  240. imagedestroy($im);
  241. imagedestroy($dstImg);
  242. // 写入数据库
  243. Db::name('text_to_image')->where('id', $record['id'])->update([
  244. 'new_image_url' => str_replace($rootPath . 'public/', '', $path1024),
  245. 'custom_image_url' => str_replace($rootPath . 'public/', '', $pathCustom),
  246. 'img_name' => $img_name,
  247. 'model' => $selectedOption,
  248. 'status' => trim($img_name) === '' ? 0 : 1,
  249. 'status_name' => "文生图",
  250. 'size' => "{$width}x{$height}",
  251. 'quality' => 'standard',
  252. 'style' => 'vivid',
  253. 'error_msg' => '',
  254. 'update_time' => date('Y-m-d H:i:s')
  255. ]);
  256. return "成功";
  257. }
  258. }