liuhairui il y a 1 jour
Parent
commit
a4da018264

+ 374 - 0
application/api/controller/Index.php

@@ -187,6 +187,210 @@ class Index extends Api
         }
     }
 
+    /**
+     * 图生图本地测试
+     * 原图+参考图+提示词=生成新图
+     * 已替换为公开测试图(免本地文件)+ 通用提示词
+     */
+    public function GET_ImgToImg()
+    {
+        // 【通用简化提示词】:明确图生图核心需求,适配测试场景
+        $prompt = '参考第二张模板图片的轻奢设计风格、光影布局、纯色背景和产品展示比例,将第一张可乐产品图的主体替换到模板的核心位置,保留模板的所有非产品设计元素,生成1:1高清产品效果图,无水印、无多余文字,画质清晰';
+
+        $size = '1:1';// 生成图片比例
+        $model = 'gemini-3-pro-image-preview'; // 当前使用的模型
+        $numImages = 1; // 生成图像数量,gemini模型目前只支持生成1张
+
+        // 支持多图像生成的模型:dall-e-3, black-forest-labs/FLUX.1-kontext-pro, gpt-image-1
+        // 这些模型通过设置 'n' 参数来指定生成图像数量
+
+        // 检查模型是否支持多图像生成
+        $supportMultiImages = in_array($model, ['dall-e-3', 'black-forest-labs/FLUX.1-kontext-pro', 'gpt-image-1']);
+        if ($supportMultiImages && $numImages > 1) {
+            // 对于支持多图像生成的模型,可以设置生成数量
+            $n = $numImages;
+        }
+        /**************************
+         * 替换为:公开测试图(直接转Base64,无需本地文件)
+         * 图1:产品图(可乐罐,通用测试)
+         * 图2:模版图(轻奢产品展示背景,通用测试)
+         **************************/
+            // 产品图:公开可乐图URL
+            $productImgUrl = 'https://s41.ax1x.com/2026/02/02/pZ4crcj.jpg';
+            // 模版图:公开轻奢产品展示背景图URL
+            $templateImgUrl = 'https://s41.ax1x.com/2026/02/02/pZ4cw4S.jpg';
+
+            // 封装:URL转纯Base64(去前缀)+ MIME类型,无需本地文件,直接测试
+            function urlToPureBase64($imgUrl) {
+                $imgContent = file_get_contents($imgUrl);
+                if (!$imgContent) throw new Exception("图片URL读取失败");
+
+                // 通过文件扩展名确定MIME类型
+                $extension = strtolower(pathinfo($imgUrl, PATHINFO_EXTENSION));
+                $mimeTypes = [
+                    'jpg' => 'image/jpeg',
+                    'jpeg' => 'image/jpeg',
+                    'png' => 'image/png',
+                    'gif' => 'image/gif',
+                    'webp' => 'image/webp'
+                ];
+                $mime = $mimeTypes[$extension] ?? 'image/jpeg';
+
+                $base64 = base64_encode($imgContent);
+                return ['mime' => $mime, 'base64' => $base64];
+            }
+
+        try {
+            // 获取两张测试图的纯Base64和MIME
+            $productImg = urlToPureBase64($productImgUrl);
+            $templateImg = urlToPureBase64($templateImgUrl);
+
+            // ########## 构造API请求参数(适配gemini-3-pro-image-preview) ##########
+            $data = [
+                "contents" => [
+                    [
+                        "role" => "user",
+                        "parts" => [
+                            ["text" => $prompt],
+                            // 产品图
+                            ["inlineData" => [
+                                "mimeType" => $productImg['mime'],
+                                "data" => $productImg['base64']
+                            ]],
+                            // 模版图
+                            ["inlineData" => [
+                                "mimeType" => $templateImg['mime'],
+                                "data" => $templateImg['base64']
+                            ]]
+                        ]
+                    ]
+                ],
+                "generationConfig" => [
+                    "responseModalities" => ["IMAGE"],
+                    "imageConfig" => ["aspectRatio" => $size, "quality" => "HIGH"],
+                    "temperature" => 0.6,
+                    "topP" => 0.9,
+                    "maxOutputTokens" => 2048
+                ]
+            ];
+
+            // ########## 调用API ##########
+            $apiUrl = 'https://chatapi.onechats.ai/v1beta/models/gemini-3-pro-image-preview:generateContent';
+            $apiKey = 'sk-9aIV9nx7pJxJFMrB8REtNbhjYuNBxCcnEOwiJDHd6UwmN2eJ';
+            $result = AIGatewayService::callApi($apiUrl, $apiKey, $data);
+
+            // 处理响应
+            if (isset($result['candidates'][0]['content']['parts'][0]['inlineData']['data'])) {
+                // 直接从inlineData获取图片数据
+                $base64_data = $result['candidates'][0]['content']['parts'][0]['inlineData']['data'];
+                $image_type = 'jpg'; // 默认类型
+
+                // 解码base64数据
+                $image_data = base64_decode($base64_data);
+                if ($image_data === false) {
+                    return json([
+                        'code' => 1,
+                        'msg' => '图片解码失败',
+                        'data' => null
+                    ]);
+                }
+
+                // 保存图片
+                $saveDir = ROOT_PATH . 'public/uploads/img2img/';
+                if (!is_dir($saveDir)) {
+                    mkdir($saveDir, 0755, true);
+                }
+
+                $fileName = 'img2img-' . time() . '.' . $image_type;
+                $savePath = $saveDir . $fileName;
+                if (!file_put_contents($savePath, $image_data)) {
+                    return json([
+                        'code' => 1,
+                        'msg' => '图片保存失败',
+                        'data' => null
+                    ]);
+                }
+
+                // 生成访问路径
+                $accessPath = '/uploads/img2img/' . $fileName;
+
+                return json([
+                    'code' => 0,
+                    'msg' => '图生图已生成',
+                    'data' => [
+                        'image' => $accessPath,
+                        'model' => $model,
+                        'support_multi_images' => $supportMultiImages
+                    ]
+                ]);
+            } else if (isset($result['candidates'][0]['content']['parts'][0]['text'])) {
+                // 尝试从文本响应中提取图片
+                $text_content = $result['candidates'][0]['content']['parts'][0]['text'];
+                preg_match('/data:image\/(png|jpg|jpeg);base64,([^"]+)/', $text_content, $matches);
+                if (empty($matches)) {
+                    return json([
+                        'code' => 1,
+                        'msg' => '未找到图片数据',
+                        'data' => null
+                    ]);
+                }
+                $image_type = $matches[1];
+                $base64_data = $matches[2];
+
+                // 解码base64数据
+                $image_data = base64_decode($base64_data);
+                if ($image_data === false) {
+                    return json([
+                        'code' => 1,
+                        'msg' => '图片解码失败',
+                        'data' => null
+                    ]);
+                }
+
+                // 保存图片
+                $saveDir = ROOT_PATH . 'public/uploads/img2img/';
+                if (!is_dir($saveDir)) {
+                    mkdir($saveDir, 0755, true);
+                }
+
+                $fileName = 'img2img-' . time() . '.' . $image_type;
+                $savePath = $saveDir . $fileName;
+                if (!file_put_contents($savePath, $image_data)) {
+                    return json([
+                        'code' => 1,
+                        'msg' => '图片保存失败',
+                        'data' => null
+                    ]);
+                }
+
+                // 生成访问路径
+                $accessPath = '/uploads/img2img/' . $fileName;
+
+                return json([
+                    'code' => 0,
+                    'msg' => '图生图已生成',
+                    'data' => [
+                        'image' => $accessPath,
+                        'model' => $model,
+                        'support_multi_images' => $supportMultiImages
+                    ]
+                ]);
+            } else {
+                return json([
+                    'code' => 1,
+                    'msg' => 'API返回格式错误',
+                    'data' => null
+                ]);
+            }
+        } catch (Exception $e) {
+            return json([
+                'code' => 1,
+                'msg' => 'API调用失败:' . $e->getMessage(),
+                'data' => null
+            ]);
+        }
+    }
+
     /**
      * 图生图本地测试
      */
