TextToImageJob.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. <?php
  2. namespace app\job;
  3. use think\Db;
  4. use think\Queue;
  5. use think\queue\Job;
  6. class TextToImageJob
  7. {
  8. protected $config = [
  9. 'gpt' => [
  10. 'api_key' => 'sk-Bhos1lXTRpZiAAmN06624a219a874eCd91Dc068b902a3e73',
  11. 'api_url' => 'https://one.opengptgod.com/v1/chat/completions'
  12. ],
  13. 'dalle' => [
  14. 'api_key' => 'sk-e0JuPjMntkbgi1BoMjrqyyzMKzAxILkQzyGMSy3xiMupuoWY',
  15. 'api_url' => 'https://niubi.zeabur.app/v1/images/generations'
  16. ]
  17. ];
  18. public function fire(Job $job, $data)
  19. {
  20. echo date('Y-m-d H:i:s') . " 任务开始执行\n";
  21. try {
  22. if (isset($data['type']) && $data['type'] === '文生图') {
  23. echo date('Y-m-d H:i:s') . " [文生图 - 数据库模式] 阶段开始\n";
  24. $list = Db::name("text_to_image")
  25. ->where('old_image_url', $data['sourceDir'] . '/' . $data['file_name'])
  26. ->where('img_name', '<>', '')
  27. ->where('status', 0)
  28. ->select();
  29. if (!empty($list)) {
  30. foreach ($list as $index => $row) {
  31. echo "处理第 " . ($index + 1) . " 条数据,处理ID:" . $row['id'] . "\n";
  32. // 调用 textToImage 方法
  33. $result = $this->textToImage(
  34. $data["file_name"], // 文件名
  35. $data["outputDir"], // 输出目录
  36. $data["width"], // 宽度
  37. $data["height"], // 高度
  38. $row["english_description"], // 英文描述
  39. $row["img_name"] // 图片名
  40. );
  41. echo "处理结果:" . $result . "\n";
  42. }
  43. echo date('Y-m-d H:i:s') . " 文生图任务全部执行完成\n";
  44. } else {
  45. echo "未找到 status=0 的数据,跳过执行\n";
  46. }
  47. $job->delete(); // 删除队列任务
  48. } else {
  49. echo date('Y-m-d H:i:s') . " [文生图 - 单条传参模式] 开始执行\n";
  50. $result = $this->textToImage(
  51. $data["fileName"],
  52. $data["outputDir"],
  53. $data["width"],
  54. $data["height"],
  55. $data["englishDesc"],
  56. $data["img_name"]
  57. );
  58. echo "返回结果:" . $result . "\n";
  59. echo date('Y-m-d H:i:s') . " 单条文生图执行结束\n";
  60. $job->delete();
  61. }
  62. } catch (\Exception $e) {
  63. echo "异常信息: " . $e->getMessage() . "\n";
  64. echo "文件: " . $e->getFile() . "\n";
  65. echo "行号: " . $e->getLine() . "\n";
  66. echo date('Y-m-d H:i:s') . " 任务执行失败\n";
  67. $job->delete();
  68. }
  69. }
  70. /**
  71. * 任务失败时的处理
  72. */
  73. public function failed($data)
  74. {
  75. // 记录失败日志或发送通知
  76. echo "ImageJob failed: " . json_encode($data);
  77. }
  78. /**
  79. * 文生图接口
  80. */
  81. public function textToImage($fileName, $outputDirRaw, $width, $height, $prompt, $img_name)
  82. {
  83. $rootPath = str_replace('\\', '/', ROOT_PATH);
  84. $outputDir = rtrim($rootPath . 'public/' . $outputDirRaw, '/') . '/';
  85. $dateDir = date('Y-m-d') . '/';
  86. $fullBaseDir = $outputDir . $dateDir;
  87. // 创建输出目录结构
  88. foreach ([$fullBaseDir, $fullBaseDir . '1024x1024/', $fullBaseDir . "{$width}x{$height}/"] as $dir) {
  89. if (!is_dir($dir)) {
  90. mkdir($dir, 0755, true);
  91. }
  92. }
  93. // 清理 prompt 的换行
  94. $prompt = preg_replace('/[\r\n\t]+/', ' ', $prompt);
  95. // 查询数据库记录
  96. $record = Db::name('text_to_image')
  97. ->where('old_image_url', 'like', "%{$fileName}")
  98. ->order('id desc')
  99. ->find();
  100. if (!$record) {
  101. return '没有找到匹配的图像记录';
  102. }
  103. // 写入 prompt 日志
  104. $logDir = $rootPath . 'runtime/logs/';
  105. if (!is_dir($logDir)) mkdir($logDir, 0755, true);
  106. // echo 2345;
  107. // 调用文生图模型接口生成图像
  108. $startTime = microtime(true);
  109. // echo "<pre>";
  110. // print_r($prompt);
  111. // echo "<pre>";die;
  112. $dalle1024 = $this->callDalleApi($prompt);
  113. // $dalle1024 = json_decode('{"created":1747932746,"data":[{"revised_prompt":"**First paragraph:** A geometric abstract design with a central motif consisting of curved and angular shapes in a symmetrical arrangement. The color scheme predominantly features shades of blue, with hints of white and black creating a contrast. The design incorporates smooth, flowing lines mixed with sharp angles. The overall style has a modern, minimalist aesthetic, with a focus on balance and clean shapes.","url":"https:\/\/filesystem.site\/cdn\/20250523\/3NVcCUaZDkLimWjtgOwJYniGezDX8d.png"}],"usage":{"total_tokens":4250,"input_tokens":75,"output_tokens":4175,"input_tokens_details":{"text_tokens":75}}}',true);
  114. $endTime = microtime(true);
  115. $executionTime = $endTime - $startTime;
  116. echo "API调用耗时: " . round($executionTime, 3) . " 秒\n";
  117. // 检查 URL 返回是否成功
  118. if (!isset($dalle1024['data'][0]['url']) || empty($dalle1024['data'][0]['url'])) {
  119. $errorText = $dalle1024['error']['message'] ?? '未知错误';
  120. echo '生成失败:' . $errorText;
  121. }
  122. // echo 342342;
  123. // 下载图像
  124. $imgUrl1024 = $dalle1024['data'][0]['url'];
  125. $imgData1024 = @file_get_contents($imgUrl1024);
  126. if (!$imgData1024 || strlen($imgData1024) < 1000) {
  127. return "下载图像失败或内容异常";
  128. }
  129. // echo 3423424444;
  130. // file_put_contents(
  131. // $logDir . 'img_name.txt',
  132. // "\n====图片 " . date('Y-m-d H:i:s') . " ====\n" . $img_name . "\n\n",
  133. // FILE_APPEND
  134. // );
  135. // 保存原图(1024x1024)
  136. // $img_name = $this->limitStringLength($img_name);
  137. $img_name = preg_replace('/[^\x{4e00}-\x{9fa5}A-Za-z0-9_\- ]/u', '', $img_name);
  138. $img_name = mb_substr($img_name, 0, 30); // 限制为前30个字符(避免路径过长)
  139. $filename1024 = $img_name . '.png';
  140. $savePath1024 = $fullBaseDir . '1024x1024/' . $filename1024;
  141. file_put_contents($savePath1024, $imgData1024);
  142. // echo 342344543532;
  143. // 处理缩略图
  144. $im = @imagecreatefromstring($imgData1024);
  145. if (!$im) return "图像格式不受支持或已损坏";
  146. $srcWidth = imagesx($im);
  147. $srcHeight = imagesy($im);
  148. $srcRatio = $srcWidth / $srcHeight;
  149. $dstRatio = $width / $height;
  150. // 居中裁剪逻辑
  151. if ($srcRatio > $dstRatio) {
  152. $cropHeight = $srcHeight;
  153. $cropWidth = intval($srcHeight * $dstRatio);
  154. $srcX = intval(($srcWidth - $cropWidth) / 2);
  155. $srcY = 0;
  156. } else {
  157. $cropWidth = $srcWidth;
  158. $cropHeight = intval($srcWidth / $dstRatio);
  159. $srcX = 0;
  160. $srcY = intval(($srcHeight - $cropHeight) / 2);
  161. }
  162. // echo 789;
  163. $dstImg = imagecreatetruecolor($width, $height);
  164. imagecopyresampled($dstImg, $im, 0, 0, $srcX, $srcY, $width, $height, $cropWidth, $cropHeight);
  165. // 保存裁剪后图像
  166. $filenameCustom = $img_name . ".png";
  167. $savePathCustom = $fullBaseDir . "{$width}x{$height}/" . $filenameCustom;
  168. imagepng($dstImg, $savePathCustom);
  169. imagedestroy($im);
  170. imagedestroy($dstImg);
  171. // file_put_contents(
  172. // $logDir . 'image_url.txt',
  173. // "\n====图片路径 " . date('Y-m-d H:i:s') . " ====\n" . str_replace($rootPath . 'public/', '', $savePath1024) . "\n\n",
  174. // "\n====图片路径 " . date('Y-m-d H:i:s') . " ====\n" . str_replace($rootPath . 'public/', '', $savePathCustom) . "\n\n",
  175. // FILE_APPEND
  176. // );
  177. $status = trim($img_name) === '' ? 0 : 1;
  178. // 更新数据库记录
  179. $updateRes = Db::name('text_to_image')->where('id', $record['id'])->update([
  180. 'new_image_url' => str_replace($rootPath . 'public/', '', $savePath1024),
  181. 'custom_image_url' => str_replace($rootPath . 'public/', '', $savePathCustom),
  182. 'img_name' => $img_name,
  183. 'error_msg' => '',
  184. 'size' => "{$width}x{$height}",
  185. 'updated_time' => date('Y-m-d H:i:s'),
  186. 'status' => $status
  187. ]);
  188. return 0;
  189. }
  190. /**
  191. * 处理字符串长度,超出限制则截断
  192. *
  193. * @param string $str 输入字符串
  194. * @param int $maxLength 最大长度限制(默认200)
  195. * @return string 处理后的字符串
  196. */
  197. public function limitStringLength($str, $maxLength = 10)
  198. {
  199. // 如果字符串长度没有超出限制,直接返回
  200. if (mb_strlen($str, 'UTF-8') <= $maxLength) {
  201. return $str;
  202. }
  203. // 超出限制则截断
  204. return mb_substr($str, 0, $maxLength, 'UTF-8');
  205. }
  206. public function cleanImageUrl($input) {
  207. // 去除字符串首尾空格和中文引号替换为英文引号
  208. $input = trim($input);
  209. $input = str_replace(['“', '”', '‘', '’'], '"', $input);
  210. // 判断是否为纯中文文字
  211. if (preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $input)) {
  212. // 纯中文:替换掉不适合用于文件名的字符
  213. $cleaned = preg_replace('/[\/\\\:\*\?"<>\|,。!¥【】、;‘’“”《》\s]+/u', '', $input);
  214. } elseif (preg_match('/[a-zA-Z]/', $input) && !preg_match('/[\x{4e00}-\x{9fa5}]/u', $input)) {
  215. // 如果是纯字母和空格,且没有中文字符:保留空格,去掉其他符号
  216. $cleaned = preg_replace('/[^a-zA-Z\s]/', '', $input);
  217. } else {
  218. // 如果包含中文或是其他混合字符,按照纯中文的规则清理符号
  219. $cleaned = preg_replace('/[\/\\\:\*\?"<>\|,。!¥【】、;‘’“”《》\s]+/u', '', $input);
  220. }
  221. return $cleaned;
  222. }
  223. /**
  224. * 文生图模型
  225. */
  226. public function callDalleApi($prompt)
  227. {
  228. $data = [
  229. 'prompt' => $prompt,
  230. // 'model' => 'dall-e-2',
  231. 'model' => 'gpt-image-1',
  232. 'n' => 1,
  233. 'size' => '1024x1024',
  234. 'quality' => 'standard',
  235. 'style' => 'vivid',
  236. 'response_format' => 'url'
  237. ];
  238. return $this->callApi($this->config['dalle']['api_url'], $this->config['dalle']['api_key'], $data);
  239. }
  240. /**
  241. * 通用API调用方法
  242. */
  243. public function callApi($url, $apiKey, $data)
  244. {
  245. $maxRetries = 2;
  246. $attempt = 0;
  247. $lastError = '';
  248. while ($attempt <= $maxRetries) {
  249. $ch = curl_init();
  250. curl_setopt_array($ch, [
  251. CURLOPT_URL => $url,
  252. CURLOPT_RETURNTRANSFER => true,
  253. CURLOPT_POST => true,
  254. CURLOPT_POSTFIELDS => json_encode($data),
  255. CURLOPT_HTTPHEADER => [
  256. 'Content-Type: application/json',
  257. 'Authorization: Bearer ' . $apiKey
  258. ],
  259. CURLOPT_TIMEOUT => 120,
  260. CURLOPT_SSL_VERIFYPEER => false,
  261. CURLOPT_SSL_VERIFYHOST => 0,
  262. CURLOPT_TCP_KEEPALIVE => 1,
  263. CURLOPT_FORBID_REUSE => false
  264. ]);
  265. $response = curl_exec($ch);
  266. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  267. $curlError = curl_error($ch);
  268. curl_close($ch);
  269. if ($response !== false && $httpCode === 200) {
  270. $result = json_decode($response, true);
  271. return $result;
  272. }
  273. $lastError = $curlError ?: "HTTP错误:{$httpCode}";
  274. $attempt++;
  275. sleep(1);
  276. }
  277. throw new \Exception("请求失败(重试{$maxRetries}次):{$lastError}");
  278. }
  279. }