TextToImageJob.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. <?php
  2. namespace app\job;
  3. use app\api\controller\WorkOrder;
  4. use app\service\AIGatewayService;
  5. use think\Db;
  6. use think\Exception;
  7. use think\Queue;
  8. use think\queue\Job;
  9. use Redis;
  10. /**
  11. * 文生图任务处理类
  12. * 描述:接收提示词,通过模型生成图像,保存图像并记录数据库信息,是链式任务中的最后一环
  13. */
  14. class TextToImageJob
  15. {
  16. /**
  17. * 队列入口方法
  18. * @param Job $job 队列任务对象
  19. * @param array $data 任务传参,包含图像文件名、路径、尺寸、提示词等
  20. */
  21. public function fire(Job $job, $data)
  22. {
  23. if (empty($data['status_val']) || $data['status_val'] == '文生图') {
  24. // 获取任务ID
  25. $taskId = $data['task_id'];
  26. // 获取产品ID
  27. $Id = $data['id'];
  28. if (empty($taskId)) {
  29. $job->delete();
  30. return;
  31. }
  32. if (empty($Id)) {
  33. $job->delete();
  34. return;
  35. }
  36. //连接Redis(配置见 application/extra/queue.php)
  37. $redis = getTaskRedis();
  38. echo "\n" . date('Y-m-d H:i:s') . " 任务开始:{$taskId}\n";
  39. // 更新任务状态为处理中
  40. $redis->set("text_to_image_task:{$taskId}", json_encode([
  41. 'status' => 'processing',
  42. 'started_at' => date('Y-m-d H:i:s')
  43. ]), ['EX' => 300]); // 5分钟过期
  44. try {
  45. // 执行图片生成
  46. $result = $this->get_txt_to_img($data);
  47. // sleep(10);
  48. // 更新Redis中的任务状态为成功
  49. $redis->set("text_to_image_task:{$taskId}", json_encode([
  50. 'status' => 'completed',
  51. // 'image_url' => "/uploads/merchant/690377511/6903775111138/newimg/698550113c2b8.jpeg",
  52. 'image_url' => $result,
  53. 'completed_at' => date('Y-m-d H:i:s')
  54. ]), ['EX' => 300]); // 5分钟过期
  55. echo "🎉 任务 {$taskId} 执行完成,图片生成成功!\n";
  56. $job->delete();
  57. } catch (\Exception $e) {
  58. echo "❌ 任务执行失败:" . $e->getMessage() . "\n";
  59. // 检查是否是网络超时错误
  60. if (strpos($e->getMessage(), 'Connection timed out') !== false) {
  61. // 对于超时错误,保持任务状态为处理中,让前端继续查询
  62. echo "⚠️ 检测到网络超时,任务可能仍在执行中\n";
  63. $redis->set("text_to_image_task:{$taskId}", json_encode([
  64. 'status' => 'processing',
  65. 'error' => '网络连接超时,正在重试...',
  66. 'updated_at' => date('Y-m-d H:i:s')
  67. ]), ['EX' => 300]); // 5分钟过期
  68. } else {
  69. // 其他错误,标记为失败
  70. $redis->set("text_to_image_task:{$taskId}", json_encode([
  71. 'status' => 'failed',
  72. 'error' => $e->getMessage(),
  73. 'completed_at' => date('Y-m-d H:i:s')
  74. ]), ['EX' => 300]); // 5分钟过期
  75. }
  76. $job->delete();
  77. } finally {
  78. $job->delete();
  79. }
  80. } else {
  81. $logId = $data['log_id'] ?? null;
  82. try {
  83. // 任务类型校验(必须是文生图)
  84. if (!isset($data['type']) || $data['type'] !== '文生图') {
  85. $job->delete();
  86. return;
  87. }
  88. $startTime = date('Y-m-d H:i:s');
  89. echo "━━━━━━━━━━ ▶ 文生图任务开始处理━━━━━━━━━━\n";
  90. echo "处理时间:{$startTime}\n";
  91. // 更新日志状态:处理中
  92. if ($logId) {
  93. Db::name('image_task_log')->where('id', $logId)->update([
  94. 'status' => 1,
  95. 'log' => '文生图处理中',
  96. 'update_time' => $startTime
  97. ]);
  98. }
  99. // 拼接原图路径
  100. $old_image_url = rtrim($data['sourceDir'], '/') . '/' . ltrim($data['file_name'], '/');
  101. $list = Db::name("text_to_image")
  102. ->where('old_image_url', $old_image_url)
  103. ->where('img_name', '<>', '')
  104. // ->where('status', 0)
  105. ->select();
  106. if (!empty($list)) {
  107. $total = count($list);
  108. echo "📊 共需处理:{$total} 条记录\n";
  109. foreach ($list as $index => $row) {
  110. $currentIndex = $index + 1;
  111. $begin = date('Y-m-d H:i:s');
  112. echo "👉 正在处理第 {$currentIndex} 条,ID: {$row['id']}\n";
  113. // 图像生成
  114. $result = $this->textToImage(
  115. $data["file_name"],
  116. $data["outputDir"],
  117. $data["width"],
  118. $data["height"],
  119. $row["chinese_description"],
  120. $row["img_name"],
  121. $data["selectedOption"],
  122. $data["executeKeywords"],
  123. $data['sourceDir']
  124. );
  125. // 标准化结果文本
  126. if ($result === true || $result === 1 || $result === '成功') {
  127. $resultText = '成功';
  128. // 日志状态设置为成功(仅在未提前失败时)
  129. if ($logId) {
  130. Db::name('image_task_log')->where('id', $logId)->update([
  131. 'status' => 2,
  132. 'log' => '文生图处理成功',
  133. 'update_time' => date('Y-m-d H:i:s')
  134. ]);
  135. }
  136. } else {
  137. $resultText = (string) $result ?: '失败或无返回';
  138. }
  139. echo "✅ 处理结果:{$resultText}\n";
  140. echo "完成时间:" . date('Y-m-d H:i:s') . "\n";
  141. echo "文生图已处理完成\n";
  142. // 若包含关键词,日志状态标为失败(-1)
  143. if (strpos($resultText, '包含关键词') !== false) {
  144. // 命中关键词类错误,状态设为失败
  145. if ($logId) {
  146. Db::name('image_task_log')->where('id', $logId)->update([
  147. 'status' => -1,
  148. 'log' => $resultText,
  149. 'update_time' => date('Y-m-d H:i:s')
  150. ]);
  151. }
  152. }
  153. }
  154. }
  155. // 处理链式任务(如果有)
  156. if (!empty($data['chain_next'])) {
  157. $nextType = array_shift($data['chain_next']);
  158. $data['type'] = $nextType;
  159. Queue::push('app\job\ImageArrJob', [
  160. 'task_id' => $data['task_id'],
  161. 'data' => [$data]
  162. ], 'arrimage');
  163. }
  164. $job->delete();
  165. } catch (\Exception $e) {
  166. echo "❌ 异常信息: " . $e->getMessage() . "\n";
  167. echo "📄 文件: " . $e->getFile() . "\n";
  168. echo "📍 行号: " . $e->getLine() . "\n";
  169. if ($logId) {
  170. Db::name('image_task_log')->where('id', $logId)->update([
  171. 'status' => -1,
  172. 'log' => '文生图失败:' . $e->getMessage(),
  173. 'update_time' => date('Y-m-d H:i:s')
  174. ]);
  175. }
  176. $job->delete();
  177. }
  178. }
  179. $job->delete();
  180. }
  181. /**
  182. * 任务失败时的处理
  183. */
  184. public function failed($data)
  185. {
  186. // 记录失败日志或发送通知
  187. echo "ImageJob failed: " . json_encode($data);
  188. }
  189. public function get_txt_to_img($data){
  190. $status_val = trim($data['status_val']);
  191. $prompt = trim($data['prompt']);
  192. $model = trim($data['model']);
  193. $size = trim($data['size']);
  194. // 获取产品信息
  195. $product = Db::name('product')->where('id', $data['id'])->find();
  196. if (empty($product)) {
  197. return '产品不存在';
  198. }
  199. // 调用AI生成图片
  200. $aiGateway = new AIGatewayService();
  201. $res = $aiGateway->buildRequestData($status_val,$model,$prompt,$size);
  202. // 提取base64图片数据,兼容两种返回格式
  203. $base64_data = null;
  204. $image_type = 'png';
  205. // 新格式:data[0].b64_json 或 data[0].url
  206. if (isset($res['data'][0]['b64_json']) && $res['data'][0]['b64_json']) {
  207. $base64_data = preg_replace('/\s+/', '', $res['data'][0]['b64_json']);
  208. } elseif (isset($res['data'][0]['url']) && $res['data'][0]['url']) {
  209. $imageContent = file_get_contents($res['data'][0]['url']);
  210. $base64_data = base64_encode($imageContent);
  211. }
  212. // 旧格式:candidates[0].content.parts[0].inlineData.data 或 text
  213. elseif (isset($res['candidates'][0]['content']['parts'][0]['inlineData']['data'])) {
  214. $text_content = $res['candidates'][0]['content']['parts'][0]['inlineData']['data'];
  215. // 带前缀 data:image/xxx;base64, 或 裸 base64 都能识别
  216. if (preg_match('/data:image\/(png|jpg|jpeg|webp);base64,(.+)$/is', $text_content, $matches)) {
  217. $image_type = ($matches[1] == 'jpg' ? 'jpeg' : $matches[1]);
  218. $base64_data = preg_replace('/\s+/', '', $matches[2]);
  219. } else {
  220. $base64_data = preg_replace('/\s+/', '', $text_content);
  221. }
  222. } elseif (isset($res['candidates'][0]['content']['parts'][0]['text'])) {
  223. $text_content = $res['candidates'][0]['content']['parts'][0]['text'];
  224. if (preg_match('/data:image\/(png|jpg|jpeg|webp);base64,(.+)$/is', $text_content, $matches)) {
  225. $image_type = ($matches[1] == 'jpg' ? 'jpeg' : $matches[1]);
  226. $base64_data = preg_replace('/\s+/', '', $matches[2]);
  227. } else {
  228. $base64_data = preg_replace('/\s+/', '', $text_content);
  229. }
  230. }
  231. if (empty($base64_data)) {
  232. return '未找到图片数据';
  233. }
  234. $image_data = base64_decode($base64_data);
  235. if ($image_data === false) {
  236. return '图片解码失败';
  237. }
  238. $rootPath = str_replace('\\', '/', ROOT_PATH);
  239. $relDir = '/uploads/ceshi/';
  240. // 生产:$code = $product['product_code'];
  241. // 生产:$relDir = '/uploads/merchant/' . substr($code, 0, 9) . '/' . $code . '/newimg/';
  242. $saveDir = rtrim($rootPath, '/') . '/public' . $relDir;
  243. if (!is_dir($saveDir)) {
  244. mkdir($saveDir, 0755, true);
  245. }
  246. $file_name = uniqid() . '.' . $image_type;
  247. if (!file_put_contents($saveDir . $file_name, $image_data)) {
  248. return '图片保存失败';
  249. }
  250. $db_img_path = $relDir . $file_name;
  251. echo "<pre>";
  252. print_r($db_img_path);
  253. echo "<pre>";die;
  254. Db::name('product')->where('id', $data['id'])->update([
  255. 'createTime' => date('Y-m-d H:i:s'),
  256. 'content' => $data['prompt'],
  257. 'product_new_img' => $db_img_path
  258. ]);
  259. $record = [
  260. 'product_id' => $data['id'],
  261. 'product_new_img' => $db_img_path,
  262. 'product_content' => $data['prompt'],
  263. 'template_id' => $data['template_id'] ?? 0,
  264. 'createTime' => date('Y-m-d H:i:s'),
  265. ];
  266. Db::name('product_image')->insert($record);
  267. return $db_img_path;
  268. }
  269. /**
  270. * 文生图处理函数
  271. * 描述:根据提示词调用图像生成接口,保存图像文件,并更新数据库
  272. */
  273. public function textToImage($data,$prompt,$img_name)
  274. {
  275. $fileName = $data["file_name"];
  276. $outputDirRaw = $data["outputDir"];
  277. $width = $data["width"];
  278. $height = $data["height"];
  279. $selectedOption = $data["selectedOption"];
  280. $executeKeywords = $data["executeKeywords"];
  281. $sourceDir = $data["sourceDir"];
  282. $rootPath = str_replace('\\', '/', ROOT_PATH);
  283. $outputDir = rtrim($rootPath . 'public/' . $outputDirRaw, '/') . '/';
  284. $dateDir = date('Y-m-d') . '/';
  285. $fullBaseDir = $outputDir . $dateDir;
  286. // 创建输出目录
  287. foreach ([$fullBaseDir, $fullBaseDir . '1024x1024/', $fullBaseDir . "{$width}x{$height}/"] as $dir) {
  288. if (!is_dir($dir)) mkdir($dir, 0755, true);
  289. }
  290. // 确保目录存在
  291. if (!is_dir($fullBaseDir . '2048x2048/')) {
  292. mkdir($fullBaseDir . '2048x2048/', 0755, true);
  293. }
  294. // 获取图像记录
  295. $record = Db::name('text_to_image')
  296. ->where('old_image_url', 'like', "%{$fileName}")
  297. ->order('id desc')
  298. ->find();
  299. Db::name('text_to_image')->where('id', $record['id'])->update([
  300. 'new_image_url' => '',
  301. ]);
  302. if (!$record) return '没有找到匹配的图像记录';
  303. //判断是否执行几何图
  304. if($executeKeywords == false){
  305. // 过滤关键词
  306. $prompt = preg_replace('/[\r\n\t]+/', ' ', $prompt);
  307. foreach (['几何', 'geometry', 'geometric'] as $keyword) {
  308. if (stripos($prompt, $keyword) !== false) {
  309. Db::name('text_to_image')->where('id', $record['id'])->update([
  310. 'status' => 3,
  311. 'error_msg' => "包含关键词".$keyword,
  312. 'update_time' => date('Y-m-d H:i:s')
  313. ]);
  314. return "包含关键词 - {$keyword}";
  315. }
  316. }
  317. }
  318. $template = Db::name('template')
  319. ->field('id,english_content,content')
  320. ->where('path',$sourceDir)
  321. ->where('ids',1)
  322. ->find();
  323. // AI 图像生成调用
  324. $ai = new AIGatewayService();
  325. $response = $ai->buildRequestData('文生图',$template['content'].$prompt, $selectedOption);
  326. if (isset($response['error'])) {
  327. throw new \Exception("❌ 图像生成失败:" . $response['error']['message']);
  328. }
  329. // 支持 URL 格式(为主)和 base64
  330. $imgData = null;
  331. if (isset($res['candidates'][0]['content']['parts'][0]['text'])) {
  332. $text_content = $res['candidates'][0]['content']['parts'][0]['text'];
  333. // 匹配base64图片数据
  334. preg_match('/data:image\/(png|jpg|jpeg);base64,([^"]+)/', $text_content, $matches);
  335. if (empty($matches)) {
  336. return '未找到图片数据';
  337. }
  338. $image_type = $matches[1];
  339. $base64_data = $matches[2];
  340. // 解码base64数据
  341. $imgData = base64_decode($base64_data);
  342. }else if (isset($response['data'][0]['url'])) {
  343. $imgData = @file_get_contents($response['data'][0]['url']);
  344. } elseif (isset($response['data'][0]['b64_json'])) {
  345. $imgData = base64_decode($response['data'][0]['b64_json']);
  346. }
  347. if (!$imgData || strlen($imgData) < 1000) {
  348. throw new \Exception("❌ 图像内容为空或异常!");
  349. }
  350. // 保存文件路径定义
  351. $img_name = mb_substr(preg_replace('/[^\x{4e00}-\x{9fa5}A-Za-z0-9_\- ]/u', '', $img_name), 0, 30);
  352. $filename = $img_name . '.png';
  353. $path512 = $fullBaseDir . '1024x1024/' . $filename;
  354. $pathCustom = $fullBaseDir . "{$width}x{$height}/" . $filename;
  355. // 保存原图
  356. file_put_contents($path512, $imgData);
  357. // 数据库更新
  358. Db::name('text_to_image')->where('id', $record['id'])->update([
  359. 'new_image_url' => str_replace($rootPath . 'public/', '', $path512),
  360. // 注释以下一行则不保存裁剪路径(适配你的配置)
  361. // 'custom_image_url' => str_replace($rootPath . 'public/', '', $pathCustom),
  362. 'img_name' => $img_name,
  363. 'model' => $selectedOption,
  364. 'status' => trim($img_name) === '' ? 0 : 1,
  365. 'status_name' => "文生图",
  366. 'size' => "{$width}x{$height}",
  367. 'quality' => 'standard',
  368. 'style' => 'vivid',
  369. 'error_msg' => '',
  370. 'update_time' => date('Y-m-d H:i:s')
  371. ]);
  372. return "成功";
  373. }
  374. public function getImageSeed($taskId)
  375. {
  376. // 配置参数
  377. $apiUrl = 'https://chatapi.onechats.ai/mj/task/' . $taskId . '/fetch';
  378. $apiKey = 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK';
  379. try {
  380. // 初始化cURL
  381. $ch = curl_init();
  382. // 设置cURL选项
  383. curl_setopt_array($ch, [
  384. CURLOPT_URL => $apiUrl,
  385. CURLOPT_RETURNTRANSFER => true,
  386. CURLOPT_CUSTOMREQUEST => 'GET', // 明确指定GET方法
  387. CURLOPT_HTTPHEADER => [
  388. 'Authorization: Bearer ' . $apiKey,
  389. 'Accept: application/json',
  390. 'Content-Type: application/json'
  391. ],
  392. CURLOPT_SSL_VERIFYPEER => false,
  393. CURLOPT_SSL_VERIFYHOST => false,
  394. CURLOPT_TIMEOUT => 60,
  395. CURLOPT_FAILONERROR => true // 添加失败时返回错误
  396. ]);
  397. // 执行请求
  398. $response = curl_exec($ch);
  399. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  400. // 错误处理
  401. if (curl_errno($ch)) {
  402. throw new Exception('cURL请求失败: ' . curl_error($ch));
  403. }
  404. // 关闭连接
  405. curl_close($ch);
  406. // 验证HTTP状态码
  407. if ($httpCode < 200 || $httpCode >= 300) {
  408. throw new Exception('API返回错误状态码: ' . $httpCode);
  409. }
  410. // 解析JSON响应
  411. $responseData = json_decode($response, true);
  412. if (json_last_error() !== JSON_ERROR_NONE) {
  413. throw new Exception('JSON解析失败: ' . json_last_error_msg());
  414. }
  415. // 返回结构化数据
  416. return [
  417. 'success' => true,
  418. 'http_code' => $httpCode,
  419. 'data' => $responseData
  420. ];
  421. } catch (Exception $e) {
  422. // 确保关闭cURL连接
  423. if (isset($ch) && is_resource($ch)) {
  424. curl_close($ch);
  425. }
  426. return [
  427. 'success' => false,
  428. 'error' => $e->getMessage(),
  429. 'http_code' => $httpCode ?? 0
  430. ];
  431. }
  432. }
  433. /**
  434. * 发送API请求
  435. * @param string $url 请求地址
  436. * @param array $data 请求数据
  437. * @param string $apiKey API密钥
  438. * @param string $method 请求方法
  439. * @return string 响应内容
  440. * @throws Exception
  441. */
  442. private function sendApiRequest($url, $data, $apiKey, $method = 'POST')
  443. {
  444. $ch = curl_init();
  445. curl_setopt_array($ch, [
  446. CURLOPT_URL => $url,
  447. CURLOPT_RETURNTRANSFER => true,
  448. CURLOPT_CUSTOMREQUEST => $method,
  449. CURLOPT_HTTPHEADER => [
  450. 'Authorization: Bearer '.$apiKey,
  451. 'Accept: application/json',
  452. 'Content-Type: application/json'
  453. ],
  454. CURLOPT_POSTFIELDS => $method === 'POST' ? json_encode($data) : null,
  455. CURLOPT_SSL_VERIFYPEER => false,
  456. CURLOPT_SSL_VERIFYHOST => false,
  457. CURLOPT_TIMEOUT => 60,
  458. CURLOPT_FAILONERROR => true
  459. ]);
  460. $response = curl_exec($ch);
  461. $error = curl_error($ch);
  462. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  463. curl_close($ch);
  464. if ($error) {
  465. throw new Exception('API请求失败: '.$error);
  466. }
  467. if ($httpCode < 200 || $httpCode >= 300) {
  468. throw new Exception('API返回错误状态码: '.$httpCode);
  469. }
  470. return $response;
  471. }
  472. }