@@ -405,4 +609,174 @@ class Index extends Api
             return json(['code' => 1, 'msg' => '保存结果失败:' . $e->getMessage()]);
         }
     }
+
+    /**
+     * 文本生成图片并保存第一张结果
+     * @param array $params 请求参数
+     * @return array 返回结果
+     */
+    public function txttowimg()
+    {
+        // API配置
+        $config = [
+            'api_url' => 'https://chatapi.onechats.ai/mj/submit/imagine',
+            'fetch_url' => 'https://chatapi.onechats.ai/mj/task/',
+            'api_key' => 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK',
+            'default_prompt' => '一个猫',
+            'wait_time' => 3 // 等待生成完成的秒数
+        ];
+        try {
+            // 1. 准备请求数据
+            $prompt =  $config['default_prompt'];
+            $postData = [
+                'botType' => 'MID_JOURNEY',
+                'prompt' => $prompt,
+                'base64Array' => [],
+                'accountFilter' => [
+                    'channelId' => "",
+                    'instanceId' => "",
+                    'modes' => [],
+                    'remark' => "",
+                    'remix' => true,
+                    'remixAutoConsidered' => true
+                ],
+                'notifyHook' => "",
+                'state' => ""
+            ];
+
+            // 2. 提交生成请求
+            $generateResponse = $this->sendApiRequest($config['api_url'], $postData, $config['api_key']);
+            $generateData = json_decode($generateResponse, true);
+            if (empty($generateData['result'])) {
+                throw new Exception('生成失败: '.($generateData['message'] ?? '未知错误'));
+            }
+            $taskId = $generateData['result'];
+            // 3. 等待图片生成完成
+            sleep($config['wait_time']);
+            // 4. 获取生成结果
+            $fetchUrl = $config['fetch_url'].$taskId.'/fetch';
+            $fetchResponse = $this->sendApiRequest($fetchUrl, [], $config['api_key'], 'GET');
+            $fetchData = json_decode($fetchResponse, true);
+            if (empty($fetchData['imageUrl'])) {
+                throw new Exception('获取图片失败: '.($fetchData['message'] ?? '未知错误'));
+            }
+            // 5. 处理返回的图片数组(取第一张)
+            $imageUrls = is_array($fetchData['imageUrl']) ? $fetchData['imageUrl'] : [$fetchData['imageUrl']];
+            $firstImageUrl = $imageUrls[0];
+            // 6. 保存图片到本地
+            $savePath = $this->saveImage($firstImageUrl);
+            // 7. 返回结果
+            return [
+                'code' => 200,
+                'msg' => '图片生成并保存成功',
+                'data' => [
+                    'local_path' => $savePath,
+                    'web_url' => request()->domain().$savePath,
+                    'task_id' => $taskId
+                ]
+            ];
+        } catch (Exception $e) {
+            // 错误处理
+            return [
+                'code' => 500,
+                'msg' => '处理失败: '.$e->getMessage(),
+                'data' => null
+            ];
+        }
+    }
+
+    /**
+     * 发送API请求
+     * @param string $url 请求地址
+     * @param array $data 请求数据
+     * @param string $apiKey API密钥
+     * @param string $method 请求方法
+     * @return string 响应内容
+     * @throws Exception
+     */
+    private function sendApiRequest($url, $data, $apiKey, $method = 'POST')
+    {
+        $ch = curl_init();
+
+        curl_setopt_array($ch, [
+            CURLOPT_URL => $url,
+            CURLOPT_RETURNTRANSFER => true,
+            CURLOPT_CUSTOMREQUEST => $method,
+            CURLOPT_HTTPHEADER => [
+                'Authorization: Bearer '.$apiKey,
+                'Accept: application/json',
+                'Content-Type: application/json'
+            ],
+            CURLOPT_POSTFIELDS => $method === 'POST' ? json_encode($data) : null,
+            CURLOPT_SSL_VERIFYPEER => false,
+            CURLOPT_SSL_VERIFYHOST => false,
+            CURLOPT_TIMEOUT => 60,
+            CURLOPT_FAILONERROR => true
+        ]);
+
+        $response = curl_exec($ch);
+        $error = curl_error($ch);
+        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+        curl_close($ch);
+
+        if ($error) {
+            throw new Exception('API请求失败: '.$error);
+        }
+
+        if ($httpCode < 200 || $httpCode >= 300) {
+            throw new Exception('API返回错误状态码: '.$httpCode);
+        }
+
+        return $response;
+    }
+
+    /**
+     * 保存图片到本地
+     * @param string $imageUrl 图片URL
+     * @return string 本地保存路径
+     * @throws Exception
+     */
+    private function saveImage($imageUrl)
+    {
+        // 1. 创建存储目录
+        $saveDir = ROOT_PATH.'public'.DS.'uploads'.DS.'midjourney'.DS.date('Ymd');
+        if (!is_dir($saveDir)) {
+            mkdir($saveDir, 0755, true);
+        }
+
+        // 2. 生成唯一文件名
+        $filename = uniqid().'.png';
+        $localPath = DS.'uploads'.DS.'midjourney'.DS.date('Ymd').DS.$filename;
+        $fullPath = $saveDir.DS.$filename;
+
+        // 3. 下载图片
+        $ch = curl_init($imageUrl);
+        curl_setopt_array($ch, [
+            CURLOPT_RETURNTRANSFER => true,
+            CURLOPT_FOLLOWLOCATION => true,
+            CURLOPT_SSL_VERIFYPEER => false,
+            CURLOPT_CONNECTTIMEOUT => 15
+        ]);
+
+        $imageData = curl_exec($ch);
+        $error = curl_error($ch);
+        curl_close($ch);
+
+        if (!$imageData) {
+            throw new Exception('图片下载失败: '.$error);
+        }
+
+        // 4. 验证图片类型
+        $imageInfo = getimagesizefromstring($imageData);
+        if (!in_array($imageInfo['mime'] ?? '', ['image/png', 'image/jpeg'])) {
+            throw new Exception('下载内容不是有效图片');
+        }
+
+        // 5. 保存文件
+        if (!file_put_contents($fullPath, $imageData)) {
+            throw new Exception('图片保存失败');
+        }
+
+        return $localPath;
+    }
 }

+ 15 - 2
application/api/controller/Product.php

@@ -89,6 +89,7 @@ class Product extends Api
             $total = \db('product')
                 ->alias('a')
                 ->join('product_merchant b', 'a.merchant_id = b.id')
+                ->where('a.deleteTime', null)
                 ->where($where)
                 ->count();
 
@@ -101,12 +102,14 @@ class Product extends Api
                     'a.product_name as 产品名称',
                     'a.product_code as 产品编码',
                     'a.product_img',
+                    'a.deleteTime',
                     'a.product_new_img',
                     'a.createTime as 创建时间',
                     'a.create_name as 创建人',
                     'b.merchant_code as 商户编码',
                     'a.id'
                 ])
+                ->where('a.deleteTime', null)
                 ->order('a.createTime', 'desc')
                 ->page($page, $pageSize)
                 ->select();
@@ -247,6 +250,7 @@ class Product extends Api
                 ->where('id', $productId)
                 ->whereNull('deleteTime')
                 ->find();
+
         } catch (\Exception $e) {
             $this->error('查询产品详情失败:' . $e->getMessage());
         }
