浏览代码

first commit

liuhairui 3 月之前
父节点
当前提交
00431bdb0f

+ 292 - 38
application/api/controller/Facility.php

@@ -14,6 +14,7 @@ class Facility extends Api
     public function getPreviewSubDirs()
     {
         $baseDir = rtrim(str_replace('\\', '/', ROOT_PATH), '/') . '/public/uploads/operate/ai/Preview';
+
         $baseRelativePath = 'uploads/operate/ai/Preview';
 
         if (!is_dir($baseDir)) {
@@ -27,7 +28,7 @@ class Facility extends Api
         $dirList = cache($cacheKey);
         if (!$dirList) {
             $dirList = $this->scanFlexibleDirectories($baseDir, $baseRelativePath);
-            cache($cacheKey, $dirList, 300); // 缓存 5 分钟(可调)
+            cache($cacheKey, $dirList, 3600); // 默认300 缓存 5 分钟(可调)
         } else {
             // 实时刷新 new_image_count(避免缓存值过期)
             foreach ($dirList as &$dir) {
@@ -38,6 +39,7 @@ class Facility extends Api
                     ->whereLike('old_image_url', $dir['old_image_url'] . '/%')
                     ->count();
             }
+
         }
 
         return json([
@@ -75,6 +77,7 @@ class Facility extends Api
 
     private function processDir($fullPath, $baseDir, $baseRelativePath, &$index)
     {
+
         $result = [];
 
         $relativeDir = ltrim(str_replace($baseDir, '', $fullPath), '/');
@@ -178,6 +181,7 @@ class Facility extends Api
         $status = $this->request->param('status', '');
         $status_name = $this->request->param('status_name', '');
         $relativePath = $this->request->param('path', '');
+        $sys_id = $this->request->param('sys_id', '');
 
         $basePath = ROOT_PATH . 'public/';
         $fullPath = $basePath . $relativePath;
@@ -190,7 +194,8 @@ class Facility extends Api
         $hash = md5($relativePath);
         $cacheKey = "previewimg_fileinfo_{$hash}";
         $lockKey = "previewimg_building_{$hash}";
-        $cacheExpire = 600; // 10分钟
+        // $cacheExpire = 600; // 10分钟
+        $cacheExpire = 3600; // 60分钟
 
         $cachedFileInfo = cache($cacheKey);
 
@@ -245,9 +250,11 @@ class Facility extends Api
         // 实时查询数据库状态信息(单次批量查询)
         $dbRecords = Db::name('text_to_image')
             ->whereIn('old_image_url', $paths)
-            ->field('id as img_id, old_image_url, new_image_url, custom_image_url,imgtoimg_url,taskId,chinese_description, english_description, img_name, status, status_name')
+            ->field('id as img_id, old_image_url, new_image_url, custom_image_url,imgtoimg_url,taskId,chinese_description, english_description, img_name, status, status_name,sys_id')
+            ->where('sys_id',$sys_id)
             ->select();
 
+
         // 实时查询队列状态(单次批量查询)
         $queueRecords = Db::name('image_task_log')
             ->where('mod_rq', null)
@@ -352,6 +359,7 @@ class Facility extends Api
                 'is_processed' => $data['isProcessed'] ? 1 : 0,
                 'queue_status' => $data['queueStatus'],
                 'taskId' => $item['taskId'] ?? '',
+                'sys_id' => $item['sys_id'] ?? '',
                 'new_image_url' => $item['new_image_url'] ?? '',
                 'custom_image_url' => $item['custom_image_url'] ?? '',
                 'imgtoimg_url' => $item['imgtoimg_url'] ?? '',
@@ -382,14 +390,21 @@ class Facility extends Api
     {
         // 获取前端传入的图片路径参数
         $params = $this->request->param('path', '');
+        $sys_id = $this->request->param('sys_id', '');
         // 查询数据库
         $res = Db::name('text_to_image')
             ->field('id,chinese_description,english_description,new_image_url,custom_image_url,size,old_image_url,img_name,model,imgtoimg_url')
             ->where('old_image_url', $params)
             ->where('img_name', '<>', '')
+            ->where('sys_id',$sys_id)
             ->order('id desc')
             ->select();
-        return json(['code' => 0, 'msg' => '查询成功', 'data' => $res,'count'=>count($res)]);
+        if($res){
+            return json(['code' => 0, 'msg' => '查询成功', 'data' => $res,'count'=>count($res)]);
+        }else{
+            return json(['code' => 0, 'msg' => '查询成功', 'data' => [],'count'=>0]);
+        }
+
     }
 
     /**
@@ -413,23 +428,31 @@ class Facility extends Api
         $file = request()->file('image');
 
         if ($file) {
-            // 指定目标目录(你想上传到的目录)
-            $targetPath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'operate' . DS . 'ai' . DS . 'Preview';
+            // 生成日期格式的文件夹名 image_YYYYMMDD
+            $dateFolder = 'image_' . date('Ymd');
+
+            // 指定目标目录(包含日期文件夹)
+            $targetPath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'operate' . DS . 'ai' . DS . 'Preview' . DS . $dateFolder;
 
             // 若目录不存在则创建
             if (!is_dir($targetPath)) {
                 mkdir($targetPath, 0755, true);
             }
 
-            // 移动文件到指定目录,并验证大小/格式
+            // 获取原始文件名(或自定义新文件名)
+            $originalName = $file->getInfo('name'); // 原始文件名
+            $extension = pathinfo($originalName, PATHINFO_EXTENSION); // 文件扩展名
+            $newFileName = uniqid() . '.' . $extension; // 生成唯一文件名(避免冲突)
+
+            // 移动文件到指定目录,并验证大小/格式,同时指定自定义文件名
             $info = $file->validate([
                 'size' => 10485760, // 最大10MB
                 'ext' => 'jpg,png'
-            ])->move($targetPath);
+            ])->move($targetPath, $newFileName); // 关键:手动指定文件名,避免自动生成日期目录
 
             if ($info) {
-                $fileName = $info->getSaveName();
-                $imageUrl = '/uploads/operate/ai/Preview/' . str_replace('\\', '/', $fileName);
+                // 直接拼接路径,不依赖 getSaveName() 的返回值
+                $imageUrl = '/uploads/operate/ai/Preview/' . $dateFolder . '/' . $newFileName;
                 return json(['code' => 0, 'msg' => '成功', 'data' => ['url' => $imageUrl]]);
             } else {
                 $res = $file->getError();
@@ -525,14 +548,69 @@ class Facility extends Api
      */
     public function TemplateList()
     {
-        $list = Db::name("template")->order('ids desc')->select();
+        $params = Request::instance()->param();
+        $path = $params['path'] ?? '';
+
+        if (empty($path)) {
+            return json([
+                'code' => 400,
+                'msg' => '缺少 path 参数',
+                'data' => []
+            ]);
+        }
+
+        // 先查询是否已有数据
+        $list = Db::name("template")
+            ->where('path', $path)
+            ->order('ids', 'desc')
+            ->select();
+
+        // 如果有记录,直接返回
+        if ($list) {
+            return json([
+                'code' => 0,
+                'msg' => '模版列表',
+                'data' => [
+                    'list' => $list,
+                    'usedId' => Db::name("template")->where('path', $path)->where('ids', 1)->value('id')
+                ]
+            ]);
+        }
+
+        $res_ids = Db::name("template")->where('ids', 99)->find();
+        // 否则插入默认模板
+        $default = [
+            'path' => $path,
+            'english_content' => '',
+            'content' => $res_ids['content'],
+            'width' => '1024',
+            'height' => '1303',
+            'ids' => 1
+        ];
+
+        $insertId = Db::name("template")->insertGetId($default);
+
+        if ($insertId) {
+            $list = Db::name("template")
+                ->where('path', $path)
+                ->order('ids', 'desc')
+                ->select();
+
+            return json([
+                'code' => 0,
+                'msg' => '模版列表(已创建默认)',
+                'data' => [
+                    'list' => $list,
+                    'usedId' => Db::name("template")->where('path', $path)->where('ids', 1)->value('id')
+                ]
+            ]);
+        }
+
+        // 插入失败
         return json([
-            'code' => 0,
-            'msg' => '模版列表',
-            'data' => [
-                'list' => $list,
-                'usedId' => Db::name("template")->where('ids', 1)->value('id')
-            ]
+            'code' => 500,
+            'msg' => '创建默认模版失败',
+            'data' => []
         ]);
     }
 
@@ -540,7 +618,9 @@ class Facility extends Api
      * 查询使用模版
      */
     public function Template_ids(){
-        $Template = Db::name("template")->where('ids',1)->find();
+        $params = Request::instance()->param();
+
+        $Template = Db::name("template")->where('path',$params['path'])->where('ids',1)->find();
         return json([
             'code' => 0,
             'msg' => '模版',
@@ -583,6 +663,7 @@ class Facility extends Api
         }
 
         $data = [
+            'path' => $params['path'],
             'english_content' => $params['english_content'],
             'content' => $params['textareaContent'],
             'width' => $params['width'],
@@ -607,43 +688,216 @@ class Facility extends Api
     public function setActiveTemplate()
     {
         $id = Request::instance()->param('id');
+        $params = Request::instance()->param();
+
         if (!$id) {
             return json(['code' => 1, 'msg' => '参数错误']);
         }
 
-        Db::name("template")->where('ids', 1)->update(['ids' => 0]); // 清除当前使用
-        Db::name("template")->where('id', $id)->update(['ids' => 1]); // 设置新的使用模版
+        Db::name("template")->where('path',$params['path'])->where('ids', 1)->update(['ids' => 0]); // 清除当前使用
+        Db::name("template")->where('path',$params['path'])->where('id', $id)->update(['ids' => 1]); // 设置新的使用模版
 
         return json(['code' => 0, 'msg' => '模版已设为当前使用']);
     }
 
-    /**
-     * 文生图查询模型列表
-     */
-    public function txttoimg_moxing(){
+    public function txttoimg_moxing()
+    {
+        // 获取所有模型数据
         $list = Db::name("moxing")->order('id asc')->select();
+
+        // 初始化分类数组
+        $classifiedData = [
+            'wenshengwen' => [],  // 文生文模型 (txttotxt)
+            'tushengwen' => [],   // 图生文模型 (imgtotxt)
+            'wenshengtu' => []    // 文生图模型 (txttoimg)
+        ];
+
+        // 当前使用的模型ID
+        $usedIds = [
+            'wenshengwen' => null,
+            'tushengwen' => null,
+            'wenshengtu' => null
+        ];
+
+        // 分类处理数据
+        foreach ($list as $model) {
+            // 文生文模型 (txttotxt)
+            if (!empty($model['txttotxt'])) {
+                $classifiedData['wenshengwen'][] = [
+                    'id' => $model['id'],
+                    'txttotxt' => $model['txttotxt'],
+                    'txttotxt_val' => $model['txttotxt_val']
+                ];
+                if ($model['txttotxt_val'] == 1) {
+                    $usedIds['wenshengwen'] = $model['id'];
+                }
+            }
+
+            // 图生文模型 (imgtotxt)
+            if (!empty($model['imgtotxt'])) {
+                $classifiedData['tushengwen'][] = [
+                    'id' => $model['id'],
+                    'imgtotxt' => $model['imgtotxt'],
+                    'imgtotxt_val' => $model['imgtotxt_val']
+                ];
+                if ($model['imgtotxt_val'] == 1) {
+                    $usedIds['tushengwen'] = $model['id'];
+                }
+            }
+
+            // 文生图模型 (txttoimg)
+            if (!empty($model['txttoimg'])) {
+                $classifiedData['wenshengtu'][] = [
+                    'id' => $model['id'],
+                    'txttoimg' => $model['txttoimg'],
+                    'txttoimg_val' => $model['txttoimg_val']
+                ];
+                if ($model['txttoimg_val'] == 1) {
+                    $usedIds['wenshengtu'] = $model['id'];
+                }
+            }
+        }
+
         return json([
             'code' => 0,
-            'msg' => '模版列表',
+            'msg' => '模型分类列表',
             'data' => [
-                'list' => $list,
-                'usedId' => Db::name("moxing")->where('txttoimg_val', 1)->value('id')
+                'models' => $classifiedData,
+                'used_ids' => $usedIds
             ]
         ]);
     }
 
-    /**
-     * 文生图设置默认使用模型
-     * txttoimg_val = 1 默认使用
-     */
-    public function txttoimg_update(){
-        $id = Request::instance()->param('id');
-        if (!$id) {
-            return json(['code' => 1, 'msg' => '参数错误']);
+    public function txttoimg_update()
+    {
+        // 获取并验证参数
+        $id = input('id/d', 0); // 强制转换为整数
+        $type = input('type/s', ''); // 强制转换为字符串
+
+        if ($id <= 0) {
+            return json(['code' => 1, 'msg' => '无效的模型ID']);
+        }
+
+        if (!in_array($type, ['tushengwen', 'wenshengwen', 'wenshengtu'])) {
+            return json(['code' => 1, 'msg' => '无效的模型类型']);
+        }
+
+        // 定义模型类型与字段的映射关系
+        $fieldMap = [
+            'tushengwen' => 'imgtotxt_val',
+            'wenshengwen' => 'txttotxt_val',
+            'wenshengtu' => 'txttoimg_val'
+        ];
+
+        $field = $fieldMap[$type];
+
+        try {
+            // 开启事务确保数据一致性
+            Db::startTrans();
+
+            // 1. 重置该类型下所有模型的激活状态
+            Db::name("moxing")
+                ->where($field, 1)
+                ->update([$field => 0]);
+
+            // 2. 设置指定模型为激活状态
+            $result = Db::name("moxing")
+                ->where('id', $id)
+                ->update([$field => 1]);
+
+            Db::commit();
+
+            if ($result) {
+                return json([
+                    'code' => 0,
+                    'msg' => '设置成功',
+                    'data' => [
+                        'id' => $id,
+                        'type' => $type
+                    ]
+                ]);
+            }
+
+            return json(['code' => 1, 'msg' => '设置失败,模型不存在或未变更']);
+
+        } catch (\Exception $e) {
+            Db::rollback();
+            return json([
+                'code' => 2,
+                'msg' => '设置失败: ' . $e->getMessage()
+            ]);
+        }
+    }
+
+
+    //获取原文件夹数据
+    public function getPreviewFolders()
+    {
+        $rootPath = app()->getRootPath(); // 更标准
+        $baseDir = rtrim(str_replace('\\', '/', $rootPath), '/') . '/public/uploads/operate/ai/Preview';
+        $cacheDir = $rootPath . 'runtime/cache/';
+        $cacheFile = $cacheDir . 'folder_list.json';
+        $cacheTTL = 86400; // 缓存 1 天
+        $forceRefresh = input('refresh/d', 0); // 更安全,强制转 int
+
+        try {
+            if (!is_dir($baseDir)) {
+                return json([
+                    'code' => 404,
+                    'msg'  => '预览目录不存在',
+                    'data' => []
+                ]);
+            }
+
+            $useCache = file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTTL;
+            $folders = [];
+
+            if ($useCache && !$forceRefresh) {
+                $folders = json_decode(file_get_contents($cacheFile), true) ?: [];
+            } else {
+                // 重新扫描目录
+                $directory = new \RecursiveDirectoryIterator($baseDir, \RecursiveDirectoryIterator::SKIP_DOTS);
+                $iterator = new \RecursiveIteratorIterator($directory, \RecursiveIteratorIterator::SELF_FIRST);
+
+                foreach ($iterator as $file) {
+                    if ($file->isDir()) {
+                        $fullPath = str_replace('\\', '/', $file->getPathname());
+
+                        // 去掉 public/ 之前的路径(使其相对路径用于前端)
+                        $relativePath = ltrim(str_replace(str_replace('\\', '/', $rootPath . 'public/'), '', $fullPath), '/');
+
+                        $folders[] = [
+                            'name'      => basename($fullPath),
+                            'path'      => $relativePath,
+                            'full_path' => $fullPath
+                        ];
+                    }
+                }
+
+                // 写入缓存(带锁)
+                if (!is_dir($cacheDir)) {
+                    mkdir($cacheDir, 0777, true);
+                }
+                file_put_contents($cacheFile, json_encode($folders, JSON_UNESCAPED_UNICODE), LOCK_EX);
+            }
+
+            return json([
+                'code' => 0,
+                'msg'  => '获取预览文件夹成功',
+                'data' => [
+                    'folders'     => $folders,
+                    'total'       => count($folders),
+                    'from_cache'  => $useCache && !$forceRefresh
+                ]
+            ]);
+        } catch (\Exception $e) {
+            return json([
+                'code' => 500,
+                'msg'  => '服务器错误: ' . $e->getMessage(),
+                'data' => []
+            ]);
         }
-        Db::name("moxing")->where('txttoimg_val', 1)->update(['txttoimg_val' => 0]); // 清除当前使用
-        Db::name("moxing")->where('id', $id)->update(['txttoimg_val' => 1]); // 设置新的使用模型
-        return json(['code' => 0, 'msg' => '模版已设为当前使用']);
     }
 
+
 }

+ 0 - 430
application/api/controller/WorkOrder.php

@@ -28,10 +28,8 @@ class WorkOrder extends Api
     }
 
 
-
     public function textToImage()
     {
-
         $outputDirRaw = 'uploads/operate/ai/Preview/undefined_BRdP4/3';
         $img_name = '42131321';
         $rootPath = str_replace('\\', '/', ROOT_PATH);
@@ -125,18 +123,14 @@ class WorkOrder extends Api
     }
 
 
-
-
     public function getImageSeed($taskId)
     {
         // 配置参数
         $apiUrl = 'https://chatapi.onechats.ai/mj/task/' . $taskId . '/fetch';
         $apiKey = 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK';
-
         try {
             // 初始化cURL
             $ch = curl_init();
-
             // 设置cURL选项
             curl_setopt_array($ch, [
                 CURLOPT_URL => $apiUrl,
@@ -156,15 +150,12 @@ class WorkOrder extends Api
             // 执行请求
             $response = curl_exec($ch);
             $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
-
             // 错误处理
             if (curl_errno($ch)) {
                 throw new Exception('cURL请求失败: ' . curl_error($ch));
             }
-
             // 关闭连接
             curl_close($ch);
-
             // 验证HTTP状态码
             if ($httpCode < 200 || $httpCode >= 300) {
                 throw new Exception('API返回错误状态码: ' . $httpCode);
@@ -175,20 +166,17 @@ class WorkOrder extends Api
             if (json_last_error() !== JSON_ERROR_NONE) {
                 throw new Exception('JSON解析失败: ' . json_last_error_msg());
             }
-
             // 返回结构化数据
             return [
                 'success' => true,
                 'http_code' => $httpCode,
                 'data' => $responseData
             ];
-
         } catch (Exception $e) {
             // 确保关闭cURL连接
             if (isset($ch) && is_resource($ch)) {
                 curl_close($ch);
             }
-
             return [
                 'success' => false,
                 'error' => $e->getMessage(),
@@ -197,120 +185,6 @@ class WorkOrder extends Api
         }
     }
 
-//    public function textToImage()
-//    {
-//        $outputDirRaw = 'uploads/operate/ai/Preview/undefined_BRdP4/3';
-//        $img_name = '16';
-//        $rootPath = str_replace('\\', '/', ROOT_PATH);
-//        $outputDir = rtrim($rootPath . 'public/' . $outputDirRaw, '/') . '/';
-//        $dateDir = date('Y-m-d') . '/';
-//        $fullBaseDir = $outputDir . $dateDir;
-//
-//        // 确保目录存在
-//        if (!is_dir($fullBaseDir . '2048x2048/')) {
-//            mkdir($fullBaseDir . '2048x2048/', 0755, true);
-//        }
-//
-//        $taskId = '1755154312186851';
-//        //API配置
-//        $config = [
-//            'fetch_url' => 'https://chatapi.onechats.ai/mj/task/',
-//            'api_key' => 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK'
-//        ];
-//
-//        // 1. 获取主任务信息
-//        $fetchUrl = $config['fetch_url'].$taskId.'/fetch';
-//        $fetchResponse = $this->sendApiRequest($fetchUrl, [], $config['api_key'], 'GET');
-//        echo "<pre>";
-//        print_r($fetchResponse);
-//        echo "<pre>";
-//        $fetchData = json_decode($fetchResponse, true);
-//        echo "<pre>";
-//        print_r($fetchData);
-//        echo "<pre>";
-//        if (empty($fetchData['buttons'])) {
-//            throw new Exception('无法获取变体按钮信息');
-//        }
-//
-//        echo "<pre>";
-//        print_r(777777777);
-//        echo "<pre>";
-//
-//        //选择要获取的变体(这里选择第一个变体U1)
-//        //customId MJ::JOB::upsample::1::47df46a8-b0bb-4b31-a578-09f69c73a2ed
-//        $customId = $fetchData['buttons'][0]['customId'];
-//
-//        $upscaleUrl = "https://chatapi.onechats.ai/mj/submit/action";
-//        $postData = [
-//            'customId' => $customId,
-//            // 可能需要额外参数,如 taskId
-//            'taskId' => $taskId,
-//        ];
-//        $response = $this->sendApiRequest($upscaleUrl, $postData, $config['api_key'], 'POST');
-//        echo "<pre>";
-//        print_r($response);
-//        echo "<pre>";
-//        $responseData = json_decode($response, true);
-//        echo "<pre>";
-//        print_r($responseData);
-//        echo "<pre>";
-//
-//
-//        echo "<pre>";
-//        print_r(21312312321321321);
-//        echo "<pre>";
-//        // 3. 调用API获取单个变体图片
-//        $upscaleUrl = $config['fetch_url'].$customId.'/image-seed';
-//        $upscaleResponse = $this->sendApiRequest($upscaleUrl, [], $config['api_key'], 'GET');
-//        echo "<pre>";
-//        print_r($upscaleResponse);
-//        echo "<pre>";
-//        $upscaleData = json_decode($upscaleResponse, true);
-//        echo "<pre>";
-//        print_r($upscaleData);
-//        echo "<pre>";
-//        die;
-//        if (empty($upscaleData['imageUrl'])) {
-//            throw new Exception('获取变体图片失败: '.($upscaleData['message'] ?? '未知错误'));
-//        }
-//
-//        // 4. 处理返回的图片URL
-//        $imageUrl = is_array($upscaleData['imageUrl']) ? $upscaleData['imageUrl'][0] : $upscaleData['imageUrl'];
-//        echo "<pre>";
-//        print_r($imageUrl.'3333');
-//        echo "<pre>";
-//        // 保存文件路径定义
-//        $img_name = mb_substr(preg_replace('/[^\x{4e00}-\x{9fa5}A-Za-z0-9_\- ]/u', '', $img_name), 0, 30);
-//        $filename = $img_name . '.png';
-//        $path512 = $fullBaseDir . '2048x2048/' . $filename;
-//
-//        // 下载并保存图片
-//        $imageContent = file_get_contents($imageUrl);
-//        if ($imageContent === false) {
-//            throw new Exception('下载图片失败');
-//        }
-//
-//        $saveResult = file_put_contents($path512, $imageContent);
-//        if ($saveResult === false) {
-//            throw new Exception('保存图片失败');
-//        }
-//
-//        // 数据库更新
-//        Db::name('text_to_image')->where('id', '552')->update([
-//            'new_image_url' => str_replace($rootPath . 'public/', '', $path512),
-//            'img_name' => $img_name,
-//            'model' => 'MID_JOURNEY',
-//            'status' => trim($img_name) === '' ? 0 : 1,
-//            'status_name' => "文生图",
-//            'size' => "2048",
-//            'quality' => 'standard',
-//            'style' => 'vivid',
-//            'error_msg' => '',
-//            'update_time' => date('Y-m-d H:i:s')
-//        ]);
-//
-//        return "成功";
-//    }
 
     private function sendPostRequest($url, $data, $apiKey)
     {
@@ -327,12 +201,10 @@ class WorkOrder extends Api
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
         curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 延长超时时间
-
         $response = curl_exec($ch);
         $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
         $error = curl_error($ch);
         curl_close($ch);
-
         return [
             'response' => $response,
             'http_code' => $httpCode,
@@ -355,7 +227,6 @@ class WorkOrder extends Api
             'default_prompt' => '一个猫',
             'wait_time' => 3 // 等待生成完成的秒数
         ];
-
         try {
             // 1. 准备请求数据
             $prompt =  $config['default_prompt'];
@@ -378,32 +249,24 @@ class WorkOrder extends Api
             // 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,
@@ -414,7 +277,6 @@ class WorkOrder extends Api
                     'task_id' => $taskId
                 ]
             ];
-
         } catch (Exception $e) {
             // 错误处理
             return [
@@ -520,298 +382,6 @@ class WorkOrder extends Api
         return $localPath;
     }
 
-//    public function txttowimg($params = [])
-//    {
-//        $config = [
-//            'api_url' => 'https://chatapi.onechats.ai/mj/submit/imagine',
-//            'api_key' => 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK',
-//            'default_prompt' => '一个猫',
-//        ];
-//
-//        // 使用传入的prompt或默认值
-//        $prompt = $params['prompt'] ?? $config['default_prompt'];
-//
-//        // 构建请求数据
-//        $postData = [
-//            'botType' => 'MID_JOURNEY',
-//            'prompt' => $prompt,
-//            'base64Array' => [],
-//            'accountFilter' => [
-//                'channelId' => $params['channelId'] ?? "",
-//                'instanceId' => $params['instanceId'] ?? "",
-//                'modes' => $params['modes'] ?? [],
-//                'remark' => $params['remark'] ?? "",
-//                'remix' => $params['remix'] ?? true,
-//                'remixAutoConsidered' => $params['remixAutoConsidered'] ?? true
-//            ],
-//            'notifyHook' => $params['notifyHook'] ?? "",
-//            'state' => $params['state'] ?? ""
-//        ];
-//
-//        $arr =  $this->sendPostRequest($config['api_url'], $postData, $config['api_key']);
-//        $response = json_decode($arr['response'], true);
-//        $imageid = $response['result'];
-//        if (!$imageid) {
-//            throw new Exception('未找到图像id');
-//        }
-//        $imageUrl = $this->getImageSeed('1755151823075229');
-//        // 保存到本地
-//        $savePath = $this->saveImageToLocal($imageUrl['data']['imageUrl']);
-//
-//        return json([
-//            'code' => 200,
-//            'msg' => '图像生成并保存成功',
-//            'data' => [
-//                'local_path' => $savePath,
-//                'web_url' => request()->domain() . $savePath
-//            ]
-//        ]);
-//    }
-//
-//    private function sendPostRequest($url, $data, $apiKey)
-//    {
-//        $ch = curl_init();
-//        curl_setopt($ch, CURLOPT_URL, $url);
-//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
-//        curl_setopt($ch, CURLOPT_POST, true);
-//        curl_setopt($ch, CURLOPT_HTTPHEADER, [
-//            'Authorization: Bearer ' . $apiKey,
-//            'Accept: application/json',
-//            'Content-Type: application/json'
-//        ]);
-//        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
-//        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
-//        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
-//        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
-//
-//        $response = curl_exec($ch);
-//        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
-//        $error = curl_error($ch);
-//        curl_close($ch);
-//
-//        return [
-//            'response' => $response,
-//            'http_code' => $httpCode,
-//            'error' => $error
-//        ];
-//    }
-//
-//    /**
-//     * 获取任务图片地址
-//     * @param $taskId
-//     * @return array
-//     */
-//    public function getImageSeed($taskId)
-//    {
-//        // 配置参数
-//        $apiUrl = 'https://chatapi.onechats.ai/mj/task/' . $taskId . '/fetch';
-//        $apiKey = 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK';
-//
-//        try {
-//            // 初始化cURL
-//            $ch = curl_init();
-//
-//            // 设置cURL选项
-//            curl_setopt_array($ch, [
-//                CURLOPT_URL => $apiUrl,
-//                CURLOPT_RETURNTRANSFER => true,
-//                CURLOPT_CUSTOMREQUEST => 'GET',  // 明确指定GET方法
-//                CURLOPT_HTTPHEADER => [
-//                    'Authorization: Bearer ' . $apiKey,
-//                    'Accept: application/json',
-//                    'Content-Type: application/json'
-//                ],
-//                CURLOPT_SSL_VERIFYPEER => false,
-//                CURLOPT_SSL_VERIFYHOST => false,
-//                CURLOPT_TIMEOUT => 60,
-//                CURLOPT_FAILONERROR => true     // 添加失败时返回错误
-//            ]);
-//
-//            // 执行请求
-//            $response = curl_exec($ch);
-//            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
-//
-//            // 错误处理
-//            if (curl_errno($ch)) {
-//                throw new Exception('cURL请求失败: ' . curl_error($ch));
-//            }
-//
-//            // 关闭连接
-//            curl_close($ch);
-//
-//            // 验证HTTP状态码
-//            if ($httpCode < 200 || $httpCode >= 300) {
-//                throw new Exception('API返回错误状态码: ' . $httpCode);
-//            }
-//
-//            // 解析JSON响应
-//            $responseData = json_decode($response, true);
-//            if (json_last_error() !== JSON_ERROR_NONE) {
-//                throw new Exception('JSON解析失败: ' . json_last_error_msg());
-//            }
-//
-//            // 返回结构化数据
-//            return [
-//                'success' => true,
-//                'http_code' => $httpCode,
-//                'data' => $responseData
-//            ];
-//
-//        } catch (Exception $e) {
-//            // 确保关闭cURL连接
-//            if (isset($ch) && is_resource($ch)) {
-//                curl_close($ch);
-//            }
-//
-//            return [
-//                'success' => false,
-//                'error' => $e->getMessage(),
-//                'http_code' => $httpCode ?? 0
-//            ];
-//        }
-//    }
-//
-//    private function saveImageToLocal($imageUrl)
-//    {
-//        // 创建存储目录
-//        $saveDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'midjourney' . DS . date('Ymd');
-//        if (!is_dir($saveDir)) {
-//            mkdir($saveDir, 0755, true);
-//        }
-//
-//        // 生成唯一文件名
-//        $filename = uniqid() . '.png';
-//        $localPath = DS . 'uploads' . DS . 'midjourney' . DS . date('Ymd') . DS . $filename;
-//        $fullPath = $saveDir . DS . $filename;
-//
-//        // 下载图像
-//        $imageData = $this->downloadImage($imageUrl);
-//
-//        // 保存到文件
-//        if (!file_put_contents($fullPath, $imageData)) {
-//            throw new Exception('图像保存失败');
-//        }
-//
-//        return $localPath;
-//    }
-//
-//    private function downloadImage($url)
-//    {
-//        $ch = curl_init($url);
-//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
-//        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
-//        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
-//        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
-//
-//        $imageData = curl_exec($ch);
-//        $error = curl_error($ch);
-//        curl_close($ch);
-//
-//        if (!$imageData) {
-//            throw new Exception('图像下载失败: ' . $error);
-//        }
-//
-//        // 基本图像类型验证
-//        if (!in_array(getimagesizefromstring($imageData)['mime'] ?? '', ['image/png', 'image/jpeg'])) {
-//            throw new Exception('下载内容不是有效图像');
-//        }
-//
-//        return $imageData;
-//    }
-
-//    public function txttowimg()
-//    {
-//        $config = [
-//            'api_url' => 'https://chatapi.onechats.ai/mj/submit/imagine',
-//            'api_key' => 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK',
-//            'prompt' => '一个猫',
-//        ];
-//
-//        $postData = [
-//            'botType' => 'MID_JOURNEY',
-//            'prompt' => $config['prompt'],
-//            'base64Array' => [],
-//            'accountFilter' => [
-//                'channelId' => "",
-//                'instanceId' => "",
-//                'modes' => [],
-//                'remark' => "",
-//                'remix' => true,
-//                'remixAutoConsidered' => true
-//            ],
-//            'notifyHook' => "",
-//            'state' => ""
-//        ];
-//
-//        $headers = [
-//            'Authorization: Bearer ' . $config['api_key'],
-//            'Accept: application/json',
-//            'Content-Type: application/json'
-//        ];
-//
-//        $ch = curl_init();
-//        curl_setopt($ch, CURLOPT_URL, $config['api_url']);
-//        curl_setopt($ch, CURLOPT_POST, true);
-//        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
-//        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
-//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
-//
-//        $response = curl_exec($ch);
-//        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
-//
-//        if (curl_errno($ch)) {
-//            $error = curl_error($ch);
-//            curl_close($ch);
-//            throw new Exception("cURL Error: " . $error);
-//        }
-//
-//        curl_close($ch);
-//
-//        if ($httpCode >= 400) {
-//            throw new Exception("API Error: HTTP " . $httpCode . " - " . $response);
-//        }
-//
-//        return json_decode($response, true);
-//    }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-//    public function txttowimg()
-//    {
-//        $prompt = 'Cat'; // 或使用 '生成一个猫' 如果要中文
-//        $apiUrl = 'https://chatapi.onechats.ai/mj/submit/imagine';
-//        $apiKey = "sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK";
-//
-//    }
-
-
-
 
 
     /**

+ 4 - 20
application/job/ImageJob.php

@@ -88,14 +88,14 @@ class ImageJob{
     public function processImage($data)
     {
         // 根据传入的数据处理图片
-        $res = $this->imageToText($data["sourceDir"],$data["file_name"],$data["prompt"],$data);
+        $res = $this->imageToText($data["sourceDir"],$data["file_name"],$data["prompt"],$data["sys_id"],$data["imgtotxt_selectedOption"],$data);
         echo $res;
     }
 
     /**
      * 执行图生文逻辑(图像转文本)
      */
-    public function imageToText($sourceDirRaw, $fileName, $prompt, $call_data)
+    public function imageToText($sourceDirRaw, $fileName, $prompt,$sys_id,$imgtotxt_selectedOption,$call_data)
     {
         // 自动拆分文件名
         if (!$fileName && preg_match('/([^\/]+\.(jpg|jpeg|png))$/i', $sourceDirRaw, $matches)) {
@@ -140,7 +140,7 @@ class ImageJob{
 
         // 调用 图生文 接口
         $ai = new AIGatewayService();
-        $gptRes = $ai->callGptApi($imageUrl, $prompt);
+        $gptRes = $ai->callGptApi($imageUrl, $prompt,$imgtotxt_selectedOption);
 
         $gptText = trim($gptRes['choices'][0]['message']['content'] ?? '');
 
@@ -182,28 +182,12 @@ class ImageJob{
         //     FILE_APPEND
         // );
 
-        // // 成功写入数据库
-        // $record = [
-        //     'chinese_description' => $chineseDesc,
-        //     'english_description' => $englishDesc,
-        //     'old_image_url' => $relativePath,
-        //     'new_image_url' => '',
-        //     'custom_image_url' => '',
-        //     'img_name' => $img_name,
-        //     'status' => 0,
-        //     'status_name' => "图生文",
-        //     'model' => "",
-        //     'size' => "",
-        //     'error_msg' => '',
-        //     'created_time' => date('Y-m-d H:i:s'),
-        //     'update_time' => date('Y-m-d H:i:s')
-        // ];
-        // Db::name('text_to_image')->insert($record);
         $now = date('Y-m-d H:i:s');
         $record = [
             'chinese_description' => $chineseDesc,
             'english_description' => $englishDesc,
             'img_name' => $img_name,
+            'sys_id' => $sys_id,
             'status' => 0,
             'status_name' => "图生文",
             'model' => "",

+ 7 - 1
application/job/TextToImageJob.php

@@ -192,9 +192,15 @@ class TextToImageJob
             }
         }
 
+        $template = Db::name('template')
+            ->field('id,english_content,content')
+            ->where('path',$fileName)
+            ->where('ids',1)
+            ->find();
+
         // AI 图像生成调用
         $ai = new AIGatewayService();
-        $response = $ai->callDalleApi($prompt, $selectedOption);
+        $response = $ai->callDalleApi($template['content'].$prompt, $selectedOption);
 
         if($response['result']){
 // echo "<pre>";

+ 6 - 5
application/job/TextToTextJob.php

@@ -46,7 +46,7 @@ class TextToTextJob
                     echo "处理时间:{$currentTime}\n";
                     echo "👉 正在处理第 " . ($index + 1) . " 条,ID: {$row['id']}\n";
 
-                    $result = $this->textToTxt($row['id'],$data["txttotxt_selectedOption"]);
+                    $result = $this->textToTxt($row['id'],$data["txttotxt_selectedOption"],$fullPath);
                     echo $result;
                     echo "✅ 处理结果:完成\n";
                     echo "完成时间:" . date('Y-m-d H:i:s') . "\n";
@@ -108,15 +108,16 @@ class TextToTextJob
      * @param int $id text_to_image 表主键
      * @return string
      */
-    public function textToTxt($id,$txttotxt_selectedOption)
+    public function textToTxt($id,$txttotxt_selectedOption,$fullPath)
     {
         $template = Db::name('template')
-            ->field('id,english_content')
+            ->field('id,english_content,content')
+            ->where('path',$fullPath)
             ->where('ids',1)
             ->find();
 
         $record = Db::name('text_to_image')
-            ->field('id,english_description')
+            ->field('id,english_description,chinese_description')
             ->where('id',$id)
             ->order('id desc')
             ->find();
@@ -124,7 +125,7 @@ class TextToTextJob
 
         // 拼接提示词调用 文生文 接口
         $ai = new AIGatewayService();
-        $gptRes = $ai->txtGptApi($template['english_content'].$record['english_description'],$txttotxt_selectedOption);
+        $gptRes = $ai->txtGptApi($template['english_content'].$record['chinese_description'],$txttotxt_selectedOption);
         $gptText = trim($gptRes['choices'][0]['message']['content'] ?? '');
 
         // 更新数据库记录

+ 2 - 2
application/service/AIGatewayService.php

@@ -43,11 +43,11 @@ class AIGatewayService{
      * @param string $imageUrl 图像 URL,支持公网可访问地址
      * @param string $prompt   对图像的提问内容或提示文本
      */
-    public function callGptApi($imageUrl, $prompt)
+    public function callGptApi($imageUrl, $prompt,$imgtotxt_selectedOption)
     {
         //方式一
         $data = [
-            "model" => "gemini-2.5-flash-lite-preview-06-17",
+            "model" => $imgtotxt_selectedOption,
             "messages" => [[
                 "role" => "user",
                 "content" => [

+ 8 - 3
application/service/ImageService.php

@@ -12,6 +12,7 @@ class ImageService{
      * @param array $params 请求参数,包含图像批次、模型类型、尺寸等
      */
     public function handleImage($params) {
+
         if (!isset($params["batch"])) {return false;}
 
         $arr = [];
@@ -36,12 +37,14 @@ class ImageService{
                 "outputDir" => $this->sourceDir($v, 2),
                 "file_name" => $this->sourceDir($v, 3),
                 "type" => $params['type'] ?? '',
-                "selectedOption" => $params['selectedOption'],
-                "txttotxt_selectedOption" => $params['txttotxt_selectedOption'],
+                "selectedOption" => $params['selectedOption'],//文生图模型
+                "txttotxt_selectedOption" => $params['txttotxt_selectedOption'],//文生文模型
+                "imgtotxt_selectedOption" => $params['imgtotxt_selectedOption'],//图生文模型
                 "prompt" => $template['content'],
                 "width" => $params['width'],
                 "height" => $params['height'],
-                "executeKeywords" => $params['executeKeywords']
+                "executeKeywords" => $params['executeKeywords'],//是否执行几何图
+                "sys_id" => $params['sys_id']//用户
             ];
             // 创建$num个相同的项目并合并到$arr
             $arr = array_merge($arr, array_fill(0, $num, $baseItem));
@@ -114,6 +117,8 @@ class ImageService{
                 $item['task_id'] = $task_id;
                 return $item;
             }, $arr);
+
+
             // 投递任务到队列
             $payload = [
                 'task_id' => $task_id,