| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385 |
- <?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')
- // ];
- // $taskInfo['image'] = Common::ossFullUrl((string)$taskInfo['image']);
- // $taskInfo['image_url'] = Common::ossFullUrl((string)$taskInfo['image_url']);
- // $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);
- if (!empty($taskInfo['image'])) {
- $taskInfo['image'] = Common::ossFullUrl((string)$taskInfo['image']);
- }
- if (!empty($taskInfo['image_url'])) {
- $taskInfo['image_url'] = Common::ossFullUrl((string)$taskInfo['image_url']);
- }
- $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()
- {
- $apiUrl = '';
- $apiKey = '';
- $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()
- {
- $apiUrl = '';
- $apiKey = '';
- $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
- ]
- ]);
- }
- //获取视频列表
- 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);
- }
- /**
- * 文生视频/图生视频接口
- */
- //文生视频
- public function video(){
- $apiUrl = '';
- $apiKey = '';
- $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 product_template()
- {
- $params = $this->request->param();
- if (!$this->request->isGet()) {
- $this->error('请求方法错误');
- }
- $page = isset($params['page']) ? (int)$params['page'] : 1;
- $limit = isset($params['limit']) ? (int)$params['limit'] : 30;
- $where = [];
- if (!empty($params['search'])) {
- $where['id|chinese_description|template_name|style'] = ['like', '%' . $params['search'] . '%'];
- }
- // toexamine / release:用 isset + 非空串,避免 empty(0) 导致「未发布」无法筛选;release 建议库中为 0/1
- if (isset($params['toexamine']) && $params['toexamine'] !== '') {
- $where['toexamine'] = $params['toexamine'];
- }
- if (isset($params['release']) && $params['release'] !== '') {
- $where['release'] = is_numeric($params['release']) ? (int) $params['release'] : $params['release'];
- }
- $isSuperAdmin = false;
- if (!empty($params['sys_id']) && $params['sys_id'] == '超级管理员') {
- $isSuperAdmin = true;
- }
- if (!$isSuperAdmin && !empty($params['sys_id'])) {
- $where['sys_id'] = ['like', '%' . $params['sys_id'] . '%'];
- $products = Db::name('product_template')->order('id desc')->where($where)
- ->whereNull('mod_rq')
- ->limit(($page - 1) * $limit, $limit)
- ->select();
- }else{
- $products = Db::name('product_template')->order('id desc')->where($where)
- ->whereNull('mod_rq')
- ->limit(($page - 1) * $limit, $limit)
- ->select();
- }
- $total = Db::name('product_template')->where($where)
- ->whereNull('mod_rq')
- ->count();
- foreach ($products as &$item) {
- if (!empty($item['template_image_url'])) {
- $item['template_image_url'] = Common::ossFullUrl((string)$item['template_image_url']);
- }
- if (!empty($item['thumbnail_image'])) {
- $item['thumbnail_image'] = Common::ossFullUrl((string)$item['thumbnail_image']);
- }
- if (array_key_exists('chinese_description', $item)) {
- $item['chinese_description'] = Common::decodeChineseDescriptionForApi($item['chinese_description']);
- }
- if (!empty($item['page_image_urls'])) {
- $arr = json_decode((string) $item['page_image_urls'], true);
- if (is_array($arr)) {
- foreach ($arr as &$pu) {
- if ($pu !== null && $pu !== '') {
- $pu = Common::ossFullUrl((string) $pu);
- }
- }
- unset($pu);
- $item['page_image_urls'] = $arr;
- }
- }
- }
- unset($item);
- return json([
- 'code' => 0,
- 'msg' => '请求成功',
- 'count' => $total,
- 'data' => $products
- ]);
- }
- /**
- * 新增模版
- * (暂时无用)
- */
- // 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()]);
- // }
- // }
- /**
- * 获取 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'] . '%');
- }
- $list = $query
- ->field('id,model_alias,model_group,model_name,model_type,sort,status,supplier')
- ->order('sort ASC, id ASC')->select();
- return json([
- 'code' => 0,
- 'msg' => '成功',
- 'data' => $list
- ]);
- }
- /**
- * 新增 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' => $params['status'],
- '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']),
- '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();
- $page = max(1, intval($params['page'] ?? 1));
- $pageSize = min(100, max(1, intval($params['limit'] ?? 30)));
- // 构建查询条件
- $where = [];
- if (!empty($params['search'])) {
- $where['prompt|model'] = ['like', '%' . $params['search'] . '%'];
- }
- if (!empty($params['sys_id'])) {
- $where['sys_id'] = ['like', '%' . $params['sys_id'] . '%'];
- }
- // $isSuperAdmin = false;
- // if (!empty($params['sys_id']) && $params['sys_id'] == '超级管理员') {
- // $isSuperAdmin = true;
- // }
- //
- // if (!$isSuperAdmin && !empty($params['sys_id'])) {
- // 普通
- // }else{
- //
- // }
- $prompt = Db::name('product_image_generate')->field('prompt')->where($where)->group('prompt')->order('id desc')->select();
- $data = Db::name('product_image_generate')->where($where)->order('id desc')->page($page, $pageSize)->select();
- $count = Db::name('product_image_generate')->field('prompt')->where($where)->order('id desc')->count();
- foreach ($data as &$item) {
- if (!empty($item['generated_image']) || !empty($item['product_img']) || !empty($item['reference_image'])) {
- $item['generated_image'] = Common::ossFullUrl((string)$item['generated_image']);
- $item['product_img'] = Common::ossFullUrl((string)$item['product_img']);
- $item['reference_image'] = Common::ossFullUrl((string)$item['reference_image']);
- }
- }
- unset($item);
- return json([
- 'code' => 0,
- 'msg' => '成功',
- 'count' => $count,
- 'prompt' => $prompt,
- 'data' => $data
- ]);
- }
- /**
- * 查询队列列表
- * 统计文件对应的队列情况
- */
- 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
- // ]);
- // }
- // }
- /**
- *获取服务器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);
- }
- }
|