| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717 |
- <?php
- namespace app\api\controller;
- use app\common\controller\Api;
- use app\job\ImageJob;
- use app\service\AIGatewayService;
- use app\service\ImageService;
- use think\App;
- use think\Db;
- use think\Exception;
- use think\Log;
- use think\Queue;
- use think\queue\job\Redis;
- use think\Request;
- class WorkOrder extends Api{
- protected $noNeedLogin = ['*'];
- protected $noNeedRight = ['*'];
- public function index(){echo '访问成功';}
- /**
- * AI队列入口处理 出图接口
- * 此方法处理图像转换为文本的请求,将图像信息存入队列以供后续处理。
- */
- public function imageToText()
- {
- $params = $this->request->param();
- $service = new ImageService();
- $service->handleImage($params);
- $this->success('任务成功提交至队列');
- }
- /**
- * task_id:查询获取任务图片
- */
- public function GetImageStatus(){
- // $taskInfo = [
- // 'status' => 'completed',
- // 'image' => '/uploads/Product/img2img-20260317152818-69b902924548d.png',
- // 'image_url' => '/uploads/Product/img2img-20260317152818-69b902924548d.png',
- // 'completed_at' => date('Y-m-d H:i:s')
- // ];
- // $res = [
- // 'code' => 0,
- // 'msg' => '查询成功',
- // 'data' => $taskInfo
- // ];
- // return json($res);die;
- $params = $this->request->param();
- $taskId = $params['task_id'];
- if (empty($taskId)) {
- $res = [
- 'code' => 1,
- 'msg' => '任务ID不能为空'
- ];
- return json($res);
- }
- //从Redis中获取任务状态
- $redis = getTaskRedis();
- $taskData = $redis->get("img_to_img_task:{$taskId}");
- if (!$taskData) {
- $taskData = $redis->get("text_to_image_task:{$taskId}");
- }
- if (!$taskData) {
- $res = [
- 'code' => 1,
- 'msg' => '任务不存在或已过期',
- ];
- return json($res);
- }
- $taskInfo = json_decode($taskData, true);
- $res = [
- 'code' => 0,
- 'msg' => '查询成功',
- 'data' => $taskInfo
- ];
- return json($res);
- }
- /**
- * 支持的AI任务类型枚举(前端传入的status_val需在该列表内)
- * 键:前端传入值,值:方法后缀( '前端传入值' => '方法后缀')
- */
- private static $AI_TASK_TYPES = [
- '图生文' => 'ImgToText',
- '文生文' => 'TextToText',
- '文生图' => 'TextToImg',
- '图生图' => 'ImgToImg'
- ];
- /**
- * AI模型接口统一调用入口
- * @description 接收前端AI请求,校验任务类型合法性,分发至对应处理方法,统一异常捕获
- * @return \think\response\Json 标准化JSON响应
- */
- public function callAIModelApi()
- {
- try {
- // 1. 获取并校验入参
- $params = $this->request->param();
- // echo "<pre>";
- // print_r($params);
- // echo "<pre>";die;
- $statusVal = $this->validateAndGetStatusVal($params);
- // 2. 映射并校验处理方法
- $method = $this->getHandleMethod($statusVal);
- // 3. 执行对应处理逻辑并返回响应
- return $this->$method($params);
- } catch (\InvalidArgumentException $e) {
- // 参数/方法异常(用户侧错误)
- return $this->jsonResponse(1, $e->getMessage());
- } catch (\Throwable $e) {
- // 系统异常(服务侧错误)
- \think\Log::error('AI接口处理异常:' . $e->getMessage() . ' | 任务类型:' . ($params['status_val'] ?? '未知') . ' | 异常行:' . $e->getLine());
- return $this->jsonResponse(1, '服务异常,请稍后重试');
- }
- }
- // -------------------------- 私有核心方法(通用逻辑) --------------------------
- /**
- * 校验并获取合法的任务类型
- * @param array $params 前端入参
- * @return string 合法的status_val
- * @throws \InvalidArgumentException 任务类型不合法时抛出
- */
- private function validateAndGetStatusVal(array $params): string
- {
- $statusVal = trim($params['status_val'] ?? '');
- // 空值校验
- if (empty($statusVal)) {
- throw new \InvalidArgumentException('任务类型不能为空');
- }
- // 合法性校验
- if (!array_key_exists($statusVal, self::$AI_TASK_TYPES)) {
- throw new \InvalidArgumentException('不支持的任务类型:' . $statusVal);
- }
- return $statusVal;
- }
- /**
- * 获取任务对应的处理方法名
- * @param string $statusVal 合法的任务类型
- * @return string 处理方法名(如handleAiImgToText)
- * @throws \InvalidArgumentException 方法未实现时抛出
- */
- private function getHandleMethod(string $statusVal): string
- {
- $methodSuffix = self::$AI_TASK_TYPES[$statusVal];
- $method = 'handleAi' . $methodSuffix;
- if (!method_exists($this, $method)) {
- throw new \InvalidArgumentException('任务类型暂未实现:' . $statusVal);
- }
- return $method;
- }
- /**
- * 通用JSON响应封装
- * @param int $code 响应码(0=成功,1=失败)
- * @param string $msg 响应信息
- * @param array $data 响应数据(可选)
- * @return \think\response\Json
- */
- private function jsonResponse(int $code, string $msg, array $data = []): \think\response\Json
- {
- $response = [
- 'code' => $code,
- 'msg' => $msg,
- 'time' => date('Y-m-d H:i:s')
- ];
- if (!empty($data)) {
- $response['data'] = $data;
- }
- return json($response);
- }
- /**
- * 任务类接口统一响应(带task_id的场景)
- * @param array $result 业务处理结果(需包含success字段)
- * @param string $failMsg 失败提示语
- * @return \think\response\Json
- */
- private function jsonTaskResponse(array $result, string $failMsg = '任务提交失败'): \think\response\Json
- {
- $isSuccess = isset($result['success']) && $result['success'];
- $data = $isSuccess ? ['task_id' => $result['task_id'] ?? ''] : [];
- $msg = $isSuccess ? ($result['message'] ?? '提交成功') : ($result['message'] ?? $failMsg);
- return $this->jsonResponse($isSuccess ? 0 : 1, $msg, $data);
- }
- // -------------------------- 业务处理方法(按任务类型拆分) --------------------------
- /**
- * 图生文任务处理:提交队列并返回提示
- * @param array $params 前端入参
- * @return \think\response\Json
- */
- private function handleAiImgToText(array $params): \think\response\Json
- {
- (new ImageService())->handleImgToText($params);
- return $this->jsonResponse(0, '正在优化提示词,请稍等.....');
- }
- /**
- * 文生文任务处理:生成话术并返回内容(支持产品内容更新)
- * @param array $params 前端入参
- * @return \think\response\Json
- */
- private function handleAiTextToText(array $params): \think\response\Json
- {
- // echo "<pre>";
- // print_r($params);
- // echo "<pre>";die;
- //构造生成提示词
- $promptTemplate = "\n请根据上述内容生成一段完整的话术,要求:\n"
- . "1. 内容必须是连贯的一段话,不要使用列表、分隔线或其他结构化格式\n"
- . "2. 不要包含非文本元素的描述\n"
- . "3. 不要添加任何额外的引导语、解释或开场白\n"
- . "4. 禁忌:不添加无关形容词,不修改产品核心信息,语言流畅自然";
- $prompt = ($params['prompt'] ?? '') . $promptTemplate;
- // 调用服务层生成内容
- $result = (new ImageService())->handleTextToText(
- $params['status_val'],
- $prompt,
- $params['model']
- );
- if (empty($result['success'])) {
- return $this->jsonResponse(1, $result['message'] ?? '生成失败');
- }
- $content = $result['data'] ?? '';
- //区分业务场景处理
- $isProductImageGeneration = ($params['status_type'] ?? '') === 'ProductImageGeneration';
- $isProductTemplateReplace = ($params['status_type'] ?? '') === 'ProductTemplateReplace';
- if (!$isProductImageGeneration && !$isProductTemplateReplace) {
- Db::name('product')->where('id', $params['id'])->update(['content' => $content]);
- }
- return $this->jsonResponse(0, '优化成功', ['content' => $content]);
- }
- /**
- * 文生图任务处理:提交任务并返回task_id
- * @param array $params 前端入参
- * @return \think\response\Json
- */
- private function handleAiTextToImg(array $params): \think\response\Json
- {
- $serviceResult = (new ImageService())->handleTextToImg($params);
- return $this->jsonTaskResponse($serviceResult, '文生图任务提交失败');
- }
- /**
- * 图生图任务处理:提交任务并返回task_id
- * @param array $params 前端入参
- * @return \think\response\Json
- */
- private function handleAiImgToImg(array $params): \think\response\Json
- {
- $serviceResult = (new ImageService())->handleImgToImg($params);
- return $this->jsonTaskResponse($serviceResult, '图生图任务提交失败');
- }
- /**
- * 即梦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 = '';
- // $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();
- $prompt = $params['prompt'];//提示词
- $model = $params['model'];//模型
- $size = $params['size'];//尺寸
- // 调用AI生成图片
- $aiGateway = new AIGatewayService();
- $res = $aiGateway->callDalleApi($prompt, $model, $size);
- // 提取base64图片数据
- $imageData = '';
- $imageType = 'png'; // 默认图片类型
- if (isset($res['candidates'][0]['content']['parts'][0]['text'])) {
- $text_content = $res['candidates'][0]['content']['parts'][0]['text'];
- // 匹配base64图片数据和类型
- if (preg_match('/data:image\/([a-zA-Z0-9]+);base64,([^\s]+)/', $text_content, $matches)) {
- $imageType = strtolower($matches[1]);
- $base64Data = $matches[2];
- // 解码base64数据
- $imageData = base64_decode($base64Data);
- }
- }
- if (!$imageData) {
- return json(['code' => 1, 'msg' => '图片生成失败,未找到有效图片数据']);
- }
- // 创建保存目录(public/uploads/log/YYYY-MM/)
- $yearMonth = date('Ym');
- $saveDir = ROOT_PATH . 'public/uploads/ceshi/' . $yearMonth . '/';
- if (!is_dir($saveDir)) {
- mkdir($saveDir, 0755, true);
- }
- // 生成唯一文件名
- $fileName = uniqid() . '.' . $imageType;
- $filePath = $saveDir . $fileName;
- // 保存图片到本地文件
- if (file_put_contents($filePath, $imageData) === false) {
- return json(['code' => 1, 'msg' => '图片保存失败']);
- }
- // 生成前端可访问的URL
- $imageUrl = '/uploads/ceshi/' . $yearMonth . '/' . $fileName;
- // 返回标准JSON响应
- return json([
- 'code' => 0,
- 'msg' => '图片生成成功',
- 'data' => [
- 'url' => $imageUrl
- ]
- ]);
- }
- /**
- * 学生端文生视频接口 - 用于生成视频
- */
- 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;
- $postData = [
- 'prompt' => $params['prompt'],
- 'model' => $params['model'],
- 'seconds' => $params['duration'],
- 'size' => $params['size'],
- ];
- // 初始化CURL
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $apiUrl);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Authorization: Bearer ' . $apiKey
- ]);
- curl_setopt($ch, CURLOPT_TIMEOUT, 300);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
- curl_setopt($ch, CURLOPT_HEADER, true); // 获取响应头
- curl_setopt($ch, CURLOPT_VERBOSE, true); // 启用详细输出以进行调试
- // 创建临时文件来捕获详细的cURL输出
- $verbose = fopen('php://temp', 'w+');
- curl_setopt($ch, CURLOPT_STDERR, $verbose);
- // 执行请求
- $response = curl_exec($ch);
- //HTTP状态码
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- // 获取详细的cURL调试信息
- rewind($verbose);
- //CURL调试信息
- $verboseLog = stream_get_contents($verbose);
- fclose($verbose);
- // 分离头部和主体
- $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
- //响应头部
- $header = substr($response, 0, $header_size);
- //响应主体
- $body = substr($response, $header_size);
- // 检查CURL错误
- $curlError = curl_error($ch);
- curl_close($ch);
- $responseData = json_decode($body, true);
- // 检查API是否返回了错误信息
- if (isset($responseData['error'])) {
- $errorMessage = isset($responseData['error']['message']) ? $responseData['error']['message'] : 'API请求失败';
- return json([
- 'code' => 1,
- 'msg' => '视频生成请求失败',
- 'data' => [
- 'error_type' => isset($responseData['error']['type']) ? $responseData['error']['type'] : 'unknown',
- 'error_code' => isset($responseData['error']['code']) ? $responseData['error']['code'] : 'unknown',
- 'error_message' => $errorMessage
- ]
- ]);
- }
- // 检查是否有自定义错误格式
- if (isset($responseData['code']) && $responseData['code'] === 'fail_to_fetch_task' && isset($responseData['message'])) {
- return json([
- 'code' => 1,
- 'msg' => '视频生成请求失败',
- 'data' => [
- 'error_code' => $responseData['code'],
- 'error_message' => $responseData['message']
- ]
- ]);
- }
- // 检查是否存在id字段
- if (!isset($responseData['id'])) {
- return json([
- 'code' => 1,
- 'msg' => '无法获取视频ID',
- 'data' => [
- 'response_data' => $responseData,
- 'http_code' => $httpCode
- ]
- ]);
- }
- // 1. 先检查视频状态
- $statusUrl = 'https://chatapi.onechats.ai/v1/videos/' . $responseData['id'];
- $statusData = $this->fetchVideoStatus($statusUrl, $apiKey);
- // 检查视频状态
- if ($statusData['status'] !== 'completed') {
- return json([
- 'code' => 202,
- 'msg' => '视频尚未生成完成',
- 'data' => [
- 'video_id' => $responseData['id'],
- 'status' => $statusData['status'],
- 'progress' => $statusData['progress'],
- 'created_at' => $statusData['created_at'],
- 'message' => '请稍后再试,视频仍在' . ($statusData['status'] === 'queued' ? '排队中' : '处理中')
- ]
- ]);
- }
- // 2. 视频生成完成,准备下载
- $apiUrl = 'https://chatapi.onechats.ai/v1/videos/' . $responseData['id'] . '/content';
- // 获取可选的variant参数
- $variant = $this->request->get('variant', '');
- if (!empty($variant)) {
- $apiUrl .= '?variant=' . urlencode($variant);
- }
- // 创建保存目录
- $saveDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd');
- if (!is_dir($saveDir)) {
- mkdir($saveDir, 0755, true);
- }
- // 生成唯一文件名
- $filename = $responseData['id'] . '.mp4';
- $localPath = DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $filename;
- $fullPath = $saveDir . DS . $filename;
- // 3. 下载视频
- $videoData = $this->downloadVideo($apiUrl, $apiKey);
- // 4. 保存视频文件
- if (file_put_contents($fullPath, $videoData) === false) {
- throw new Exception('视频保存失败');
- }
- // 确保路径使用正斜杠,并只保存相对路径部分
- $localPath = str_replace('\\', '/', $localPath);
- // 移除开头的斜杠,确保路径格式为uploads/videos/...
- $savePath = ltrim($localPath, '/');
- // 返回成功响应
- return json([
- 'code' => 0,
- 'msg' => '视频下载成功',
- 'data' => [
- 'video_id' => $responseData['id'],
- 'web_url' => $savePath
- ]
- ]);
- }
- /**
- * 学生端视频状态查询接口 - 用于通过video_id查询视频状态
- */
- public function Getvideo_id(){
- // 获取并验证参数
- $params = $this->request->param();
- $videoId = $params['video_id'] ?? '';
- // 验证video_id参数
- if (empty($videoId)) {
- return json([
- 'code' => 1,
- 'msg' => '缺少必要参数:video_id',
- 'data' => []
- ]);
- }
- $aiGateway = new AIGatewayService();
- // $apiUrl = $aiGateway->config['videos']['api_url'];
- $apiKey = $aiGateway->config['videos']['api_key'];
- $apiUrl = 'https://chatapi.onechats.ai/v1/videos/' . $videoId;
- // 先检查本地是否已经有该视频
- $localVideoPath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $videoId . '.mp4';
- if (file_exists($localVideoPath)) {
- // 视频已存在本地,直接返回
- $webPath = '/uploads/videos/' . date('Ymd') . '/' . $videoId . '.mp4';
- return json([
- 'code' => 0,
- 'msg' => '视频下载成功',
- 'data' => [
- 'video_id' => $videoId,
- 'web_url' => substr($webPath, 1) // 移除开头的斜杠
- ]
- ]);
- }
- // 检查视频状态
- $statusData = $this->fetchVideoStatus($apiUrl, $apiKey);
- // 检查视频状态
- if ($statusData['status'] !== 'completed') {
- return json([
- 'code' => 202,
- 'msg' => '视频尚未生成完成',
- 'data' => [
- 'video_id' => $videoId,
- 'status' => $statusData['status'],
- 'progress' => isset($statusData['progress']) ? $statusData['progress'] : 0,
- 'created_at' => $statusData['created_at'],
- 'message' => '请稍后再试,视频仍在' . ($statusData['status'] === 'queued' ? '排队中' : '处理中')
- ]
- ]);
- }
- // 视频生成完成,下载视频
- $downloadUrl = 'https://chatapi.onechats.ai/v1/videos/' . $videoId . '/content';
- // 获取可选的variant参数
- $variant = $this->request->get('variant', '');
- if (!empty($variant)) {
- $downloadUrl .= '?variant=' . urlencode($variant);
- }
- // 创建保存目录
- $saveDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd');
- if (!is_dir($saveDir)) {
- mkdir($saveDir, 0755, true);
- }
- // 生成唯一文件名
- $filename = $videoId . '.mp4';
- $localPath = DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $filename;
- $fullPath = $saveDir . DS . $filename;
- // 下载视频
- $videoData = $this->downloadVideo($downloadUrl, $apiKey);
- // 保存视频文件
- if (file_put_contents($fullPath, $videoData) === false) {
- throw new Exception('视频保存失败');
- }
- // 确保路径使用正斜杠,并只保存相对路径部分
- $localPath = str_replace(DIRECTORY_SEPARATOR, '/', $localPath);
- // 移除开头的斜杠,确保路径格式为uploads/videos/...
- $savePath = ltrim($localPath, '/');
- // 返回成功响应
- return json([
- 'code' => 0,
- 'msg' => '视频下载成功',
- 'data' => [
- 'video_id' => $videoId,
- 'web_url' => $savePath
- ]
- ]);
- }
- //获取视频列表
- public function Getvideolist(){
- if (!$this->request->isGet()) {
- $this->error('请求方式错误');
- }
- $params = $this->request->param();
- $search = input('search', '');
- $page = isset($params['page']) ? (int)$params['page'] : 1;
- $limit = isset($params['limit']) ? (int)$params['limit'] : 50;
- $where = [];
- if (!empty($search)) {
- $where['prompt'] = ['like', '%' . $search . '%'];
- }
- $list = Db::name('video')->where('mod_rq', null)
- ->where($where)
- ->order('id desc')
- ->limit(($page - 1) * $limit, $limit)
- ->select();
- $total = Db::name('video')->where('mod_rq', null)
- ->where($where)
- ->count();
- $res['code'] = 0;
- $res['msg'] = '成功';
- $res['count'] = $total;
- $res['data'] = $list;
- return json($res);
- }
- /**
- * 文生视频/图生视频接口
- * @return \think\response\Json
- * @throws \Exception
- */
- //文生视频
- public function video(){
- $aiGateway = new AIGatewayService();
- $apiUrl = $aiGateway->config['videos']['api_url'];
- $apiKey = $aiGateway->config['videos']['api_key'];
- $params = $this->request->param();
- $postData = [
- 'prompt' => $params['prompt'],
- 'model' => $params['model'],
- 'seconds' => $params['seconds'],
- 'size' => $params['size'],
- ];
- // 初始化CURL
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $apiUrl);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Authorization: Bearer ' . $apiKey
- ]);
- curl_setopt($ch, CURLOPT_TIMEOUT, 300);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
- curl_setopt($ch, CURLOPT_HEADER, true); // 获取响应头
- curl_setopt($ch, CURLOPT_VERBOSE, true); // 启用详细输出以进行调试
- // 创建临时文件来捕获详细的cURL输出
- $verbose = fopen('php://temp', 'w+');
- curl_setopt($ch, CURLOPT_STDERR, $verbose);
- // 执行请求
- $response = curl_exec($ch);
- //HTTP状态码
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- // 获取详细的cURL调试信息
- rewind($verbose);
- //CURL调试信息
- $verboseLog = stream_get_contents($verbose);
- fclose($verbose);
- // 分离头部和主体
- $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
- //响应头部
- $header = substr($response, 0, $header_size);
- //响应主体
- $body = substr($response, $header_size);
- // 检查CURL错误
- $curlError = curl_error($ch);
- curl_close($ch);
- $responseData = json_decode($body, true);
- echo "<pre>";
- print_r($responseData);
- echo "<pre>";die;
- // 检查API是否返回了错误信息
- if (isset($responseData['error'])) {
- $errorMessage = isset($responseData['error']['message']) ? $responseData['error']['message'] : 'API请求失败';
- return json([
- 'code' => 1,
- 'msg' => '视频生成请求失败',
- 'data' => [
- 'error_type' => isset($responseData['error']['type']) ? $responseData['error']['type'] : 'unknown',
- 'error_code' => isset($responseData['error']['code']) ? $responseData['error']['code'] : 'unknown',
- 'error_message' => $errorMessage
- ]
- ]);
- }
- // 检查是否有自定义错误格式
- if (isset($responseData['code']) && $responseData['code'] === 'fail_to_fetch_task' && isset($responseData['message'])) {
- return json([
- 'code' => 1,
- 'msg' => '视频生成请求失败',
- 'data' => [
- 'error_code' => $responseData['code'],
- 'error_message' => $responseData['message']
- ]
- ]);
- }
- // 检查是否存在id字段
- if (!isset($responseData['id'])) {
- return json([
- 'code' => 1,
- 'msg' => '无法获取视频ID',
- 'data' => [
- 'response_data' => $responseData,
- 'http_code' => $httpCode
- ]
- ]);
- }
- $videoData = [
- 'video_id' => $responseData['id'],
- 'prompt' => $postData['prompt'],
- 'model' => $postData['model'],
- 'seconds' => $postData['seconds'],
- 'size' => $postData['size'],
- 'sys_rq' => date("Y-m-d H:i:s")
- ];
- echo "<pre>";
- print_r($videoData);
- echo "<pre>";die;
- // 尝试插入数据
- try {
- $res = Db::name('video')->insert($videoData);
- return json([
- 'code' => 0,
- 'msg' => '视频正在生成中',
- 'data ' => [
- 'video_id' => $responseData['id'],
- 'insert_result' => $res
- ]
- ]);
- } catch (Exception $e) {
- return json([
- 'code' => 1,
- 'msg' => '数据库操作失败',
- 'data' => [
- 'error_message' => $e->getMessage()
- ]
- ]);
- }
- }
- /**
- * 获取视频内容
- * 下载已完成的视频内容
- */
- public function videoContent(){
- // 从请求参数获取video_id,如果没有则使用默认值
- $video_id = input('get.video_id');
- $apiKey = '';
- // 1. 先检查视频状态
- $statusUrl = 'https://chatapi.onechats.ai/v1/videos/' . $video_id;
- $statusData = $this->fetchVideoStatus($statusUrl, $apiKey);
- // 检查视频状态
- if ($statusData['status'] !== 'completed') {
- return json([
- 'code' => 202,
- 'msg' => '视频尚未生成完成',
- 'data' => [
- 'video_id' => $video_id,
- 'status' => $statusData['status'],
- 'progress' => $statusData['progress'],
- 'created_at' => $statusData['created_at'],
- 'message' => '请稍后再试,视频仍在' . ($statusData['status'] === 'queued' ? '排队中' : '处理中')
- ]
- ]);
- }
- // 2. 视频生成完成,准备下载
- $apiUrl = 'https://chatapi.onechats.ai/v1/videos/' . $video_id . '/content';
- // 获取可选的variant参数
- $variant = $this->request->get('variant', '');
- if (!empty($variant)) {
- $apiUrl .= '?variant=' . urlencode($variant);
- }
- // 创建保存目录
- $saveDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd');
- if (!is_dir($saveDir)) {
- mkdir($saveDir, 0755, true);
- }
- // 生成唯一文件名
- $filename = $video_id . '.mp4';
- $localPath = DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $filename;
- $fullPath = $saveDir . DS . $filename;
- // 3. 下载视频
- $videoData = $this->downloadVideo($apiUrl, $apiKey);
- // 4. 保存视频文件
- if (file_put_contents($fullPath, $videoData) === false) {
- throw new Exception('视频保存失败');
- }
- // 确保路径使用正斜杠,并只保存相对路径部分
- $localPath = str_replace('\\', '/', $localPath);
- // 移除开头的斜杠,确保路径格式为uploads/videos/...
- $savePath = ltrim($localPath, '/');
- // 将正确格式的文件路径存入数据库
- Db::name('video')->where('video_id', $video_id)->update([
- 'web_url' => $savePath
- ]);
- // 返回成功响应
- return json([
- 'code' => 0,
- 'msg' => '视频下载成功',
- 'data' => [
- 'video_id' => $video_id,
- 'local_path' => $localPath,
- 'web_url' => $savePath,
- 'file_size' => filesize($fullPath)
- ]
- ]);
- }
- /**
- * 获取视频状态
- */
- private function fetchVideoStatus($url, $apiKey) {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HTTPGET, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Authorization: Bearer ' . $apiKey,
- 'Accept: application/json'
- ]);
- curl_setopt($ch, CURLOPT_TIMEOUT, 30);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
- $response = curl_exec($ch);
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- $error = curl_error($ch);
- curl_close($ch);
- if ($error) {
- throw new Exception('获取视频状态失败: ' . $error);
- }
- if ($httpCode < 200 || $httpCode >= 300) {
- throw new Exception('获取视频状态失败,HTTP状态码: ' . $httpCode);
- }
- $data = json_decode($response, true);
- if (!is_array($data)) {
- throw new Exception('视频状态数据格式错误');
- }
- return $data;
- }
- /**
- * 下载视频文件
- */
- private function downloadVideo($url, $apiKey) {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HTTPGET, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Authorization: Bearer ' . $apiKey
- ]);
- curl_setopt($ch, CURLOPT_TIMEOUT, 300);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
- $response = curl_exec($ch);
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- $error = curl_error($ch);
- curl_close($ch);
- if ($error) {
- throw new Exception('视频下载失败: ' . $error);
- }
- if ($httpCode < 200 || $httpCode >= 300) {
- throw new Exception('视频下载失败,HTTP状态码: ' . $httpCode);
- }
- return $response;
- }
- 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
- ];
- }
- /**
- * 查询队列列表
- * 统计文件对应的队列情况
- */
- public function get_queue_logs()
- {
- $params = $this->request->param('old_image_file', '');
- $queue_logs = Db::name('queue_logs')
- ->where('old_image_file', $params)
- ->order('id desc')
- ->select();
- $result = []; //初始化变量,避免未定义错误
- foreach ($queue_logs as &$log) {
- $taskId = $log['id'];
- $statusCount = Db::name('image_task_log')
- ->field('status, COUNT(*) as count')
- ->where('task_id', $taskId)
- ->where('mod_rq', null)
- ->group('status')
- ->select();
- $log['已完成数量'] = 0;
- $log['处理中数量'] = 0;
- $log['排队中的数量'] = 0;
- $log['失败数量'] = 0;
- foreach ($statusCount as $item) {
- switch ($item['status']) {
- case 0:
- $log['排队中的数量'] = $item['count'];
- break;
- case 1:
- $log['处理中数量'] = $item['count'];
- break;
- case 2:
- $log['已完成数量'] = $item['count'];
- break;
- case -1:
- $log['失败数量'] = $item['count'];
- break;
- }
- }
- // if ($log['排队中的数量'] >$log['已完成数量']) {
- // $result[] = $log;
- // }
- if ($log['排队中的数量']) {
- $result[] = $log;
- }
- // if ($log['处理中数量'] >= 0) {
- // $result[] = $log;
- // }
- }
- return json([
- 'code' => 0,
- 'msg' => '查询成功',
- 'data' => $result,
- 'count' => count($result)
- ]);
- }
- /**
- * 查询总队列状态(统计当前处理的数据量)
- */
- public function queueStats()
- {
- $statusList = Db::name('image_task_log')
- ->field('status, COUNT(*) as total')
- ->where('mod_rq', null)
- ->where('create_time', '>=', date('Y-m-d 00:00:00'))
- ->group('status')
- ->select();
- $statusCount = [];
- foreach ($statusList as $item) {
- $statusCount[$item['status']] = $item['total'];
- }
- // 总数为所有状态和
- $total = array_sum($statusCount);
- //获取队列当前状态
- $statusText = Db::name('queue_logs')->order('id desc')->value('status');
- return json([
- 'code' => 0,
- 'msg' => '获取成功',
- 'data' => [
- '总任务数' => $total,
- '待处理' => $statusCount[0] ?? 0,
- '处理中' => $statusCount[1] ?? 0,
- '成功' => $statusCount[2] ?? 0,
- '失败' => $statusCount[-1] ?? 0,
- '当前状态' => $statusText
- ]
- ]);
- }
- /**
- * 获取 Redis 连接实例
- * @return \Redis|null Redis 实例或 null(如果连接失败)
- */
- private function getRedisConnection()
- {
- if (!class_exists('\Redis')) {
- return null;
- }
- return getTaskRedis();
- }
- /**
- * 显示当前运行中的队列监听进程
- */
- public function viewQueueStatus()
- {
- $redis = $this->getRedisConnection();
- if (!$redis) {
- return json([
- 'code' => 1,
- 'msg' => 'Redis扩展未安装或未启用',
- 'data' => null
- ]);
- }
- $key = 'queues:imgtotxt';
- // 判断 key 是否存在,避免报错
- if (!$redis->exists($key)) {
- return json([
- 'code' => 0,
- 'msg' => '查询成功,队列为空',
- 'count' => 0,
- 'tasks_preview' => []
- ]);
- }
- $count = $redis->lLen($key);
- $list = $redis->lRange($key, 0, 9);
- // 解码 JSON 内容,确保每一项都有效
- $parsed = array_filter(array_map(function ($item) {
- return json_decode($item, true);
- }, $list), function ($item) {
- return !is_null($item);
- });
- return json([
- 'code' => 0,
- 'msg' => '查询成功',
- 'count' => $count,
- 'tasks_preview' => $parsed
- ]);
- }
- /**
- * 清空队列并删除队列日志记录
- */
- public function stopQueueProcesses()
- {
- Db::name('image_task_log')
- ->where('log', '队列中')
- ->whereOr('status', 1)
- ->where('create_time', '>=', date('Y-m-d 00:00:00'))
- ->update([
- 'status' => "-1",
- 'log' => '清空取消队列',
- 'mod_rq' => date('Y-m-d H:i:s')
- ]);
- Db::name('image_task_log')
- ->whereLike('log', '%处理中%')
- ->where('create_time', '>=', date('Y-m-d 00:00:00'))
- ->update([
- 'status' => "-1",
- 'log' => '清空取消队列',
- 'mod_rq' => date('Y-m-d H:i:s')
- ]);
- $redis = $this->getRedisConnection();
- if (!$redis) {
- return json([
- 'code' => 1,
- 'msg' => 'Redis扩展未安装或未启用',
- 'data' => null
- ]);
- }
- $key_txttoimg = 'queues:txttoimg:reserved';
- $key_txttotxt = 'queues:txttotxt:reserved';
- $key_imgtotxt = 'queues:imgtotxt:reserved';
- $key_imgtoimg = 'queues:imgtoimg:reserved';
- // 清空 Redis 队列
- $redis->del($key_txttoimg);
- $redis->del($key_txttotxt);
- $redis->del($key_imgtotxt);
- $redis->del($key_imgtoimg);
- $count = $redis->lLen($key_txttoimg) + $redis->lLen($key_txttotxt) + $redis->lLen($key_imgtotxt) + $redis->lLen($key_imgtoimg);
- // if ($count === 0) {
- // return json([
- // 'code' => 1,
- // 'msg' => '暂无队列需要停止'
- // ]);
- // }
- return json([
- 'code' => 0,
- 'msg' => '成功停止队列任务'
- ]);
- }
- /**
- * 开启队列任务
- * 暂时用不到、服务器已开启自动开启队列模式
- */
- // public function kaiStats()
- // {
- // // 判断是否已有监听进程在运行
- // $check = shell_exec("ps aux | grep 'queue:listen' | grep -v grep");
- // if ($check) {
- // return json([
- // 'code' => 1,
- // 'msg' => '监听进程已存在,请勿重复启动'
- // ]);
- // }
- // // 启动监听
- // $command = 'nohup php think queue:listen --queue --timeout=300 --sleep=3 --memory=256 > /var/log/job_queue.log 2>&1 &';
- // exec($command, $output, $status);
- // if ($status === 0) {
- // return json([
- // 'code' => 0,
- // 'msg' => '队列监听已启动'
- // ]);
- // } else {
- // return json([
- // 'code' => 1,
- // 'msg' => '队列启动失败',
- // 'output' => $output
- // ]);
- // }
- // }
- /**
- * 新增模版
- * (暂时无用)
- */
- public function Add_Product_Template(){
- try {
- $params = $this->request->param();
- $chinese_description = $params['chinese_description'] ?? '';
- $template_image_url = $params['template_image_url'] ?? '';
- $template_name = $params['template_name'] ?? '';
- $size = $params['size'] ?? '';
- $style = $params['style'] ?? '';
- $type = $params['type'] ?? '';
- $user_id = $params['user_id'] ?? '';
- $seconds = $params['seconds'] ?? '';
- $video_id = $params['video_id'] ?? '';
- if (empty($template_name)) {
- return json(['code' => 1, 'msg' => '模板名称不能为空']);
- }
- $data = [
- 'toexamine' => "未审核",
- 'chinese_description' => $chinese_description,
- 'template_image_url' => $template_image_url,
- 'template_name' => $template_name,
- 'type' => $type,
- 'style' => $style,
- 'seconds' => $seconds,
- 'size' => $size,
- 'video_id' => $video_id,
- 'user_id' => $user_id,
- 'sys_rq' => date('Y-m-d'),
- 'create_time' => date('Y-m-d H:i:s')
- ];
- $result = Db::name('product_template')->insert($data);
- if ($result) {
- return json(['code' => 0, 'msg' => '模板保存成功']);
- } else {
- 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|template_name|style'] = ['like', '%' . $params['search'] . '%'];
- }
- if (!empty($params['sys_id'])) {
- $where['sys_id'] = ['like', '%' . $params['sys_id'] . '%'];
- $products = Db::name('product_template')->order('id desc')->where($where)
- ->whereNull('mod_rq')
- ->select();
- }else{
- $products = Db::name('product_template')->order('id desc')->where($where)
- ->where('release','1')
- ->whereNull('mod_rq')
- ->select();
- }
- return json([
- 'code' => 0,
- 'msg' => '请求成功',
- 'data' => $products
- ]);
- }
- /**
- *获取服务器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);
- }
- /**
- * 获取 AI 模型配置
- * status 1 = 启用 0 = 禁用(同一模型内的优先级,数值越小越优先)
- * model_type 支持多能力逗号间隔(如 文生图,图生图),传参精确匹配某一能力
- * 可选参数:manage=1 时返回全部(含禁用),用于管理端
- */
- public function GetAIModel(){
- $params = $this->request->param();
- $query = Db::name('ai_model');
- if (empty($params['manage'])) {
- $query->where('status', '1');
- }
- if (!empty($params['model_type'])) {
- $query->whereRaw('FIND_IN_SET(:mt, model_type) > 0', ['mt' => trim($params['model_type'])]);
- }
- if (!empty($params['supplier'])) {
- $query->where('supplier', 'like', '%' . $params['supplier'] . '%');
- }
- if (!empty($params['model_name'])) {
- $query->where('model_name|model_alias', 'like', '%' . $params['model_name'] . '%');
- }
- $data = $query->order('sort ASC, id ASC')->select();
- return json([
- 'code' => 0,
- 'msg' => '成功',
- 'data' => $data
- ]);
- }
- /**
- * 新增 AI 模型配置
- * POST: status, supplier, api_key, api_url, model_group, model_name, model_alias, model_type, sort
- * model_type 多能力用逗号间隔,如:文生图,图生图
- */
- public function AddAIModel(){
- $params = $this->request->param();
- $required = ['api_url', 'api_key', 'model_name', 'model_type'];
- foreach ($required as $k) {
- if (empty(trim($params[$k] ?? ''))) {
- return json(['code' => 1, 'msg' => $k . ' 不能为空']);
- }
- }
- $insert = [
- 'status' => isset($params['status']) ? trim($params['status']) : '1',
- 'supplier' => trim($params['supplier'] ?? ''),
- 'api_key' => trim($params['api_key']),
- 'api_url' => trim($params['api_url']),
- 'model_group' => trim($params['model_group'] ?? ''),
- 'model_name' => trim($params['model_name']),
- 'model_alias' => trim($params['model_alias'] ?? $params['model_name'] ?? ''),
- 'model_type' => trim($params['model_type']),
- 'sort' => isset($params['sort']) ? intval($params['sort']) : 0,
- ];
- try {
- Db::name('ai_model')->insert($insert);
- return json(['code' => 0, 'msg' => '新增成功']);
- } catch (\Exception $e) {
- return json(['code' => 1, 'msg' => '新增失败: ' . $e->getMessage()]);
- }
- }
- /**
- * 修改 AI 模型配置
- * POST: id(必填), 其余字段同新增
- */
- public function UpdateAIModel(){
- $params = $this->request->param();
- if (empty($params['id'])) {
- return json(['code' => 1, 'msg' => 'id 不能为空']);
- }
- $id = intval($params['id']);
- $exists = Db::name('ai_model')->where('id', $id)->find();
- if (!$exists) {
- return json(['code' => 1, 'msg' => '记录不存在']);
- }
- $update = [];
- $fields = ['status', 'supplier', 'api_key', 'api_url', 'model_group', 'model_name', 'model_alias', 'model_type', 'sort'];
- foreach ($fields as $f) {
- if (array_key_exists($f, $params)) {
- $update[$f] = $f === 'sort' ? intval($params[$f]) : trim($params[$f] ?? '');
- }
- }
- if (empty($update)) {
- return json(['code' => 1, 'msg' => '无有效修改字段']);
- }
- try {
- Db::name('ai_model')->where('id', $id)->update($update);
- return json(['code' => 0, 'msg' => '修改成功']);
- } catch (\Exception $e) {
- return json(['code' => 1, 'msg' => '修改失败: ' . $e->getMessage()]);
- }
- }
- /**
- * 用于获取所有产品记录
- **/
- public function GetProductList(){
- $params = $this->request->param();
- // 构建查询条件
- $where = [];
- if (!empty($params['search'])) {
- $where['prompt|model'] = ['like', '%' . $params['search'] . '%'];
- }
- if (!empty($params['sys_id'])) {
- $where['sys_id'] = ['like', '%' . $params['sys_id'] . '%'];
- }
- $data = Db::name('product_image_generate')->where($where)->order('id desc')->limit(0,10)->select();
- $prompt = Db::name('product_image_generate')->field('prompt')->where($where)->group('prompt')->order('id desc')->select();
- return json([
- 'code' => 0,
- 'msg' => '成功',
- 'prompt' => $prompt,
- 'data' => $data
- ]);
- }
- }
|