ImageService.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. <?php
  2. namespace app\service;
  3. use app\service\AIGatewayService;
  4. use think\Db;
  5. use think\Exception;
  6. use think\Queue;
  7. /**
  8. * ImageService 类用于处理图像任务和存放日志队列。
  9. * 该类将前端传过来的多个图像信息推送到处理队列中。
  10. */
  11. class ImageService{
  12. /**
  13. * 直接调用图生文API并返回结果
  14. * @param array $params 请求参数,包含文生文提示词、模型类型等
  15. * @return array GPT生成的结果
  16. */
  17. public function handleImgToText($params) {
  18. Queue::push('app\job\ImageArrJob', $params, "arrimage");
  19. return true;
  20. }
  21. /**
  22. * 文生文
  23. * @param array $params 请求参数,包含文生文提示词、模型类型等
  24. * @return array GPT生成的结果
  25. */
  26. public function handleTextToText($prompt,$model) {
  27. $ai = new AIGatewayService();
  28. $gptRes = $ai->txtGptApi($prompt, $model);
  29. // 根据不同模型解析返回结果
  30. $gptText = '';
  31. if (strpos($model, 'gemini') !== false && isset($gptRes['candidates'][0]['content']['parts'][0]['text'])) {
  32. $gptText = trim($gptRes['candidates'][0]['content']['parts'][0]['text']);
  33. } elseif (isset($gptRes['choices'][0]['message']['content'])) {
  34. $gptText = trim($gptRes['choices'][0]['message']['content']);
  35. } else {
  36. throw new Exception('AI API返回格式错误');
  37. }
  38. return [
  39. 'success' => true,
  40. 'message' => '生成成功',
  41. 'data' => $gptText
  42. ];
  43. }
  44. /**
  45. * 直接调用文生图API并返回结果
  46. * @param array $params 请求参数,包含文生文提示词、模型类型等
  47. * @return array GPT生成的结果
  48. */
  49. public function handleTextToImg($params) {
  50. Queue::push('app\job\ImageArrJob', $params, "arrimage");
  51. return true;
  52. }
  53. /**
  54. * 推送图像任务到队列(支持链式和单独模式)
  55. * @param array $params 请求参数,包含图像批次、模型类型、尺寸等
  56. */
  57. public function handleImage($params) {
  58. if (!isset($params["batch"])) {return false;}
  59. $arr = [];
  60. // 获取图像批量信息
  61. $batch = $params["batch"];
  62. // 获取执行次数数量
  63. $num = $params["num"];
  64. /*获取ids为1模板
  65. * english_content 文生文提示词
  66. * content 图生文提示词
  67. * */
  68. $template = Db::name('template')
  69. ->field('id,english_content,content,ids')
  70. ->where('path',$params['old_image_file'])
  71. ->where('ids',1)
  72. ->find();
  73. // 构建任务基础结构(每图生成 N 份任务)
  74. foreach ($batch as $k => $v) {
  75. $baseItem = [
  76. "sourceDir" => $this->sourceDir($v, 1),
  77. "outputDir" => $this->sourceDir($v, 2),
  78. "file_name" => $this->sourceDir($v, 3),
  79. "type" => $params['type'] ?? '',
  80. "selectedOption" => $params['selectedOption'],//文生图模型
  81. "txttotxt_selectedOption" => $params['txttotxt_selectedOption'],//文生文模型
  82. "imgtotxt_selectedOption" => $params['imgtotxt_selectedOption'],//图生文模型
  83. "prompt" => '',
  84. "width" => $params['width'],
  85. "height" => $params['height'],
  86. "executeKeywords" => $params['executeKeywords'],//是否执行几何图
  87. "sys_id" => $params['sys_id']//用户
  88. ];
  89. // 创建$num个相同的项目并合并到$arr
  90. $arr = array_merge($arr, array_fill(0, $num, $baseItem));
  91. }
  92. // 插入队列日志
  93. $insertData = [
  94. 'create_time' => date('Y-m-d H:i:s'),
  95. 'old_image_file' => $params['old_image_file'],
  96. 'status' => '等待中',
  97. 'image_count' => count($arr),
  98. 'params' => json_encode($params, JSON_UNESCAPED_UNICODE)
  99. ];
  100. //模型任务类型处理
  101. if (empty($params['type'])) {
  102. /*
  103. * 执行全部任务时一键链式任务队列
  104. * 用于存放队列日志
  105. * 链式任务:图生文 → 文生文 → 文生图
  106. * */
  107. $insertData['model'] = "gpt-4-vision-preview,"."gpt-4,".$params['selectedOption'];
  108. $insertData['model_name'] = '文生图';
  109. $task_id = Db::name('queue_logs')->insertGetId($insertData);
  110. $arr = array_map(function ($item) use ($task_id) {
  111. $item['type'] = '图生文';
  112. $item['chain_next'] = ['文生文', '文生图','图生图','高清放大'];
  113. $item['task_id'] = $task_id;
  114. return $item;
  115. }, $arr);
  116. $payload = [
  117. 'task_id' => $task_id,
  118. 'data' => $arr
  119. ];
  120. Queue::push('app\job\ImageArrJob', $payload, "arrimage");
  121. } else {
  122. // 指定单个独立任务类型
  123. switch ($params['type']) {
  124. case '图生文':
  125. $insertData['model'] = 'gpt-4-vision-preview';
  126. $insertData['model_name'] = '图生文';
  127. break;
  128. case '文生文':
  129. $insertData['model'] = $params['txttotxt_selectedOption'];
  130. $insertData['model_name'] = '文生文';
  131. break;
  132. case '文生图':
  133. $insertData['model'] = $params['selectedOption'];
  134. $insertData['model_name'] = '文生图';
  135. break;
  136. case '图生图':
  137. $insertData['model'] = "realisticVisionV51_v51VAE-inpainting.safetensors [f0d4872d24]";
  138. $insertData['model_name'] = '图生图';
  139. break;
  140. case '高清放大':
  141. $insertData['model'] = "高清放大";
  142. $insertData['model_name'] = '高清放大';
  143. break;
  144. default:
  145. return false;
  146. }
  147. //将一组队列存放queue_logs任务表中,将新增id最为任务id记录
  148. $task_id = Db::name('queue_logs')->insertGetId($insertData);
  149. $arr = array_map(function ($item) use ($params, $task_id) {
  150. $item['type'] = $params['type'];
  151. $item['task_id'] = $task_id;
  152. return $item;
  153. }, $arr);
  154. // 投递任务到队列
  155. $payload = [
  156. 'task_id' => $task_id,
  157. 'data' => $arr
  158. ];
  159. Queue::push('app\job\ImageArrJob', $payload, "arrimage");
  160. }
  161. return true;
  162. }
  163. /**
  164. * 解析图像路径,返回不同组成部分
  165. *
  166. * @param string $filePath 图像路径(如 uploads/operate/ai/Preview/20240610/xxx.png)
  167. * @param int $type 返回内容类型:
  168. * 1 = 基础路径(去掉日期+文件名)
  169. * sourceDir 源目录uploads/operate/ai/Preview/
  170. * 2 = 输出路径(Preview 替换为 dall-e,并加日期代表当天数据存到当天文件夹中)
  171. * outputDir 输出目录/uploads/operate/ai/dall-e/hua/并加日期
  172. * 3 = 文件名
  173. * file_name 文件名0194b6fdd6203fda369d5e3b74b6b454.png
  174. * @return string|null
  175. */
  176. public function sourceDir($filePath, $type) {
  177. $arr = [];
  178. $pathParts = explode('/', $filePath);
  179. $filename = array_pop($pathParts); // 最后是文件名
  180. $baseParts = $pathParts;
  181. // 查找是否有 8 位数字(即日期)文件夹
  182. $date = '';
  183. foreach ($pathParts as $index => $part) {
  184. if (preg_match('/^\d{8}$/', $part)) {
  185. $date = $part;
  186. unset($baseParts[$index]); // 日期不算在 basePath 里
  187. break;
  188. }
  189. }
  190. $arr = [
  191. 'basePath' => implode('/', $baseParts),
  192. 'date' => $date,
  193. 'filename' => $filename
  194. ];
  195. // 根据类型返回不同路径
  196. if ($type == 1) {
  197. return $arr["basePath"];
  198. }
  199. if ($type == 2) {
  200. return '/' . str_replace('/Preview/', '/dall-e/', $arr["basePath"]) . $arr["date"];
  201. }
  202. if ($type == 3) {
  203. return $arr["filename"];
  204. }
  205. }
  206. }