TextToImageJob.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. <?php
  2. namespace app\job;
  3. use app\api\controller\Common;
  4. use app\api\controller\WorkOrder;
  5. use app\service\AIGatewayService;
  6. use think\Db;
  7. use think\Exception;
  8. use think\Queue;
  9. use think\queue\Job;
  10. use Redis;
  11. /**
  12. * 文生图任务处理类
  13. * 描述:接收提示词,通过模型生成图像,保存图像并记录数据库信息,是链式任务中的最后一环
  14. */
  15. class TextToImageJob
  16. {
  17. /**
  18. * 队列入口方法
  19. * @param Job $job 队列任务对象
  20. * @param array $data 任务传参,包含图像文件名、路径、尺寸、提示词等
  21. */
  22. public function fire(Job $job, $data)
  23. {
  24. if (empty($data['status_val']) || $data['status_val'] == '文生图') {
  25. // 获取任务ID
  26. $taskId = $data['task_id'];
  27. // 获取产品ID
  28. $Id = $data['id'];
  29. if (empty($taskId)) {
  30. $job->delete();
  31. return;
  32. }
  33. if (empty($Id)) {
  34. $job->delete();
  35. return;
  36. }
  37. //连接Redis(配置见 application/extra/queue.php)
  38. $redis = getTaskRedis();
  39. echo "\n" . date('Y-m-d H:i:s') . " 任务开始:{$taskId}\n";
  40. // 更新任务状态为处理中
  41. $redis->set("text_to_image_task:{$taskId}", json_encode([
  42. 'status' => 'processing',
  43. 'started_at' => date('Y-m-d H:i:s')
  44. ]), ['EX' => 300]); // 5分钟过期
  45. try {
  46. // 执行图片生成
  47. $result = $this->get_txt_to_img($data);
  48. // sleep(10);
  49. // 更新Redis中的任务状态为成功
  50. $redis->set("text_to_image_task:{$taskId}", json_encode([
  51. 'status' => 'completed',
  52. // 'image_url' => "/uploads/merchant/690377511/6903775111138/newimg/698550113c2b8.jpeg",
  53. 'image_url' => $result,
  54. 'completed_at' => date('Y-m-d H:i:s')
  55. ]), ['EX' => 300]); // 5分钟过期
  56. echo "🎉 任务 {$taskId} 执行完成,图片生成成功!\n";
  57. $job->delete();
  58. } catch (\Exception $e) {
  59. echo "❌ 任务执行失败:" . $e->getMessage() . "\n";
  60. // 检查是否是网络超时错误
  61. if (strpos($e->getMessage(), 'Connection timed out') !== false) {
  62. // 对于超时错误,保持任务状态为处理中,让前端继续查询
  63. echo "⚠️ 检测到网络超时,任务可能仍在执行中\n";
  64. $redis->set("text_to_image_task:{$taskId}", json_encode([
  65. 'status' => 'processing',
  66. 'error' => '网络连接超时,正在重试...',
  67. 'updated_at' => date('Y-m-d H:i:s')
  68. ]), ['EX' => 300]); // 5分钟过期
  69. } else {
  70. // 其他错误,标记为失败
  71. $redis->set("text_to_image_task:{$taskId}", json_encode([
  72. 'status' => 'failed',
  73. 'error' => $e->getMessage(),
  74. 'completed_at' => date('Y-m-d H:i:s')
  75. ]), ['EX' => 300]); // 5分钟过期
  76. }
  77. $job->delete();
  78. } finally {
  79. $job->delete();
  80. }
  81. } else {
  82. $logId = $data['log_id'] ?? null;
  83. try {
  84. // 任务类型校验(必须是文生图)
  85. if (!isset($data['type']) || $data['type'] !== '文生图') {
  86. $job->delete();
  87. return;
  88. }
  89. $startTime = date('Y-m-d H:i:s');
  90. echo "━━━━━━━━━━ ▶ 文生图任务开始处理━━━━━━━━━━\n";
  91. echo "处理时间:{$startTime}\n";
  92. // 更新日志状态:处理中
  93. if ($logId) {
  94. Db::name('image_task_log')->where('id', $logId)->update([
  95. 'status' => 1,
  96. 'log' => '文生图处理中',
  97. 'update_time' => $startTime
  98. ]);
  99. }
  100. // 拼接原图路径
  101. $old_image_url = rtrim($data['sourceDir'], '/') . '/' . ltrim($data['file_name'], '/');
  102. $list = Db::name("text_to_image")
  103. ->where('old_image_url', $old_image_url)
  104. ->where('img_name', '<>', '')
  105. // ->where('status', 0)
  106. ->select();
  107. if (!empty($list)) {
  108. $total = count($list);
  109. echo "📊 共需处理:{$total} 条记录\n";
  110. foreach ($list as $index => $row) {
  111. $currentIndex = $index + 1;
  112. $begin = date('Y-m-d H:i:s');
  113. echo "👉 正在处理第 {$currentIndex} 条,ID: {$row['id']}\n";
  114. // 图像生成
  115. $result = $this->textToImage(
  116. $data["file_name"],
  117. $data["outputDir"],
  118. $data["width"],
  119. $data["height"],
  120. $row["chinese_description"],
  121. $row["img_name"],
  122. $data["selectedOption"],
  123. $data["executeKeywords"],
  124. $data['sourceDir']
  125. );
  126. // 标准化结果文本
  127. if ($result === true || $result === 1 || $result === '成功') {
  128. $resultText = '成功';
  129. // 日志状态设置为成功(仅在未提前失败时)
  130. if ($logId) {
  131. Db::name('image_task_log')->where('id', $logId)->update([
  132. 'status' => 2,
  133. 'log' => '文生图处理成功',
  134. 'update_time' => date('Y-m-d H:i:s')
  135. ]);
  136. }
  137. } else {
  138. $resultText = (string) $result ?: '失败或无返回';
  139. }
  140. echo "✅ 处理结果:{$resultText}\n";
  141. echo "完成时间:" . date('Y-m-d H:i:s') . "\n";
  142. echo "文生图已处理完成\n";
  143. // 若包含关键词,日志状态标为失败(-1)
  144. if (strpos($resultText, '包含关键词') !== false) {
  145. // 命中关键词类错误,状态设为失败
  146. if ($logId) {
  147. Db::name('image_task_log')->where('id', $logId)->update([
  148. 'status' => -1,
  149. 'log' => $resultText,
  150. 'update_time' => date('Y-m-d H:i:s')
  151. ]);
  152. }
  153. }
  154. }
  155. }
  156. // 处理链式任务(如果有)
  157. if (!empty($data['chain_next'])) {
  158. $nextType = array_shift($data['chain_next']);
  159. $data['type'] = $nextType;
  160. Queue::push('app\job\ImageArrJob', [
  161. 'task_id' => $data['task_id'],
  162. 'data' => [$data]
  163. ], 'arrimage');
  164. }
  165. $job->delete();
  166. } catch (\Exception $e) {
  167. echo "❌ 异常信息: " . $e->getMessage() . "\n";
  168. echo "📄 文件: " . $e->getFile() . "\n";
  169. echo "📍 行号: " . $e->getLine() . "\n";
  170. if ($logId) {
  171. Db::name('image_task_log')->where('id', $logId)->update([
  172. 'status' => -1,
  173. 'log' => '文生图失败:' . $e->getMessage(),
  174. 'update_time' => date('Y-m-d H:i:s')
  175. ]);
  176. }
  177. $job->delete();
  178. }
  179. }
  180. $job->delete();
  181. }
  182. /**
  183. * 任务失败时的处理
  184. */
  185. public function failed($data)
  186. {
  187. // 记录失败日志或发送通知
  188. echo "ImageJob failed: " . json_encode($data);
  189. }
  190. public function get_txt_to_img($data){
  191. $status_val = trim($data['status_val']);
  192. $prompt = trim($data['prompt']);
  193. $model = trim($data['model']);
  194. $size = trim($data['size']);
  195. // 获取产品信息
  196. $product = Db::name('product')->where('id', $data['id'])->find();
  197. if (empty($product)) {
  198. return '产品不存在';
  199. }
  200. // 调用AI生成图片
  201. $aiGateway = new AIGatewayService();
  202. $res = $aiGateway->buildRequestData($status_val,$model,$prompt,$size);
  203. // 提取base64图片数据,兼容两种返回格式
  204. $base64_data = null;
  205. $image_type = 'png';
  206. // 新格式:data[0].b64_json 或 data[0].url
  207. if (isset($res['data'][0]['b64_json']) && $res['data'][0]['b64_json']) {
  208. $base64_data = preg_replace('/\s+/', '', $res['data'][0]['b64_json']);
  209. } elseif (isset($res['data'][0]['url']) && $res['data'][0]['url']) {
  210. $imageContent = file_get_contents($res['data'][0]['url']);
  211. $base64_data = base64_encode($imageContent);
  212. }
  213. // 旧格式:candidates[0].content.parts[0].inlineData.data 或 text
  214. elseif (isset($res['candidates'][0]['content']['parts'][0]['inlineData']['data'])) {
  215. $text_content = $res['candidates'][0]['content']['parts'][0]['inlineData']['data'];
  216. // 带前缀 data:image/xxx;base64, 或 裸 base64 都能识别
  217. if (preg_match('/data:image\/(png|jpg|jpeg|webp);base64,(.+)$/is', $text_content, $matches)) {
  218. $image_type = ($matches[1] == 'jpg' ? 'jpeg' : $matches[1]);
  219. $base64_data = preg_replace('/\s+/', '', $matches[2]);
  220. } else {
  221. $base64_data = preg_replace('/\s+/', '', $text_content);
  222. }
  223. } elseif (isset($res['candidates'][0]['content']['parts'][0]['text'])) {
  224. $text_content = $res['candidates'][0]['content']['parts'][0]['text'];
  225. if (preg_match('/data:image\/(png|jpg|jpeg|webp);base64,(.+)$/is', $text_content, $matches)) {
  226. $image_type = ($matches[1] == 'jpg' ? 'jpeg' : $matches[1]);
  227. $base64_data = preg_replace('/\s+/', '', $matches[2]);
  228. } else {
  229. $base64_data = preg_replace('/\s+/', '', $text_content);
  230. }
  231. }
  232. if (empty($base64_data)) {
  233. return '未找到图片数据';
  234. }
  235. $image_data = base64_decode($base64_data);
  236. if ($image_data === false) {
  237. return '图片解码失败';
  238. }
  239. $rootPath = str_replace('\\', '/', ROOT_PATH);
  240. $relDir = '/uploads/ceshi/';
  241. // 生产:$code = $product['product_code'];
  242. // 生产:$relDir = '/uploads/merchant/' . substr($code, 0, 9) . '/' . $code . '/newimg/';
  243. $saveDir = rtrim($rootPath, '/') . '/public' . $relDir;
  244. if (!is_dir($saveDir)) {
  245. mkdir($saveDir, 0755, true);
  246. }
  247. $file_name = uniqid() . '.' . $image_type;
  248. if (!file_put_contents($saveDir . $file_name, $image_data)) {
  249. return '图片保存失败';
  250. }
  251. $db_img_path = $relDir . $file_name;
  252. // 本地落盘成功后同步 OSS(失败不阻断主流程)
  253. Common::uploadLocalFileToOss((string)($saveDir . $file_name), (string)$db_img_path);
  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. }