@@ -281,8 +285,17 @@ class Product extends Api
         // 7. 移除原始图片字段,保持返回数据整洁
         unset($product['product_img'], $product['product_new_img']);
 
-        // 8. 返回成功结果
-        $this->success('获取产品详情成功', $product);
+        $product_image = \db('product_image')
+            ->where('product_id', $productId)
+            ->order('id desc')
+            ->select();
+
+        return json([
+            'code' => 0,
+            'msg' => '获取产品详情成功',
+            'image' => $product_image,//历史图片
+            'data' => $product
+        ]);
     }
 
     /**

+ 414 - 277
application/api/controller/WorkOrder.php

@@ -17,7 +17,6 @@ class WorkOrder extends Api{
     protected $noNeedLogin = ['*'];
     protected $noNeedRight = ['*'];
     public function index(){echo '访问成功';}
-
     /**
      * AI队列入口处理  出图接口
      * 此方法处理图像转换为文本的请求,将图像信息存入队列以供后续处理。
@@ -30,13 +29,11 @@ class WorkOrder extends Api{
         $this->success('任务成功提交至队列');
     }
 
-
     /**
      * product 产品专用统一api调用接口
      * AI模型调用接口
      */
     public function GetTxtToTxt(){
-
         $params = $this->request->param();
 
         $prompt = $params['prompt'];//提示词
@@ -64,21 +61,20 @@ class WorkOrder extends Api{
                         2. 不要包含非文本元素的描述
                         3. 不要添加任何额外的引导语、解释或开场白
                         4. 语言流畅自然";
-                $result = $service->handleTextToText($fullPrompt, $model);
-
-                if(!empty($params['id'])){
-                    Db::name('product')->where('id',  $params['id'])->update(['content' => $result['data']]);
-                }
+            $result = $service->handleTextToText($fullPrompt, $model);
 
-                $res = [
-                    'code' => 0,
-                    'msg' => '优化成功',
-                    'content' => $result['data']
-                ];
-                return json($res);
+            if(!empty($params['id'])){
+                Db::name('product')->where('id',  $params['id'])->update(['content' => $result['data']]);
+            }
+            $res = [
+                'code' => 0,
+                'msg' => '优化成功',
+                'content' => $result['data']
+            ];
+            return json($res);
 
         }elseif($params['status_val'] == '文生图'){
-           $service->handleTextToImg($params);
+            $service->handleTextToImg($params);
             $res = [
                 'code' => 0,
                 'msg' => '正在生成图片中,请稍等.....'
@@ -89,6 +85,335 @@ class WorkOrder extends Api{
         }
     }
 
+    /**
+     * 即梦AI--创建视频任务接口
+     * 首帧图 + 尾帧图 = 新效果视频
+     */
+    public function Create_ImgToVideo()
+    {
+        $aiGateway = new AIGatewayService();
+        $apiUrl = $aiGateway->config['Create_ImgToVideo']['api_url'];
+        $apiKey = $aiGateway->config['Create_ImgToVideo']['api_key'];
+
+        $params = $this->request->param();
+        $modelParams = [
+            'resolution' => $params['resolution'] ?? '720p',        // 分辨率:480p, 720p, 1080p
+            'duration' => $params['duration'] ?? 5,                  // 视频时长(秒)
+            'camerafixed' => $params['camerafixed'] ?? false,        // 相机固定
+            'watermark' => $params['watermark'] ?? true,             // 水印
+            'aspect_ratio' => $params['aspect_ratio'] ?? '16:9'      // 视频比例:16:9, 4:3, 1:1等
+        ];
+        // 构建提示词
+        $prompt = $params['prompt'] ?? '';
+        $prompt .= ' --resolution ' . $modelParams['resolution'];
+        $prompt .= ' --duration ' . $modelParams['duration'];
+        $prompt .= ' --camerafixed ' . ($modelParams['camerafixed'] ? 'true' : 'false');
+        $prompt .= ' --watermark ' . ($modelParams['watermark'] ? 'true' : 'false');
+        $prompt .= ' --aspect_ratio ' . $modelParams['aspect_ratio'];
+
+        // 构建请求数据
+        $data = [
+            'model' => 'doubao-seedance-1-0-pro-250528',//模型
+            'content' => [
+                [
+                    'type' => 'text',
+                    'text' => $prompt
+                ],
+                [
+                    'type' => 'image_url',
+                    'image_url' => [
+                        'url' => $params['first_image_url']// 首帧图片URL(参数)
+                    ],
+                    'role' => 'first_image'
+                ],
+                [
+                    'type' => 'image_url',
+                    'image_url' => [
+                        'url' => $params['last_image_url'] // 尾帧图片URL(参数)
+                    ],
+                    'role' => 'last_image'
+                ]
+            ]
+        ];
+        // 转换为 JSON 字符串
+        $jsonData = json_encode($data);
+
+        // 初始化 cURL
+        $ch = curl_init();
+        curl_setopt($ch, CURLOPT_URL, $apiUrl);
+        curl_setopt($ch, CURLOPT_POST, true);
+        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
+        curl_setopt($ch, CURLOPT_HTTPHEADER, [
+            'Content-Type: application/json',
+            'Authorization: Bearer ' . $apiKey
+        ]);
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 开发环境临时关闭SSL验证
+        curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 超时时间
+
+        // 执行请求
+        $response = curl_exec($ch);
+
+        // 检查 cURL 错误
+        if (curl_errno($ch)) {
+            $error = curl_error($ch);
+            curl_close($ch);
+            return json(['code' => 0, 'msg' => 'Curl 错误: ' . $error]);
+        }
+        curl_close($ch);
+
+        // 解析响应
+        $responseData = json_decode($response, true);
+
+        // 检查 API 错误
+        if (isset($responseData['error'])) {
+            return json(['code' => 0, 'msg' => 'API 错误: ' . $responseData['error']['message']]);
+        }
+
+        // 获取任务 ID
+        $taskId = $responseData['id'] ?? '';
+        if (empty($taskId)) {
+            return json(['code' => 0, 'msg' => '获取任务 ID 失败']);
+        }
+
+        // 返回结果
+        return json([
+            'code' => 1,
+            'data' => [
+                'task_id' => $taskId,
+                'status' => $responseData['status'] ?? '',
+                'created_at' => $responseData['created_at'] ?? ''
+            ]
+        ]);
+    }
+
+    /**
+     * 即梦AI--获取视频接口
+     * 首帧图 + 尾帧图 = 新效果视频
+     */
+    public function Get_ImgToVideo()
+    {
+        $aiGateway = new AIGatewayService();
+        $apiUrl = $aiGateway->config['Create_ImgToVideo']['api_url'];
+        $apiKey = $aiGateway->config['Create_ImgToVideo']['api_key'];
+
+        $params = $this->request->param();
+        $taskId = $params['task_id'] ?? '';
+        if (empty($taskId)) {
+            return json(['code' => 0, 'msg' => '任务 ID 不能为空']);
+        }
+
+        // 查询任务状态
+        $queryUrl = $apiUrl . '/' . $taskId;
+        $ch2 = curl_init();
+        curl_setopt($ch2, CURLOPT_URL, $queryUrl);
+        curl_setopt($ch2, CURLOPT_HTTPHEADER, [
+            'Content-Type: application/json',
+            'Authorization: Bearer ' . $apiKey
+        ]);
+        curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
+        curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false); // 开发环境临时关闭SSL验证
+        curl_setopt($ch2, CURLOPT_TIMEOUT, 60); // 超时时间
+
+        $queryResponse = curl_exec($ch2);
+
+        // 检查 cURL 错误
+        if (curl_errno($ch2)) {
+            $error = curl_error($ch2);
+            curl_close($ch2);
+            return json(['code' => 0, 'msg' => 'Curl 错误: ' . $error]);
+        }
+        curl_close($ch2);
+
+        // 解析查询响应
+        $queryData = json_decode($queryResponse, true);
+        // print_r($queryData);die;
+
+        // 轮询任务状态,直到完成
+        $maxPolls = 30; // 最大轮询次数
+        $pollCount = 0;
+        $taskStatus = $queryData['status'] ?? '';
+
+        while (!in_array($taskStatus, ['completed', 'succeeded']) && $pollCount < $maxPolls) {
+            sleep(5); // 每5秒轮询一次
+            $pollCount++;
+
+            // 再次查询任务状态
+            $ch3 = curl_init();
+            curl_setopt($ch3, CURLOPT_URL, $queryUrl);
+            curl_setopt($ch3, CURLOPT_HTTPHEADER, [
+                'Content-Type: application/json',
+                'Authorization: Bearer ' . $apiKey
+            ]);
+            curl_setopt($ch3, CURLOPT_RETURNTRANSFER, true);
+            curl_setopt($ch3, CURLOPT_SSL_VERIFYPEER, false);
+            curl_setopt($ch3, CURLOPT_TIMEOUT, 60);
+
+            $pollResponse = curl_exec($ch3);
+            curl_close($ch3);
+
+            $pollData = json_decode($pollResponse, true);
+            $taskStatus = $pollData['status'] ?? '';
+
+            // 检查任务是否失败
+            if ($taskStatus === 'failed') {
+                return json(['code' => 0, 'msg' => '任务执行失败']);
+            }
+        }
+
+        // 如果任务已经成功,直接使用 $queryData
+        if (empty($pollData) && isset($queryData['status']) && $queryData['status'] === 'succeeded') {
+            $pollData = $queryData;
+        }
+
+        // 检查轮询是否超时
+        if (!in_array($taskStatus, ['completed', 'succeeded'])) {
+            return json(['code' => 0, 'msg' => '任务执行超时']);
+        }
+
+        // 获取视频 URL
+        $videoUrl = $pollData['content']['video_url'] ?? '';
+        if (empty($videoUrl)) {
+            return json(['code' => 0, 'msg' => '获取视频 URL 失败', 'data' => ['pollData' => $pollData]]);
+        }
+
+        // 确保保存目录存在
+        $saveDir = ROOT_PATH . 'public/uploads/ceshi/';
+        if (!is_dir($saveDir)) {
+            mkdir($saveDir, 0755, true);
+        }
+
+        // 生成保存文件名
+        $fileName =  $taskId . '.mp4';
+        $savePath = $saveDir . '/' . $fileName;
+
+        // 下载视频
+        // 设置超时时间为300秒(5分钟)
+        $context = stream_context_create(['http' => ['timeout' => 300]]);
+        $videoContent = file_get_contents($videoUrl, false, $context);
+        if ($videoContent === false) {
+            return json(['code' => 0, 'msg' => '下载视频失败', 'data' => ['videoUrl' => $videoUrl]]);
+        }
+
+        // 保存视频到文件
+        $saveResult = file_put_contents($savePath, $videoContent);
+        if ($saveResult === false) {
+            return json(['code' => 0, 'msg' => '保存视频失败', 'data' => ['savePath' => $savePath, 'dirWritable' => is_writable($saveDir)]]);
+        }
+
+        // 生成视频的访问 URL
+        $videoAccessUrl = '/uploads/ceshi/' . $fileName;
+
+        // 返回结果
+        return json([
+            'code' => 1,
+            'data' => [
+                'task_id' => $taskId,
+                'status' => $taskStatus,
+                'video_url' => $videoAccessUrl,
+                'save_path' => $savePath
+            ]
+        ]);
+    }
+
+    /**
+     * 九个分镜头生成流程
+     * 模型:gemini-3-pro-image-preview
+     * 说明:
+     * 第一步:(提示词 + 原始图片 = 九个分镜头图片) 或 (提示词 = 九个分镜头图片)
+     * 第二步:使用九个分镜头图进行裁剪单图生成连贯视频
+     * 第三步:在通过分镜头视频拼接成一个完整的视频(列如每个分镜头视频为8秒,九个为72秒形成完整视频)
+     */
+//    public function Get_txttonineimg()
+//    {
+//        // 发起接口请求
+////        $apiUrl = 'https://chatapi.onechats.ai/v1beta/models/gemini-3-pro-image-preview:generateContent';
+//        $apiUrl = 'https://chatapi.onechats.ai/v1beta/models/gemini-3-pro-image-preview:streamGenerateContent';
+//        $apiKey = 'sk-9aIV9nx7pJxJFMrB8REtNbhjYuNBxCcnEOwiJDHd6UwmN2eJ';
+//
+////        $params = $this->request->param();
+//        $prompt = '生成一个苹果(九个分镜头图片)';
+//
+//        $requestData = [
+//            "contents" => [
+//                [
+//                    "role" => "user",
+//                    "parts" => [
+//                        ["text" => $prompt]
+//                    ]
+//                ]
+//            ],
+//            "generationConfig" => [
+//                "responseModalities" => ["TEXT", "IMAGE"],
+//                "imageConfig" => [
+//                    "aspectRatio" => "1:1"
+//                ]
+//            ]
+//        ];
+//
+//        $ch = curl_init();
+//        curl_setopt($ch, CURLOPT_URL, $apiUrl);
+//        curl_setopt($ch, CURLOPT_POST, true);
+//        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData, JSON_UNESCAPED_UNICODE));
+//        curl_setopt($ch, CURLOPT_HTTPHEADER, [
+//            'Content-Type: application/json',
+//            'Authorization: Bearer ' . $apiKey
+//        ]);
+//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+//        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 开发环境临时关闭SSL验证
+//        curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 生成图片超时时间(建议60秒)
+//
+//        $response = curl_exec($ch);
+//        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+//
+//        $error = curl_error($ch);
+//        curl_close($ch);
+//        $res = json_decode($response, true);
+//
+//        // 构建URL路径(使用正斜杠)
+//        $url_path = '/uploads/txtnewimg/';
+//        // 构建物理路径(使用正斜杠确保统一格式)
+//        $save_path = ROOT_PATH . 'public' . '/' . 'uploads' . '/' . 'txtnewimg'  . '/';
+//        // 移除ROOT_PATH中可能存在的反斜杠,确保统一使用正斜杠
+//        $save_path = str_replace('\\', '/', $save_path);
+//        // 自动创建文件夹(如果不存在)
+//        if (!is_dir($save_path)) {
+//            mkdir($save_path, 0755, true);
+//        }
+//
+//        // 提取base64图片数据
+//        $text_content = $res['candidates'][0]['content']['parts'][0]['inlineData']['data'];
+//        $str = 'data:image/jpeg;base64,';
+//        $text_content = $str. $text_content;
+//        // 匹配base64图片数据
+//        preg_match('/data:image\/(png|jpg|jpeg);base64,([^"]+)/', $text_content, $matches);
+//        if (empty($matches)) {
+//            return '未找到图片数据';
+//        }
+//        $image_type = $matches[1];
+//        $base64_data = $matches[2];
+//
+//        // 解码base64数据
+//        $image_data = base64_decode($base64_data);
+//        if ($image_data === false) {
+//            return '图片解码失败';
+//        }
+//
+//        // 生成唯一文件名(包含扩展名)
+//        $file_name = uniqid() . '.' . $image_type;
+//        $full_file_path = $save_path . $file_name;
+//
+//        // 保存图片到文件系统
+//        if (!file_put_contents($full_file_path, $image_data)) {
+//            return '图片保存失败';
+//        }
+//        // 生成数据库存储路径(使用正斜杠格式)
+//        $db_img_path = $url_path . $file_name;
+//        return  $db_img_path;
+//    }
+
+
+
     public function GetTxtToImg(){
         $params = $this->request->param();
 
@@ -120,7 +445,7 @@ class WorkOrder extends Api{
 
          // 创建保存目录(public/uploads/log/YYYY-MM/)
          $yearMonth = date('Ym');
-         $saveDir = ROOT_PATH . 'public/uploads/log/' . $yearMonth . '/';
+         $saveDir = ROOT_PATH . 'public/uploads/ceshi/' . $yearMonth . '/';
          if (!is_dir($saveDir)) {
              mkdir($saveDir, 0755, true);
          }
@@ -135,7 +460,7 @@ class WorkOrder extends Api{
          }
 
          // 生成前端可访问的URL
-         $imageUrl = '/uploads/log/' . $yearMonth . '/' . $fileName;
+         $imageUrl = '/uploads/ceshi/' . $yearMonth . '/' . $fileName;
 
         // 返回标准JSON响应
         return json([
@@ -143,7 +468,6 @@ class WorkOrder extends Api{
             'msg' => '图片生成成功',
             'data' => [
                 'url' => $imageUrl
-//                'url' => '/uploads/log/202601/695b141099d1e.jpeg'
             ]
         ]);
     }
@@ -152,15 +476,15 @@ class WorkOrder extends Api{
      * 学生端文生视频接口 - 用于生成视频
      */
     public function GetTxtToVideo(){
+        $aiGateway = new AIGatewayService();
+        $apiUrl = $aiGateway->config['videos']['api_url'];
+        $apiKey = $aiGateway->config['videos']['api_key'];
+
         // 获取并验证参数
         $params = $this->request->param();
-//    echo "<pre>";
-//    print_r($params);
-//    echo "<pre>";die;
-
-        // 正常的视频生成请求处理
-        $apiUrl = 'https://chatapi.onechats.ai/v1/videos';
-        $apiKey = 'sk-sWW1GFlnjbrDRb1DkMEzePIxgdvLK6cZt0Qg93yDMVP2z1yN';
+        //    echo "<pre>";
+        //    print_r($params);
+        //    echo "<pre>";die;
 
         $postData = [
             'prompt' => $params['prompt'],
@@ -325,8 +649,11 @@ class WorkOrder extends Api{
             ]);
         }
 
+        $aiGateway = new AIGatewayService();
+//        $apiUrl = $aiGateway->config['videos']['api_url'];
+        $apiKey = $aiGateway->config['videos']['api_key'];
+
         $apiUrl = 'https://chatapi.onechats.ai/v1/videos/' . $videoId;
-        $apiKey = 'sk-sWW1GFlnjbrDRb1DkMEzePIxgdvLK6cZt0Qg93yDMVP2z1yN';
 
         // 先检查本地是否已经有该视频
         $localVideoPath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $videoId . '.mp4';
@@ -405,22 +732,7 @@ class WorkOrder extends Api{
         ]);
     }
 
-    //获取服务器URL IP地址:端口
-    public function GetHttpUrl(){
-        $data = Db::name('http_url')->find();
-        $fullUrl = "http://" . $data['baseUrl'] . ":" . $data['port'];
-        $res = [
-            'code' => 0,
-            'msg' => '成功',
-            'data' => [
-                'full_url' => $fullUrl,
-                'id' => $data['id'],
-                'baseUrl' => $data['baseUrl'],
-                'port' => $data['port']
-            ]
-        ];
-        return json($res);
-    }
+
 
 
     //获取视频列表
@@ -458,10 +770,11 @@ class WorkOrder extends Api{
      */
     //文生视频
     public function video(){
-        $params = $this->request->param();
+        $aiGateway = new AIGatewayService();
+        $apiUrl = $aiGateway->config['videos']['api_url'];
+        $apiKey = $aiGateway->config['videos']['api_key'];
 
-        $apiUrl = 'https://chatapi.onechats.ai/v1/videos';
-        $apiKey = 'sk-sWW1GFlnjbrDRb1DkMEzePIxgdvLK6cZt0Qg93yDMVP2z1yN';
+        $params = $this->request->param();
         $postData = [
             'prompt' => $params['prompt'],
             'model' => $params['model'],
@@ -752,181 +1065,6 @@ class WorkOrder extends Api{
         ];
     }
 
-    /**
-     * 文本生成图片并保存第一张结果
-     * @param array $params 请求参数
-     * @return array 返回结果
-     */
-    public function txttowimg()
-    {
-        // API配置
-        $config = [
-            'api_url' => 'https://chatapi.onechats.ai/mj/submit/imagine',
-            'fetch_url' => 'https://chatapi.onechats.ai/mj/task/',
-            'api_key' => 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK',
-            'default_prompt' => '一个猫',
-            'wait_time' => 3 // 等待生成完成的秒数
-        ];
-        try {
-            // 1. 准备请求数据
-            $prompt =  $config['default_prompt'];
-            $postData = [
-                'botType' => 'MID_JOURNEY',
-                'prompt' => $prompt,
-                'base64Array' => [],
-                'accountFilter' => [
-                    'channelId' => "",
-                    'instanceId' => "",
-                    'modes' => [],
-                    'remark' => "",
-                    'remix' => true,
-                    'remixAutoConsidered' => true
-                ],
-                'notifyHook' => "",
-                'state' => ""
-            ];
-
-            // 2. 提交生成请求
-            $generateResponse = $this->sendApiRequest($config['api_url'], $postData, $config['api_key']);
-            $generateData = json_decode($generateResponse, true);
-            if (empty($generateData['result'])) {
-                throw new Exception('生成失败: '.($generateData['message'] ?? '未知错误'));
-            }
-            $taskId = $generateData['result'];
-            // 3. 等待图片生成完成
-            sleep($config['wait_time']);
-            // 4. 获取生成结果
-            $fetchUrl = $config['fetch_url'].$taskId.'/fetch';
-            $fetchResponse = $this->sendApiRequest($fetchUrl, [], $config['api_key'], 'GET');
-            $fetchData = json_decode($fetchResponse, true);
-            if (empty($fetchData['imageUrl'])) {
-                throw new Exception('获取图片失败: '.($fetchData['message'] ?? '未知错误'));
-            }
-            // 5. 处理返回的图片数组(取第一张)
-            $imageUrls = is_array($fetchData['imageUrl']) ? $fetchData['imageUrl'] : [$fetchData['imageUrl']];
-            $firstImageUrl = $imageUrls[0];
-            // 6. 保存图片到本地
-            $savePath = $this->saveImage($firstImageUrl);
-            // 7. 返回结果
-            return [
-                'code' => 200,
-                'msg' => '图片生成并保存成功',
-                'data' => [
-                    'local_path' => $savePath,
-                    'web_url' => request()->domain().$savePath,
-                    'task_id' => $taskId
-                ]
-            ];
-        } catch (Exception $e) {
-            // 错误处理
-            return [
-                'code' => 500,
-                'msg' => '处理失败: '.$e->getMessage(),
-                'data' => null
-            ];
-        }
-    }
-
-    /**
-     * 发送API请求
-     * @param string $url 请求地址
-     * @param array $data 请求数据
-     * @param string $apiKey API密钥
-     * @param string $method 请求方法
-     * @return string 响应内容
-     * @throws Exception
-     */
-    private function sendApiRequest($url, $data, $apiKey, $method = 'POST')
-    {
-        $ch = curl_init();
-
-        curl_setopt_array($ch, [
-            CURLOPT_URL => $url,
-            CURLOPT_RETURNTRANSFER => true,
-            CURLOPT_CUSTOMREQUEST => $method,
-            CURLOPT_HTTPHEADER => [
-                'Authorization: Bearer '.$apiKey,
-                'Accept: application/json',
-                'Content-Type: application/json'
-            ],
-            CURLOPT_POSTFIELDS => $method === 'POST' ? json_encode($data) : null,
-            CURLOPT_SSL_VERIFYPEER => false,
-            CURLOPT_SSL_VERIFYHOST => false,
-            CURLOPT_TIMEOUT => 60,
-            CURLOPT_FAILONERROR => true
-        ]);
-
-        $response = curl_exec($ch);
-        $error = curl_error($ch);
-        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
-        curl_close($ch);
-
-        if ($error) {
-            throw new Exception('API请求失败: '.$error);
-        }
-
-        if ($httpCode < 200 || $httpCode >= 300) {
-            throw new Exception('API返回错误状态码: '.$httpCode);
-        }
-
-        return $response;
-    }
-
-    /**
-     * 保存图片到本地
-     * @param string $imageUrl 图片URL
-     * @return string 本地保存路径
-     * @throws Exception
-     */
-    private function saveImage($imageUrl)
-    {
-        // 1. 创建存储目录
-        $saveDir = ROOT_PATH.'public'.DS.'uploads'.DS.'midjourney'.DS.date('Ymd');
-        if (!is_dir($saveDir)) {
-            mkdir($saveDir, 0755, true);
-        }
-
-        // 2. 生成唯一文件名
-        $filename = uniqid().'.png';
-        $localPath = DS.'uploads'.DS.'midjourney'.DS.date('Ymd').DS.$filename;
-        $fullPath = $saveDir.DS.$filename;
-
-        // 3. 下载图片
-        $ch = curl_init($imageUrl);
-        curl_setopt_array($ch, [
-            CURLOPT_RETURNTRANSFER => true,
-            CURLOPT_FOLLOWLOCATION => true,
-            CURLOPT_SSL_VERIFYPEER => false,
-            CURLOPT_CONNECTTIMEOUT => 15
-        ]);
-
-        $imageData = curl_exec($ch);
-        $error = curl_error($ch);
-        curl_close($ch);
-
-        if (!$imageData) {
-            throw new Exception('图片下载失败: '.$error);
-        }
-
-        // 4. 验证图片类型
-        $imageInfo = getimagesizefromstring($imageData);
-        if (!in_array($imageInfo['mime'] ?? '', ['image/png', 'image/jpeg'])) {
-            throw new Exception('下载内容不是有效图片');
-        }
-
-        // 5. 保存文件
-        if (!file_put_contents($fullPath, $imageData)) {
-            throw new Exception('图片保存失败');
-        }
-
-        return $localPath;
-    }
-
-
-
-
-
-
     /**
      * 查询队列列表
      * 统计文件对应的队列情况
@@ -1030,14 +1168,34 @@ class WorkOrder extends Api{
     }
 
     /**
-     * 显示当前运行中的队列监听进程
+     * 获取 Redis 连接实例
+     * @return \Redis|null Redis 实例或 null(如果连接失败)
      */
-    public function viewQueueStatus()
+    private function getRedisConnection()
     {
+        if (!class_exists('\Redis')) {
+            return null;
+        }
         $redis = new \Redis();
         $redis->connect('127.0.0.1', 6379);
         $redis->auth('123456');
         $redis->select(15);
+        return $redis;
+    }
+
+    /**
+     * 显示当前运行中的队列监听进程
+     */
+    public function viewQueueStatus()
+    {
+        $redis = $this->getRedisConnection();
+        if (!$redis) {
+            return json([
+                'code' => 1,
+                'msg' => 'Redis扩展未安装或未启用',
+                'data' => null
+            ]);
+        }
 
         $key = 'queues:imgtotxt';
 
@@ -1074,7 +1232,6 @@ class WorkOrder extends Api{
      */
     public function stopQueueProcesses()
     {
-
         Db::name('image_task_log')
             ->where('log', '队列中')
             ->whereOr('status', 1)
@@ -1094,10 +1251,14 @@ class WorkOrder extends Api{
                 'mod_rq' => date('Y-m-d H:i:s')
             ]);
 
-        $redis = new \Redis();
-        $redis->connect('127.0.0.1', 6379);
-        $redis->auth('123456');
-        $redis->select(15);
+        $redis = $this->getRedisConnection();
+        if (!$redis) {
+            return json([
+                'code' => 1,
+                'msg' => 'Redis扩展未安装或未启用',
+                'data' => null
+            ]);
+        }
 
         $key_txttoimg = 'queues:txttoimg:reserved';
         $key_txttotxt = 'queues:txttotxt:reserved';
@@ -1155,44 +1316,12 @@ class WorkOrder extends Api{
 //            ]);
 //        }
 //    }
-    /**
-     * 通过店铺ID-查询对应店铺表数据
-     *
-     */
-    public function PatternApi()
-    {
-        $params = $this->request->param('pattern_id', '');
-        $tableName = 'pattern-' . $params;
-
-        // 连接 MongoDB
-        $mongo = Db::connect('mongodb');
-
-        // 查询指定 skc 的数据
-        $data = $mongo->table($tableName)
-            ->field('
-                name,
-                skc,
-                file
-            ')
-            ->where("skc", '0853004152036')
-            ->select();
-
-        $data = json_decode(json_encode($data), true);  // 数组
-
-        return json([
-            'code' => 0,
-            'msg' => '获取成功',
-            'data' => $data
-        ]);
-    }
-
 
     /**
-     * 新增产品模版
+     * 新增模版
      */
     public function Add_Product_Template(){
         try {
-            // 获取请求参数
             $params = $this->request->param();
 
             $chinese_description  = $params['chinese_description'] ?? '';
@@ -1223,46 +1352,38 @@ class WorkOrder extends Api{
                 'sys_rq' => date('Y-m-d'),
                 'create_time' => date('Y-m-d H:i:s')
             ];
-
 //            echo "<pre>";
 //            print_r($data);
 //            echo "<pre>";die;
-            // 记录插入的数据用于调试
-//            Log::record('准备插入模板数据: ' . json_encode($data), 'info');
-
             $result = Db::name('product_template')->insert($data);
-
             if ($result) {
-//                Log::record('模板保存成功,插入数据: ' . json_encode($data), 'info');
                 return json(['code' => 0, 'msg' => '模板保存成功']);
             } else {
-//                Log::record('模板保存失败,插入数据: ' . json_encode($data) . ',受影响行数: ' . $result, 'error');
                 return json(['code' => 1, 'msg' => '模板保存失败: 数据库操作未影响任何行']);
             }
         } catch (\Exception $e) {
-            // 捕获并记录异常信息
             Log::record('模板保存异常: ' . $e->getMessage(), 'error');
             Log::record('异常堆栈: ' . $e->getTraceAsString(), 'error');
             return json(['code' => 1, 'msg' => '模板保存失败: ' . $e->getMessage()]);
         }
     }
 
-
     /**
-     * 查询产品模版
+     * 查询模版
      */
     public function product_template()
     {
         $params = $this->request->param();
-
         // 构建查询条件
         $where = [];
         if (!empty($params['search'])) {
             $where['chinese_description'] = ['like', '%' . $params['search'] . '%'];
         }
-
-        // 查询模版表
-        $products = Db::name('product_template')->order('id desc')->where($where)->select();
+        // 查询模版表-style分类名称
+        $products = Db::name('product_template')->order('id desc')->where($where)
+            ->where('type','文生图')
+            ->whereNull('mod_rq')
+            ->select();
 
         $http_url = Db::name('http_url')->field('baseUrl,port')->find();
         if ($products && $http_url) {
@@ -1275,7 +1396,6 @@ class WorkOrder extends Api{
                 }
             }
         }
-
         return json([
             'code' => 0,
             'msg' => '请求成功',
@@ -1283,6 +1403,23 @@ class WorkOrder extends Api{
         ]);
     }
 
-
-
+    /**
+     *获取服务器URL地址和端口 IP地址:端口
+     * 用于获取图片路径拼接时
+     **/
+    public function GetHttpUrl(){
+        $data = Db::name('http_url')->find();
+        $fullUrl = "http://" . $data['baseUrl'] . ":" . $data['port'];
+        $res = [
+            'code' => 0,
+            'msg' => '成功',
+            'data' => [
+                'id' => $data['id'],
+                'full_url' => $fullUrl,
+                'baseUrl' => $data['baseUrl'],
+                'port' => $data['port']
+            ]
+        ];
+        return json($res);
+    }
 }

+ 13 - 1
application/config.php

@@ -8,7 +8,7 @@ return [
     // 应用命名空间
     'app_namespace'          => 'app',
     // 应用调试模式
-    'app_debug'              => Env::get('app.debug', false),
+    'app_debug'              => Env::get('app.debug', true),
     // 应用Trace
     'app_trace'              => Env::get('app.trace', false),
     // 应用模式状态
@@ -183,6 +183,18 @@ return [
         // 缓存有效期 0表示永久缓存
         'expire' => 0,
     ],
+//    'cache'   =>  [
+//        // 默认缓存驱动
+//        'default' => 'redis',
+//        // 缓存连接方式为Redis缓存
+//        'type'    => 'redis',
+//        // Redis服务器连接信息
+//        'host'    => Env::get('redis.hostname', '127.0.0.1'),
+//        'port'    => Env::get('redis.hostport', '6379'),
+//        'password' => Env::get('redis.password', '123456'),
+//        'select'   => Env::get('redis.select', 1),
+//        'timeout'  => Env::get('redis.timeout', 500),
+//    ],
     // +----------------------------------------------------------------------
     // | 会话设置
     // +----------------------------------------------------------------------

+ 6 - 41
application/database.php

@@ -16,15 +16,17 @@ return [
 
     // 数据库类型
     'type'            => Env::get('database.type', 'mysql'),
-    // 服务器地址
+
     'hostname'        => Env::get('database.hostname', '20.0.16.128'),
-    // 数据库名
     'database'        => Env::get('database.database', 'ai_mesdb'),
-    // 用户名
     'username'        => Env::get('database.username', 'ai_mesdb'),
-    // 密码
     'password'        => Env::get('database.password', 'xAPLXSPXGWDRCtnG'),
 
+//    'hostname'        => Env::get('database.hostname', '127.0.0.1'),
+//    'database'        => Env::get('database.database', 'ai_mesdb'),
+//    'username'        => Env::get('database.username', 'ai_mesdb'),
+//    'password'        => Env::get('database.password', 'xAPLXSPXGWDRCtnG'),
+
     // 端口
     'hostport'        => Env::get('database.hostport', '3306'),
     // 连接dsn
@@ -60,55 +62,18 @@ return [
         // type 和 query 必须写成这个类名(如果你用的是 think-mongo 1.1)
         'type'        => '\think\mongo\Connection',
         'query'       => '\think\mongo\Query',
-
         // MongoDB 服务器信息
         'hostname'    => '20.0.16.79',   // 改成你的MongoDB服务器IP
         'hostport'    => 27017,          // 默认端口
-
         // 数据库名(⚠️ 必须填写)
         'database'    => 'qiqi',
-
         // 账号密码(如果没有就留空)
         'username'    => '',
         'password'    => '',
-
         // 认证源(如果没启用认证就可以留空或删除这行)
         'params'      => [],
-
         // 其他配置
         'pk_convert_id' => false,  // 推荐false,防止ObjectId自动转字符串
         'debug'          => true,  // 开启调试
     ],
-
-    'db3' => [
-        // ✅ 数据库类型明确设为 mysql
-        'type'            => 'mysql',
-
-        // 服务器地址(你写的没问题)
-        'hostname'        => Env::get('database.hostname', '20.0.16.87'),
-
-        // 数据库名、用户名、密码也 OK
-        'database'        => Env::get('database.database', 'mesdb'),
-        'username'        => Env::get('database.username', 'mesdb'),
-        'password'        => Env::get('database.password', 'NL484DiLH5EBxaAd'),
-
-        // ✅ 注意:MySQL 默认端口是 3306,不是 SQL Server 的
-        'hostport'        => Env::get('database.hostport', '3306'),
-
-        // 其他配置项可以保留不变
-        'dsn'             => '',
-        'params'          => [],
-        'charset'         => Env::get('database3.charset', 'utf8mb4'),
-        'prefix'          => Env::get('database3.prefix', ''),
-        'debug'           => Env::get('database3.debug', false),
-        'deploy'          => 0,
-        'rw_separate'     => false,
-        'master_num'      => 1,
-        'slave_no'        => '',
-        'fields_strict'   => true,
-        'resultset_type'  => 'array',
-        'auto_timestamp'  => false,
-        'datetime_format' => false,
-        'sql_explain'     => false,
-    ],
 ];

+ 1 - 1
application/extra/queue.php

@@ -5,7 +5,7 @@ return [
     'default'    => 'default',    // 默认的队列名称
     'host'       => '127.0.0.1',       // redis 主机ip
     'port'       => 6379,        // redis 端口
-    'password'   => '',             // redis 密码
+    'password'   => '123456',             // redis 密码
     'select'     => 0,          // 使用哪一个 db,默认为 db0
     'timeout'    => 0,          // redis连接的超时时间
     'persistent' => false,

+ 17 - 9
application/job/TextToImageJob.php

@@ -42,7 +42,7 @@ class TextToImageJob
             // NX: 只在键不存在时设置
             // EX: 设置过期时间
             $lockAcquired = $redis->set($lockKey, time(), ['NX', 'EX' => $lockExpire]);
-            
+
             if (!$lockAcquired) {
                 // 无法获取锁,任务正在执行
                 echo "❌ 检测到相同ID({$taskId})的任务正在执行,当前任务跳过\n";
@@ -63,7 +63,7 @@ class TextToImageJob
             echo "✅ 处理结果:{$resultText}\n";
             echo "完成时间:" . date('Y-m-d H:i:s') . "\n";
             echo "文生图已处理完成\n";
-    
+
             // 释放锁 - 使用del()替代被弃用的delete()方法
             $redis->del($lockKey);
             echo "🔓 释放任务锁,ID: {$taskId}\n";
@@ -229,10 +229,18 @@ class TextToImageJob
         $res = $aiGateway->callDalleApi($prompt, $model, $size);
 
         // 提取base64图片数据
-        if (isset($res['candidates'][0]['content']['parts'][0]['text'])) {
-            $text_content = $res['candidates'][0]['content']['parts'][0]['text'];
-            // 匹配base64图片数据
-            preg_match('/data:image\/(png|jpg|jpeg);base64,([^"]+)/', $text_content, $matches);
+//        if (isset($res['candidates'][0]['content']['parts'][0]['text'])) {
+//            $text_content = $res['candidates'][0]['content']['parts'][0]['text'];
+//            $text_content = $res['candidates'][0]['content']['parts'][0]['inlineData']['data'];
+//            // 匹配base64图片数据
+//            preg_match('/data:image\/(png|jpg|jpeg);base64,([^"]+)/', $text_content, $matches);
+
+        // 提取base64图片数据
+        $text_content = $res['candidates'][0]['content']['parts'][0]['inlineData']['data'];
+        $str = 'data:image/jpeg;base64,';
+        $text_content = $str. $text_content;
+        // 匹配base64图片数据
+        preg_match('/data:image\/(png|jpg|jpeg);base64,([^"]+)/', $text_content, $matches);
             if (empty($matches)) {
                 return '未找到图片数据';
             }
@@ -260,9 +268,9 @@ class TextToImageJob
             Db::name('product')->where('id',  $data['id'])->update(['product_new_img' => $db_img_path]);
 
             return  '成功';
-        } else {
-            return 'AI返回格式错误';
-        }
+//        } else {
+//            return 'AI返回格式错误';
+//        }
     }
 
     /**

+ 54 - 40
application/service/AIGatewayService.php

@@ -5,64 +5,78 @@ use think\Queue;
 class AIGatewayService{
     /**
      * 接口访问配置
-     *
-     * 每个模块包含:
      * - api_key:API 调用密钥(Token)
      * - api_url:对应功能的服务端地址
      */
-    // protected $config = [
-    //    //图生文 gemini-3-pro-preview
-    //    'gemini_imgtotxt' => [
-    //        'api_key' => 'sk-R4O93k4FrJTXMLYZ2eB32WDPHWiDNbeUdlUcsLjgjeDKuzFI',
-    //        'api_url' => 'https://chatapi.onechats.ai/v1beta/models/gemini-3-pro-preview:generateContent'
-    //    ],
-    //     //文生文 gpt-4
-    //     'txttotxtgtp' => [
-    //         'api_key' => 'sk-fxlawqVtbbQbNW0wInR3E4wsLo5JHozDC2XOHzMa711su6ss',
-    //         'api_url' => 'https://chatapi.onechats.top/v1/chat/completions'
-    //     ],
-    //     //文生文 gemini-2.0-flash
-    //     'txttotxtgemini' => [
-    //         'api_key' => 'sk-cqfCZFiiSIdpDjIHLMBbH6uWfeg7iVsASvlubjrNEmfUXbpX',
-    //         'api_url' => 'https://chatapi.onechats.ai/v1beta/models/gemini-2.0-flash:generateContent'
-    //     ],
-    //     //文生图 black-forest-labs/FLUX.1-kontext-pro、dall-e-3、gpt-image-1
-    //     'txttoimg' => [
-    //         'api_key' => 'sk-MB6SR8qNaTjO80U7HJl4ztivX3zQKPgKVka9oyfVSXIkHSYZ',
-    //         'api_url' => 'https://chatapi.onechats.ai/v1/images/generations'
-    //     ],
-    //     //文生图 gemini-3-pro-image-preview
-    //     'gemini_txttoimg' => [
-    //         'api_key' => 'sk-8nTt32NDI6q7klryBehwjEfnGaGrX8m1zI0C4ddfudLtanqP',
-    //         'api_url' => 'https://chatapi.onechats.ai/v1beta/models/gemini-3-pro-image-preview:streamGenerateContent'
-    //     ],
-    //     //文生图 MID_JOURNEY
-    //     'submitimage' => [
-    //         'api_key' => 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK',
-    //         'api_url' => 'https://chatapi.onechats.ai/mj/submit/imagine'
-    //     ]
-    // ];
-    //自用
-    protected $config = [
-       //图生文 gemini-3-pro-preview
+//     protected $config = [
+//        //图生文 gemini-3-pro-preview
+//        'gemini_imgtotxt' => [
+//            'api_key' => 'sk-R4O93k4FrJTXMLYZ2eB32WDPHWiDNbeUdlUcsLjgjeDKuzFI',
+//            'api_url' => 'https://chatapi.onechats.ai/v1beta/models/gemini-3-pro-preview:generateContent'
+//        ],
+//         //文生文 gpt-4
+//         'txttotxtgtp' => [
+//             'api_key' => 'sk-fxlawqVtbbQbNW0wInR3E4wsLo5JHozDC2XOHzMa711su6ss',
+//             'api_url' => 'https://chatapi.onechats.top/v1/chat/completions'
+//         ],
+//         //文生文 gemini-2.0-flash
+//         'txttotxtgemini' => [
+//             'api_key' => 'sk-cqfCZFiiSIdpDjIHLMBbH6uWfeg7iVsASvlubjrNEmfUXbpX',
+//             'api_url' => 'https://chatapi.onechats.ai/v1beta/models/gemini-2.0-flash:generateContent'
+//         ],
+//         //文生图 black-forest-labs/FLUX.1-kontext-pro、dall-e-3、gpt-image-1
+//         'txttoimg' => [
+//             'api_key' => 'sk-MB6SR8qNaTjO80U7HJl4ztivX3zQKPgKVka9oyfVSXIkHSYZ',
+//             'api_url' => 'https://chatapi.onechats.ai/v1/images/generations'
+//         ],
+//         //文生图 gemini-3-pro-image-preview
+//         'gemini_txttoimg' => [
+//             'api_key' => 'sk-8nTt32NDI6q7klryBehwjEfnGaGrX8m1zI0C4ddfudLtanqP',
+//             'api_url' => 'https://chatapi.onechats.ai/v1beta/models/gemini-3-pro-image-preview:streamGenerateContent'
+//         ],
+//         //文生图 MID_JOURNEY
+//         'submitimage' => [
+//             'api_key' => 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK',
+//             'api_url' => 'https://chatapi.onechats.ai/mj/submit/imagine'
+//         ],
+//         //文生视频【sora-2】
+//         'videos' => [
+//             'api_key' => 'sk-sWW1GFlnjbrDRb1DkMEzePIxgdvLK6cZt0Qg93yDMVP2z1yN',
+//             'api_url' => 'https://chatapi.onechats.ai/v1/videos'
+//         ]
+//     ];
+
+    //刘海瑞API接口文档秘钥
+    public $config = [
+       //图生文【gemini-3-pro-preview】
        'gemini_imgtotxt' => [
            'api_key' => 'sk-QiakVPhSisJiOh90LQFpjx9MX27mqGGOpOQ8XjKRhekoNCyr',
            'api_url' => 'https://chatapi.onechats.ai/v1beta/models/gemini-3-pro-preview:generateContent'
        ],
-        //文生文 gpt-4 (OpenAI格式)
+        //文生文【gpt-4 (OpenAI格式)】
         'txttotxtgtp' => [
             'api_key' => 'sk-pAlJU9xScpzDGvj1rhYKpokYcECETaceCSqDMUtq5N7FnbnA',
             'api_url' => 'https://chatapi.onechats.top/v1/chat/completions'
         ],
-        //文生文 gemini-2.0-flash (Gemini格式)
+        //文生文【gemini-2.0-flash (Gemini格式)】
         'txttotxtgemini' => [
             'api_key' => 'sk-pAlJU9xScpzDGvj1rhYKpokYcECETaceCSqDMUtq5N7FnbnA',
             'api_url' => 'https://chatapi.onechats.ai/v1beta/models/gemini-2.0-flash:generateContent'
         ],
-        //文生图 gemini-3-pro-image-preview
+        //文生图【gemini-3-pro-image-preview】
         'gemini_txttoimg' => [
             'api_key' => 'sk-pAlJU9xScpzDGvj1rhYKpokYcECETaceCSqDMUtq5N7FnbnA',
             'api_url' => 'https://chatapi.onechats.ai/v1beta/models/gemini-3-pro-image-preview:streamGenerateContent'
+        ],
+        //文生视频【sora-2】
+        'videos' => [
+            'api_key' => 'sk-ABO93U8p7u6Sin4yxnAHI8Z8K9hX8YjRO9rfTC0y3Ftv4mNm',
+            'api_url' => 'https://chatapi.onechats.ai/v1/videos'
+        ],
+        //即梦AI 创建视频任务接口【首帧图 + 尾帧图 = 新效果视频】
+        'Create_ImgToVideo' => [
+            'api_key' => '3da64aa0-afe2-4e3b-be4e-3eea5169aa6a',
+            'api_url' => 'https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks'
         ]
     ];