TextToImageJob.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. <?php
  2. namespace app\job;
  3. use app\service\AIGatewayService;
  4. use think\Db;
  5. use think\Exception;
  6. use think\Queue;
  7. use think\queue\Job;
  8. /**
  9. * 文生图任务处理类
  10. * 描述:接收提示词,通过模型生成图像,保存图像并记录数据库信息,是链式任务中的最后一环
  11. */
  12. class TextToImageJob
  13. {
  14. /**
  15. * 队列入口方法
  16. * @param Job $job 队列任务对象
  17. * @param array $data 任务传参,包含图像文件名、路径、尺寸、提示词等
  18. */
  19. public function fire(Job $job, $data)
  20. {
  21. $logId = $data['log_id'] ?? null;
  22. try {
  23. // 任务类型校验(必须是文生图)
  24. if (!isset($data['type']) || $data['type'] !== '文生图') {
  25. $job->delete();
  26. return;
  27. }
  28. $startTime = date('Y-m-d H:i:s');
  29. echo "━━━━━━━━━━ ▶ 文生图任务开始处理━━━━━━━━━━\n";
  30. echo "处理时间:{$startTime}\n";
  31. // 更新日志状态:处理中
  32. if ($logId) {
  33. Db::name('image_task_log')->where('id', $logId)->update([
  34. 'status' => 1,
  35. 'log' => '文生图处理中',
  36. 'update_time' => $startTime
  37. ]);
  38. }
  39. // 拼接原图路径
  40. $old_image_url = rtrim($data['sourceDir'], '/') . '/' . ltrim($data['file_name'], '/');
  41. $list = Db::name("text_to_image")
  42. ->where('old_image_url', $old_image_url)
  43. ->where('img_name', '<>', '')
  44. // ->where('status', 0)
  45. ->select();
  46. if (!empty($list)) {
  47. $total = count($list);
  48. echo "📊 共需处理:{$total} 条记录\n";
  49. foreach ($list as $index => $row) {
  50. $currentIndex = $index + 1;
  51. $begin = date('Y-m-d H:i:s');
  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["chinese_description"],
  60. $row["img_name"],
  61. $data["selectedOption"],
  62. $data["executeKeywords"],
  63. $data['sourceDir']
  64. );
  65. // 标准化结果文本
  66. if ($result === true || $result === 1 || $result === '成功') {
  67. $resultText = '成功';
  68. // 日志状态设置为成功(仅在未提前失败时)
  69. if ($logId) {
  70. Db::name('image_task_log')->where('id', $logId)->update([
  71. 'status' => 2,
  72. 'log' => '文生图处理成功',
  73. 'update_time' => date('Y-m-d H:i:s')
  74. ]);
  75. }
  76. } else {
  77. $resultText = (string) $result ?: '失败或无返回';
  78. }
  79. echo "✅ 处理结果:{$resultText}\n";
  80. echo "完成时间:" . date('Y-m-d H:i:s') . "\n";
  81. echo "文生图已处理完成\n";
  82. // 若包含关键词,日志状态标为失败(-1)
  83. if (strpos($resultText, '包含关键词') !== false) {
  84. // 命中关键词类错误,状态设为失败
  85. if ($logId) {
  86. Db::name('image_task_log')->where('id', $logId)->update([
  87. 'status' => -1,
  88. 'log' => $resultText,
  89. 'update_time' => date('Y-m-d H:i:s')
  90. ]);
  91. }
  92. }
  93. }
  94. }
  95. // 处理链式任务(如果有)
  96. if (!empty($data['chain_next'])) {
  97. $nextType = array_shift($data['chain_next']);
  98. $data['type'] = $nextType;
  99. Queue::push('app\job\ImageArrJob', [
  100. 'task_id' => $data['task_id'],
  101. 'data' => [$data]
  102. ], 'arrimage');
  103. }
  104. $job->delete();
  105. } catch (\Exception $e) {
  106. echo "❌ 异常信息: " . $e->getMessage() . "\n";
  107. echo "📄 文件: " . $e->getFile() . "\n";
  108. echo "📍 行号: " . $e->getLine() . "\n";
  109. if ($logId) {
  110. Db::name('image_task_log')->where('id', $logId)->update([
  111. 'status' => -1,
  112. 'log' => '文生图失败:' . $e->getMessage(),
  113. 'update_time' => date('Y-m-d H:i:s')
  114. ]);
  115. }
  116. $job->delete();
  117. }
  118. }
  119. /**
  120. * 任务失败时的处理
  121. */
  122. public function failed($data)
  123. {
  124. // 记录失败日志或发送通知
  125. echo "ImageJob failed: " . json_encode($data);
  126. }
  127. /**
  128. * 文生图处理函数
  129. * 描述:根据提示词调用图像生成接口,保存图像文件,并更新数据库
  130. */
  131. public function textToImage($fileName, $outputDirRaw, $width, $height, $prompt, $img_name, $selectedOption,$executeKeywords,$sourceDir)
  132. {
  133. $rootPath = str_replace('\\', '/', ROOT_PATH);
  134. $outputDir = rtrim($rootPath . 'public/' . $outputDirRaw, '/') . '/';
  135. $dateDir = date('Y-m-d') . '/';
  136. $fullBaseDir = $outputDir . $dateDir;
  137. // 创建输出目录
  138. foreach ([$fullBaseDir, $fullBaseDir . '1024x1024/', $fullBaseDir . "{$width}x{$height}/"] as $dir) {
  139. if (!is_dir($dir)) mkdir($dir, 0755, true);
  140. }
  141. // 确保目录存在
  142. if (!is_dir($fullBaseDir . '2048x2048/')) {
  143. mkdir($fullBaseDir . '2048x2048/', 0755, true);
  144. }
  145. // 获取图像记录
  146. $record = Db::name('text_to_image')
  147. ->where('old_image_url', 'like', "%{$fileName}")
  148. ->order('id desc')
  149. ->find();
  150. Db::name('text_to_image')->where('id', $record['id'])->update([
  151. 'new_image_url' => '',
  152. ]);
  153. if (!$record) return '没有找到匹配的图像记录';
  154. //判断是否执行几何图
  155. if($executeKeywords == false){
  156. // 过滤关键词
  157. $prompt = preg_replace('/[\r\n\t]+/', ' ', $prompt);
  158. foreach (['几何', 'geometry', 'geometric'] as $keyword) {
  159. if (stripos($prompt, $keyword) !== false) {
  160. Db::name('text_to_image')->where('id', $record['id'])->update([
  161. 'status' => 3,
  162. 'error_msg' => "包含关键词".$keyword,
  163. 'update_time' => date('Y-m-d H:i:s')
  164. ]);
  165. return "包含关键词 - {$keyword}";
  166. }
  167. }
  168. }
  169. $template = Db::name('template')
  170. ->field('id,english_content,content')
  171. ->where('path',$sourceDir)
  172. ->where('ids',1)
  173. ->find();
  174. // AI 图像生成调用
  175. $ai = new AIGatewayService();
  176. $response = $ai->callDalleApi($template['content'].$prompt, $selectedOption);
  177. if (isset($response['error'])) {
  178. throw new \Exception("❌ 图像生成失败:" . $response['error']['message']);
  179. }
  180. // 支持 URL 格式(为主)和 base64
  181. $imgData = null;
  182. if (isset($response['data'][0]['url'])) {
  183. $imgData = @file_get_contents($response['data'][0]['url']);
  184. } elseif (isset($response['data'][0]['b64_json'])) {
  185. $imgData = base64_decode($response['data'][0]['b64_json']);
  186. }
  187. if (!$imgData || strlen($imgData) < 1000) {
  188. throw new \Exception("❌ 图像内容为空或异常!");
  189. }
  190. // 保存文件路径定义
  191. $img_name = mb_substr(preg_replace('/[^\x{4e00}-\x{9fa5}A-Za-z0-9_\- ]/u', '', $img_name), 0, 30);
  192. $filename = $img_name . '.png';
  193. $path512 = $fullBaseDir . '1024x1024/' . $filename;
  194. $pathCustom = $fullBaseDir . "{$width}x{$height}/" . $filename;
  195. // 保存原图
  196. file_put_contents($path512, $imgData);
  197. // 数据库更新
  198. Db::name('text_to_image')->where('id', $record['id'])->update([
  199. 'new_image_url' => str_replace($rootPath . 'public/', '', $path512),
  200. // 注释以下一行则不保存裁剪路径(适配你的配置)
  201. // 'custom_image_url' => str_replace($rootPath . 'public/', '', $pathCustom),
  202. 'img_name' => $img_name,
  203. 'model' => $selectedOption,
  204. 'status' => trim($img_name) === '' ? 0 : 1,
  205. 'status_name' => "文生图",
  206. 'size' => "{$width}x{$height}",
  207. 'quality' => 'standard',
  208. 'style' => 'vivid',
  209. 'error_msg' => '',
  210. 'update_time' => date('Y-m-d H:i:s')
  211. ]);
  212. return "成功";
  213. }
  214. public function getImageSeed($taskId)
  215. {
  216. // 配置参数
  217. $apiUrl = 'https://chatapi.onechats.ai/mj/task/' . $taskId . '/fetch';
  218. $apiKey = 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK';
  219. try {
  220. // 初始化cURL
  221. $ch = curl_init();
  222. // 设置cURL选项
  223. curl_setopt_array($ch, [
  224. CURLOPT_URL => $apiUrl,
  225. CURLOPT_RETURNTRANSFER => true,
  226. CURLOPT_CUSTOMREQUEST => 'GET', // 明确指定GET方法
  227. CURLOPT_HTTPHEADER => [
  228. 'Authorization: Bearer ' . $apiKey,
  229. 'Accept: application/json',
  230. 'Content-Type: application/json'
  231. ],
  232. CURLOPT_SSL_VERIFYPEER => false,
  233. CURLOPT_SSL_VERIFYHOST => false,
  234. CURLOPT_TIMEOUT => 60,
  235. CURLOPT_FAILONERROR => true // 添加失败时返回错误
  236. ]);
  237. // 执行请求
  238. $response = curl_exec($ch);
  239. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  240. // 错误处理
  241. if (curl_errno($ch)) {
  242. throw new Exception('cURL请求失败: ' . curl_error($ch));
  243. }
  244. // 关闭连接
  245. curl_close($ch);
  246. // 验证HTTP状态码
  247. if ($httpCode < 200 || $httpCode >= 300) {
  248. throw new Exception('API返回错误状态码: ' . $httpCode);
  249. }
  250. // 解析JSON响应
  251. $responseData = json_decode($response, true);
  252. if (json_last_error() !== JSON_ERROR_NONE) {
  253. throw new Exception('JSON解析失败: ' . json_last_error_msg());
  254. }
  255. // 返回结构化数据
  256. return [
  257. 'success' => true,
  258. 'http_code' => $httpCode,
  259. 'data' => $responseData
  260. ];
  261. } catch (Exception $e) {
  262. // 确保关闭cURL连接
  263. if (isset($ch) && is_resource($ch)) {
  264. curl_close($ch);
  265. }
  266. return [
  267. 'success' => false,
  268. 'error' => $e->getMessage(),
  269. 'http_code' => $httpCode ?? 0
  270. ];
  271. }
  272. }
  273. /**
  274. * 发送API请求
  275. * @param string $url 请求地址
  276. * @param array $data 请求数据
  277. * @param string $apiKey API密钥
  278. * @param string $method 请求方法
  279. * @return string 响应内容
  280. * @throws Exception
  281. */
  282. private function sendApiRequest($url, $data, $apiKey, $method = 'POST')
  283. {
  284. $ch = curl_init();
  285. curl_setopt_array($ch, [
  286. CURLOPT_URL => $url,
  287. CURLOPT_RETURNTRANSFER => true,
  288. CURLOPT_CUSTOMREQUEST => $method,
  289. CURLOPT_HTTPHEADER => [
  290. 'Authorization: Bearer '.$apiKey,
  291. 'Accept: application/json',
  292. 'Content-Type: application/json'
  293. ],
  294. CURLOPT_POSTFIELDS => $method === 'POST' ? json_encode($data) : null,
  295. CURLOPT_SSL_VERIFYPEER => false,
  296. CURLOPT_SSL_VERIFYHOST => false,
  297. CURLOPT_TIMEOUT => 60,
  298. CURLOPT_FAILONERROR => true
  299. ]);
  300. $response = curl_exec($ch);
  301. $error = curl_error($ch);
  302. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  303. curl_close($ch);
  304. if ($error) {
  305. throw new Exception('API请求失败: '.$error);
  306. }
  307. if ($httpCode < 200 || $httpCode >= 300) {
  308. throw new Exception('API返回错误状态码: '.$httpCode);
  309. }
  310. return $response;
  311. }
  312. }