WorkOrder.php 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use app\job\ImageJob;
  5. use app\service\AIGatewayService;
  6. use app\service\ImageService;
  7. use think\App;
  8. use think\Db;
  9. use think\Exception;
  10. use think\Log;
  11. use think\Queue;
  12. use think\queue\job\Redis;
  13. use think\Request;
  14. class WorkOrder extends Api{
  15. protected $noNeedLogin = ['*'];
  16. protected $noNeedRight = ['*'];
  17. public function index(){echo '访问成功';}
  18. /**
  19. * AI队列入口处理 出图接口
  20. * 此方法处理图像转换为文本的请求,将图像信息存入队列以供后续处理。
  21. */
  22. public function imageToText()
  23. {
  24. $params = $this->request->param();
  25. $service = new ImageService();
  26. $service->handleImage($params);
  27. $this->success('任务成功提交至队列');
  28. }
  29. /**
  30. * task_id:查询获取任务图片
  31. */
  32. public function GetImageStatus(){
  33. // $taskInfo = [
  34. // 'status' => 'completed',
  35. // 'image' => '/uploads/Product/img2img-20260317152818-69b902924548d.png',
  36. // 'image_url' => '/uploads/Product/img2img-20260317152818-69b902924548d.png',
  37. // 'completed_at' => date('Y-m-d H:i:s')
  38. // ];
  39. // $res = [
  40. // 'code' => 0,
  41. // 'msg' => '查询成功',
  42. // 'data' => $taskInfo
  43. // ];
  44. // return json($res);die;
  45. $params = $this->request->param();
  46. $taskId = $params['task_id'];
  47. if (empty($taskId)) {
  48. $res = [
  49. 'code' => 1,
  50. 'msg' => '任务ID不能为空'
  51. ];
  52. return json($res);
  53. }
  54. //从Redis中获取任务状态
  55. $redis = getTaskRedis();
  56. $taskData = $redis->get("img_to_img_task:{$taskId}");
  57. if (!$taskData) {
  58. $taskData = $redis->get("text_to_image_task:{$taskId}");
  59. }
  60. if (!$taskData) {
  61. $res = [
  62. 'code' => 1,
  63. 'msg' => '任务不存在或已过期',
  64. ];
  65. return json($res);
  66. }
  67. $taskInfo = json_decode($taskData, true);
  68. $res = [
  69. 'code' => 0,
  70. 'msg' => '查询成功',
  71. 'data' => $taskInfo
  72. ];
  73. return json($res);
  74. }
  75. /**
  76. * 支持的AI任务类型枚举(前端传入的status_val需在该列表内)
  77. * 键:前端传入值,值:方法后缀( '前端传入值' => '方法后缀')
  78. */
  79. private static $AI_TASK_TYPES = [
  80. '图生文' => 'ImgToText',
  81. '文生文' => 'TextToText',
  82. '文生图' => 'TextToImg',
  83. '图生图' => 'ImgToImg'
  84. ];
  85. /**
  86. * AI模型接口统一调用入口
  87. * @description 接收前端AI请求,校验任务类型合法性,分发至对应处理方法,统一异常捕获
  88. * @return \think\response\Json 标准化JSON响应
  89. */
  90. public function callAIModelApi()
  91. {
  92. try {
  93. // 1. 获取并校验入参
  94. $params = $this->request->param();
  95. // echo "<pre>";
  96. // print_r($params);
  97. // echo "<pre>";die;
  98. $statusVal = $this->validateAndGetStatusVal($params);
  99. // 2. 映射并校验处理方法
  100. $method = $this->getHandleMethod($statusVal);
  101. // 3. 执行对应处理逻辑并返回响应
  102. return $this->$method($params);
  103. } catch (\InvalidArgumentException $e) {
  104. // 参数/方法异常(用户侧错误)
  105. return $this->jsonResponse(1, $e->getMessage());
  106. } catch (\Throwable $e) {
  107. // 系统异常(服务侧错误)
  108. \think\Log::error('AI接口处理异常:' . $e->getMessage() . ' | 任务类型:' . ($params['status_val'] ?? '未知') . ' | 异常行:' . $e->getLine());
  109. return $this->jsonResponse(1, '服务异常,请稍后重试');
  110. }
  111. }
  112. // -------------------------- 私有核心方法(通用逻辑) --------------------------
  113. /**
  114. * 校验并获取合法的任务类型
  115. * @param array $params 前端入参
  116. * @return string 合法的status_val
  117. * @throws \InvalidArgumentException 任务类型不合法时抛出
  118. */
  119. private function validateAndGetStatusVal(array $params): string
  120. {
  121. $statusVal = trim($params['status_val'] ?? '');
  122. // 空值校验
  123. if (empty($statusVal)) {
  124. throw new \InvalidArgumentException('任务类型不能为空');
  125. }
  126. // 合法性校验
  127. if (!array_key_exists($statusVal, self::$AI_TASK_TYPES)) {
  128. throw new \InvalidArgumentException('不支持的任务类型:' . $statusVal);
  129. }
  130. return $statusVal;
  131. }
  132. /**
  133. * 获取任务对应的处理方法名
  134. * @param string $statusVal 合法的任务类型
  135. * @return string 处理方法名(如handleAiImgToText)
  136. * @throws \InvalidArgumentException 方法未实现时抛出
  137. */
  138. private function getHandleMethod(string $statusVal): string
  139. {
  140. $methodSuffix = self::$AI_TASK_TYPES[$statusVal];
  141. $method = 'handleAi' . $methodSuffix;
  142. if (!method_exists($this, $method)) {
  143. throw new \InvalidArgumentException('任务类型暂未实现:' . $statusVal);
  144. }
  145. return $method;
  146. }
  147. /**
  148. * 通用JSON响应封装
  149. * @param int $code 响应码(0=成功,1=失败)
  150. * @param string $msg 响应信息
  151. * @param array $data 响应数据(可选)
  152. * @return \think\response\Json
  153. */
  154. private function jsonResponse(int $code, string $msg, array $data = []): \think\response\Json
  155. {
  156. $response = [
  157. 'code' => $code,
  158. 'msg' => $msg,
  159. 'time' => date('Y-m-d H:i:s')
  160. ];
  161. if (!empty($data)) {
  162. $response['data'] = $data;
  163. }
  164. return json($response);
  165. }
  166. /**
  167. * 任务类接口统一响应(带task_id的场景)
  168. * @param array $result 业务处理结果(需包含success字段)
  169. * @param string $failMsg 失败提示语
  170. * @return \think\response\Json
  171. */
  172. private function jsonTaskResponse(array $result, string $failMsg = '任务提交失败'): \think\response\Json
  173. {
  174. $isSuccess = isset($result['success']) && $result['success'];
  175. $data = $isSuccess ? ['task_id' => $result['task_id'] ?? ''] : [];
  176. $msg = $isSuccess ? ($result['message'] ?? '提交成功') : ($result['message'] ?? $failMsg);
  177. return $this->jsonResponse($isSuccess ? 0 : 1, $msg, $data);
  178. }
  179. // -------------------------- 业务处理方法(按任务类型拆分) --------------------------
  180. /**
  181. * 图生文任务处理:提交队列并返回提示
  182. * @param array $params 前端入参
  183. * @return \think\response\Json
  184. */
  185. private function handleAiImgToText(array $params): \think\response\Json
  186. {
  187. (new ImageService())->handleImgToText($params);
  188. return $this->jsonResponse(0, '正在优化提示词,请稍等.....');
  189. }
  190. /**
  191. * 文生文任务处理:生成话术并返回内容(支持产品内容更新)
  192. * @param array $params 前端入参
  193. * @return \think\response\Json
  194. */
  195. private function handleAiTextToText(array $params): \think\response\Json
  196. {
  197. // echo "<pre>";
  198. // print_r($params);
  199. // echo "<pre>";die;
  200. //构造生成提示词
  201. $promptTemplate = "\n请根据上述内容生成一段完整的话术,要求:\n"
  202. . "1. 内容必须是连贯的一段话,不要使用列表、分隔线或其他结构化格式\n"
  203. . "2. 不要包含非文本元素的描述\n"
  204. . "3. 不要添加任何额外的引导语、解释或开场白\n"
  205. . "4. 禁忌:不添加无关形容词,不修改产品核心信息,语言流畅自然";
  206. $prompt = ($params['prompt'] ?? '') . $promptTemplate;
  207. // 调用服务层生成内容
  208. $result = (new ImageService())->handleTextToText(
  209. $params['status_val'],
  210. $prompt,
  211. $params['model']
  212. );
  213. if (empty($result['success'])) {
  214. return $this->jsonResponse(1, $result['message'] ?? '生成失败');
  215. }
  216. $content = $result['data'] ?? '';
  217. //区分业务场景处理
  218. $isProductImageGeneration = ($params['status_type'] ?? '') === 'ProductImageGeneration';
  219. $isProductTemplateReplace = ($params['status_type'] ?? '') === 'ProductTemplateReplace';
  220. if (!$isProductImageGeneration && !$isProductTemplateReplace) {
  221. Db::name('product')->where('id', $params['id'])->update(['content' => $content]);
  222. }
  223. return $this->jsonResponse(0, '优化成功', ['content' => $content]);
  224. }
  225. /**
  226. * 文生图任务处理:提交任务并返回task_id
  227. * @param array $params 前端入参
  228. * @return \think\response\Json
  229. */
  230. private function handleAiTextToImg(array $params): \think\response\Json
  231. {
  232. $serviceResult = (new ImageService())->handleTextToImg($params);
  233. return $this->jsonTaskResponse($serviceResult, '文生图任务提交失败');
  234. }
  235. /**
  236. * 图生图任务处理:提交任务并返回task_id
  237. * @param array $params 前端入参
  238. * @return \think\response\Json
  239. */
  240. private function handleAiImgToImg(array $params): \think\response\Json
  241. {
  242. $serviceResult = (new ImageService())->handleImgToImg($params);
  243. return $this->jsonTaskResponse($serviceResult, '图生图任务提交失败');
  244. }
  245. /**
  246. * 即梦AI--创建视频任务接口
  247. * 首帧图 + 尾帧图 = 新效果视频
  248. */
  249. public function Create_ImgToVideo()
  250. {
  251. $aiGateway = new AIGatewayService();
  252. $apiUrl = $aiGateway->config['Create_ImgToVideo']['api_url'];
  253. $apiKey = $aiGateway->config['Create_ImgToVideo']['api_key'];
  254. $params = $this->request->param();
  255. $modelParams = [
  256. 'resolution' => $params['resolution'] ?? '720p', // 分辨率:480p, 720p, 1080p
  257. 'duration' => $params['duration'] ?? 5, // 视频时长(秒)
  258. 'camerafixed' => $params['camerafixed'] ?? false, // 相机固定
  259. 'watermark' => $params['watermark'] ?? true, // 水印
  260. 'aspect_ratio' => $params['aspect_ratio'] ?? '16:9' // 视频比例:16:9, 4:3, 1:1等
  261. ];
  262. // 构建提示词
  263. $prompt = $params['prompt'] ?? '';
  264. $prompt .= ' --resolution ' . $modelParams['resolution'];
  265. $prompt .= ' --duration ' . $modelParams['duration'];
  266. $prompt .= ' --camerafixed ' . ($modelParams['camerafixed'] ? 'true' : 'false');
  267. $prompt .= ' --watermark ' . ($modelParams['watermark'] ? 'true' : 'false');
  268. $prompt .= ' --aspect_ratio ' . $modelParams['aspect_ratio'];
  269. // 构建请求数据
  270. $data = [
  271. 'model' => 'doubao-seedance-1-0-pro-250528',//模型
  272. 'content' => [
  273. [
  274. 'type' => 'text',
  275. 'text' => $prompt
  276. ],
  277. [
  278. 'type' => 'image_url',
  279. 'image_url' => [
  280. 'url' => $params['first_image_url']// 首帧图片URL(参数)
  281. ],
  282. 'role' => 'first_image'
  283. ],
  284. [
  285. 'type' => 'image_url',
  286. 'image_url' => [
  287. 'url' => $params['last_image_url'] // 尾帧图片URL(参数)
  288. ],
  289. 'role' => 'last_image'
  290. ]
  291. ]
  292. ];
  293. // 转换为 JSON 字符串
  294. $jsonData = json_encode($data);
  295. // 初始化 cURL
  296. $ch = curl_init();
  297. curl_setopt($ch, CURLOPT_URL, $apiUrl);
  298. curl_setopt($ch, CURLOPT_POST, true);
  299. curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
  300. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  301. 'Content-Type: application/json',
  302. 'Authorization: Bearer ' . $apiKey
  303. ]);
  304. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  305. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 开发环境临时关闭SSL验证
  306. curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 超时时间
  307. // 执行请求
  308. $response = curl_exec($ch);
  309. // 检查 cURL 错误
  310. if (curl_errno($ch)) {
  311. $error = curl_error($ch);
  312. curl_close($ch);
  313. return json(['code' => 0, 'msg' => 'Curl 错误: ' . $error]);
  314. }
  315. curl_close($ch);
  316. // 解析响应
  317. $responseData = json_decode($response, true);
  318. // 检查 API 错误
  319. if (isset($responseData['error'])) {
  320. return json(['code' => 0, 'msg' => 'API 错误: ' . $responseData['error']['message']]);
  321. }
  322. // 获取任务 ID
  323. $taskId = $responseData['id'] ?? '';
  324. if (empty($taskId)) {
  325. return json(['code' => 0, 'msg' => '获取任务 ID 失败']);
  326. }
  327. // 返回结果
  328. return json([
  329. 'code' => 1,
  330. 'data' => [
  331. 'task_id' => $taskId,
  332. 'status' => $responseData['status'] ?? '',
  333. 'created_at' => $responseData['created_at'] ?? ''
  334. ]
  335. ]);
  336. }
  337. /**
  338. * 即梦AI--获取视频接口
  339. * 首帧图 + 尾帧图 = 新效果视频
  340. */
  341. public function Get_ImgToVideo()
  342. {
  343. $aiGateway = new AIGatewayService();
  344. $apiUrl = $aiGateway->config['Create_ImgToVideo']['api_url'];
  345. $apiKey = $aiGateway->config['Create_ImgToVideo']['api_key'];
  346. $params = $this->request->param();
  347. $taskId = $params['task_id'] ?? '';
  348. if (empty($taskId)) {
  349. return json(['code' => 0, 'msg' => '任务 ID 不能为空']);
  350. }
  351. // 查询任务状态
  352. $queryUrl = $apiUrl . '/' . $taskId;
  353. $ch2 = curl_init();
  354. curl_setopt($ch2, CURLOPT_URL, $queryUrl);
  355. curl_setopt($ch2, CURLOPT_HTTPHEADER, [
  356. 'Content-Type: application/json',
  357. 'Authorization: Bearer ' . $apiKey
  358. ]);
  359. curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
  360. curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false); // 开发环境临时关闭SSL验证
  361. curl_setopt($ch2, CURLOPT_TIMEOUT, 60); // 超时时间
  362. $queryResponse = curl_exec($ch2);
  363. // 检查 cURL 错误
  364. if (curl_errno($ch2)) {
  365. $error = curl_error($ch2);
  366. curl_close($ch2);
  367. return json(['code' => 0, 'msg' => 'Curl 错误: ' . $error]);
  368. }
  369. curl_close($ch2);
  370. // 解析查询响应
  371. $queryData = json_decode($queryResponse, true);
  372. // print_r($queryData);die;
  373. // 轮询任务状态,直到完成
  374. $maxPolls = 30; // 最大轮询次数
  375. $pollCount = 0;
  376. $taskStatus = $queryData['status'] ?? '';
  377. while (!in_array($taskStatus, ['completed', 'succeeded']) && $pollCount < $maxPolls) {
  378. sleep(5); // 每5秒轮询一次
  379. $pollCount++;
  380. // 再次查询任务状态
  381. $ch3 = curl_init();
  382. curl_setopt($ch3, CURLOPT_URL, $queryUrl);
  383. curl_setopt($ch3, CURLOPT_HTTPHEADER, [
  384. 'Content-Type: application/json',
  385. 'Authorization: Bearer ' . $apiKey
  386. ]);
  387. curl_setopt($ch3, CURLOPT_RETURNTRANSFER, true);
  388. curl_setopt($ch3, CURLOPT_SSL_VERIFYPEER, false);
  389. curl_setopt($ch3, CURLOPT_TIMEOUT, 60);
  390. $pollResponse = curl_exec($ch3);
  391. curl_close($ch3);
  392. $pollData = json_decode($pollResponse, true);
  393. $taskStatus = $pollData['status'] ?? '';
  394. // 检查任务是否失败
  395. if ($taskStatus === 'failed') {
  396. return json(['code' => 0, 'msg' => '任务执行失败']);
  397. }
  398. }
  399. // 如果任务已经成功,直接使用 $queryData
  400. if (empty($pollData) && isset($queryData['status']) && $queryData['status'] === 'succeeded') {
  401. $pollData = $queryData;
  402. }
  403. // 检查轮询是否超时
  404. if (!in_array($taskStatus, ['completed', 'succeeded'])) {
  405. return json(['code' => 0, 'msg' => '任务执行超时']);
  406. }
  407. // 获取视频 URL
  408. $videoUrl = $pollData['content']['video_url'] ?? '';
  409. if (empty($videoUrl)) {
  410. return json(['code' => 0, 'msg' => '获取视频 URL 失败', 'data' => ['pollData' => $pollData]]);
  411. }
  412. // 确保保存目录存在
  413. $saveDir = ROOT_PATH . 'public/uploads/ceshi/';
  414. if (!is_dir($saveDir)) {
  415. mkdir($saveDir, 0755, true);
  416. }
  417. // 生成保存文件名
  418. $fileName = $taskId . '.mp4';
  419. $savePath = $saveDir . '/' . $fileName;
  420. // 下载视频
  421. // 设置超时时间为300秒(5分钟)
  422. $context = stream_context_create(['http' => ['timeout' => 300]]);
  423. $videoContent = file_get_contents($videoUrl, false, $context);
  424. if ($videoContent === false) {
  425. return json(['code' => 0, 'msg' => '下载视频失败', 'data' => ['videoUrl' => $videoUrl]]);
  426. }
  427. // 保存视频到文件
  428. $saveResult = file_put_contents($savePath, $videoContent);
  429. if ($saveResult === false) {
  430. return json(['code' => 0, 'msg' => '保存视频失败', 'data' => ['savePath' => $savePath, 'dirWritable' => is_writable($saveDir)]]);
  431. }
  432. // 生成视频的访问 URL
  433. $videoAccessUrl = '/uploads/ceshi/' . $fileName;
  434. // 返回结果
  435. return json([
  436. 'code' => 1,
  437. 'data' => [
  438. 'task_id' => $taskId,
  439. 'status' => $taskStatus,
  440. 'video_url' => $videoAccessUrl,
  441. 'save_path' => $savePath
  442. ]
  443. ]);
  444. }
  445. /**
  446. * 九个分镜头生成流程
  447. * 模型:gemini-3-pro-image-preview
  448. * 说明:
  449. * 第一步:(提示词 + 原始图片 = 九个分镜头图片) 或 (提示词 = 九个分镜头图片)
  450. * 第二步:使用九个分镜头图进行裁剪单图生成连贯视频
  451. * 第三步:在通过分镜头视频拼接成一个完整的视频(列如每个分镜头视频为8秒,九个为72秒形成完整视频)
  452. */
  453. public function Get_txttonineimg()
  454. {
  455. // 发起接口请求
  456. // $apiUrl = 'https://chatapi.onechats.ai/v1beta/models/gemini-3-pro-image-preview:generateContent';
  457. $apiUrl = 'https://chatapi.onechats.ai/v1beta/models/gemini-3-pro-image-preview:streamGenerateContent';
  458. $apiKey = '';
  459. // $params = $this->request->param();
  460. $prompt = '生成一个苹果(九个分镜头图片)';
  461. $requestData = [
  462. "contents" => [
  463. [
  464. "role" => "user",
  465. "parts" => [
  466. ["text" => $prompt]
  467. ]
  468. ]
  469. ],
  470. "generationConfig" => [
  471. "responseModalities" => ["TEXT", "IMAGE"],
  472. "imageConfig" => [
  473. "aspectRatio" => "1:1"
  474. ]
  475. ]
  476. ];
  477. $ch = curl_init();
  478. curl_setopt($ch, CURLOPT_URL, $apiUrl);
  479. curl_setopt($ch, CURLOPT_POST, true);
  480. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData, JSON_UNESCAPED_UNICODE));
  481. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  482. 'Content-Type: application/json',
  483. 'Authorization: Bearer ' . $apiKey
  484. ]);
  485. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  486. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 开发环境临时关闭SSL验证
  487. curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 生成图片超时时间(建议60秒)
  488. $response = curl_exec($ch);
  489. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  490. $error = curl_error($ch);
  491. curl_close($ch);
  492. $res = json_decode($response, true);
  493. // 构建URL路径(使用正斜杠)
  494. $url_path = '/uploads/txtnewimg/';
  495. // 构建物理路径(使用正斜杠确保统一格式)
  496. $save_path = ROOT_PATH . 'public' . '/' . 'uploads' . '/' . 'txtnewimg' . '/';
  497. // 移除ROOT_PATH中可能存在的反斜杠,确保统一使用正斜杠
  498. $save_path = str_replace('\\', '/', $save_path);
  499. // 自动创建文件夹(如果不存在)
  500. if (!is_dir($save_path)) {
  501. mkdir($save_path, 0755, true);
  502. }
  503. // 提取base64图片数据
  504. $text_content = $res['candidates'][0]['content']['parts'][0]['inlineData']['data'];
  505. $str = 'data:image/jpeg;base64,';
  506. $text_content = $str. $text_content;
  507. // 匹配base64图片数据
  508. preg_match('/data:image\/(png|jpg|jpeg);base64,([^"]+)/', $text_content, $matches);
  509. if (empty($matches)) {
  510. return '未找到图片数据';
  511. }
  512. $image_type = $matches[1];
  513. $base64_data = $matches[2];
  514. // 解码base64数据
  515. $image_data = base64_decode($base64_data);
  516. if ($image_data === false) {
  517. return '图片解码失败';
  518. }
  519. // 生成唯一文件名(包含扩展名)
  520. $file_name = uniqid() . '.' . $image_type;
  521. $full_file_path = $save_path . $file_name;
  522. // 保存图片到文件系统
  523. if (!file_put_contents($full_file_path, $image_data)) {
  524. return '图片保存失败';
  525. }
  526. // 生成数据库存储路径(使用正斜杠格式)
  527. $db_img_path = $url_path . $file_name;
  528. return $db_img_path;
  529. }
  530. public function GetTxtToImg(){
  531. $params = $this->request->param();
  532. $prompt = $params['prompt'];//提示词
  533. $model = $params['model'];//模型
  534. $size = $params['size'];//尺寸
  535. // 调用AI生成图片
  536. $aiGateway = new AIGatewayService();
  537. $res = $aiGateway->callDalleApi($prompt, $model, $size);
  538. // 提取base64图片数据
  539. $imageData = '';
  540. $imageType = 'png'; // 默认图片类型
  541. if (isset($res['candidates'][0]['content']['parts'][0]['text'])) {
  542. $text_content = $res['candidates'][0]['content']['parts'][0]['text'];
  543. // 匹配base64图片数据和类型
  544. if (preg_match('/data:image\/([a-zA-Z0-9]+);base64,([^\s]+)/', $text_content, $matches)) {
  545. $imageType = strtolower($matches[1]);
  546. $base64Data = $matches[2];
  547. // 解码base64数据
  548. $imageData = base64_decode($base64Data);
  549. }
  550. }
  551. if (!$imageData) {
  552. return json(['code' => 1, 'msg' => '图片生成失败,未找到有效图片数据']);
  553. }
  554. // 创建保存目录(public/uploads/log/YYYY-MM/)
  555. $yearMonth = date('Ym');
  556. $saveDir = ROOT_PATH . 'public/uploads/ceshi/' . $yearMonth . '/';
  557. if (!is_dir($saveDir)) {
  558. mkdir($saveDir, 0755, true);
  559. }
  560. // 生成唯一文件名
  561. $fileName = uniqid() . '.' . $imageType;
  562. $filePath = $saveDir . $fileName;
  563. // 保存图片到本地文件
  564. if (file_put_contents($filePath, $imageData) === false) {
  565. return json(['code' => 1, 'msg' => '图片保存失败']);
  566. }
  567. // 生成前端可访问的URL
  568. $imageUrl = '/uploads/ceshi/' . $yearMonth . '/' . $fileName;
  569. // 返回标准JSON响应
  570. return json([
  571. 'code' => 0,
  572. 'msg' => '图片生成成功',
  573. 'data' => [
  574. 'url' => $imageUrl
  575. ]
  576. ]);
  577. }
  578. /**
  579. * 学生端文生视频接口 - 用于生成视频
  580. */
  581. public function GetTxtToVideo(){
  582. $aiGateway = new AIGatewayService();
  583. $apiUrl = $aiGateway->config['videos']['api_url'];
  584. $apiKey = $aiGateway->config['videos']['api_key'];
  585. // 获取并验证参数
  586. $params = $this->request->param();
  587. // echo "<pre>";
  588. // print_r($params);
  589. // echo "<pre>";die;
  590. $postData = [
  591. 'prompt' => $params['prompt'],
  592. 'model' => $params['model'],
  593. 'seconds' => $params['duration'],
  594. 'size' => $params['size'],
  595. ];
  596. // 初始化CURL
  597. $ch = curl_init();
  598. curl_setopt($ch, CURLOPT_URL, $apiUrl);
  599. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  600. curl_setopt($ch, CURLOPT_POST, true);
  601. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  602. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  603. 'Authorization: Bearer ' . $apiKey
  604. ]);
  605. curl_setopt($ch, CURLOPT_TIMEOUT, 300);
  606. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  607. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  608. curl_setopt($ch, CURLOPT_HEADER, true); // 获取响应头
  609. curl_setopt($ch, CURLOPT_VERBOSE, true); // 启用详细输出以进行调试
  610. // 创建临时文件来捕获详细的cURL输出
  611. $verbose = fopen('php://temp', 'w+');
  612. curl_setopt($ch, CURLOPT_STDERR, $verbose);
  613. // 执行请求
  614. $response = curl_exec($ch);
  615. //HTTP状态码
  616. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  617. // 获取详细的cURL调试信息
  618. rewind($verbose);
  619. //CURL调试信息
  620. $verboseLog = stream_get_contents($verbose);
  621. fclose($verbose);
  622. // 分离头部和主体
  623. $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  624. //响应头部
  625. $header = substr($response, 0, $header_size);
  626. //响应主体
  627. $body = substr($response, $header_size);
  628. // 检查CURL错误
  629. $curlError = curl_error($ch);
  630. curl_close($ch);
  631. $responseData = json_decode($body, true);
  632. // 检查API是否返回了错误信息
  633. if (isset($responseData['error'])) {
  634. $errorMessage = isset($responseData['error']['message']) ? $responseData['error']['message'] : 'API请求失败';
  635. return json([
  636. 'code' => 1,
  637. 'msg' => '视频生成请求失败',
  638. 'data' => [
  639. 'error_type' => isset($responseData['error']['type']) ? $responseData['error']['type'] : 'unknown',
  640. 'error_code' => isset($responseData['error']['code']) ? $responseData['error']['code'] : 'unknown',
  641. 'error_message' => $errorMessage
  642. ]
  643. ]);
  644. }
  645. // 检查是否有自定义错误格式
  646. if (isset($responseData['code']) && $responseData['code'] === 'fail_to_fetch_task' && isset($responseData['message'])) {
  647. return json([
  648. 'code' => 1,
  649. 'msg' => '视频生成请求失败',
  650. 'data' => [
  651. 'error_code' => $responseData['code'],
  652. 'error_message' => $responseData['message']
  653. ]
  654. ]);
  655. }
  656. // 检查是否存在id字段
  657. if (!isset($responseData['id'])) {
  658. return json([
  659. 'code' => 1,
  660. 'msg' => '无法获取视频ID',
  661. 'data' => [
  662. 'response_data' => $responseData,
  663. 'http_code' => $httpCode
  664. ]
  665. ]);
  666. }
  667. // 1. 先检查视频状态
  668. $statusUrl = 'https://chatapi.onechats.ai/v1/videos/' . $responseData['id'];
  669. $statusData = $this->fetchVideoStatus($statusUrl, $apiKey);
  670. // 检查视频状态
  671. if ($statusData['status'] !== 'completed') {
  672. return json([
  673. 'code' => 202,
  674. 'msg' => '视频尚未生成完成',
  675. 'data' => [
  676. 'video_id' => $responseData['id'],
  677. 'status' => $statusData['status'],
  678. 'progress' => $statusData['progress'],
  679. 'created_at' => $statusData['created_at'],
  680. 'message' => '请稍后再试,视频仍在' . ($statusData['status'] === 'queued' ? '排队中' : '处理中')
  681. ]
  682. ]);
  683. }
  684. // 2. 视频生成完成,准备下载
  685. $apiUrl = 'https://chatapi.onechats.ai/v1/videos/' . $responseData['id'] . '/content';
  686. // 获取可选的variant参数
  687. $variant = $this->request->get('variant', '');
  688. if (!empty($variant)) {
  689. $apiUrl .= '?variant=' . urlencode($variant);
  690. }
  691. // 创建保存目录
  692. $saveDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd');
  693. if (!is_dir($saveDir)) {
  694. mkdir($saveDir, 0755, true);
  695. }
  696. // 生成唯一文件名
  697. $filename = $responseData['id'] . '.mp4';
  698. $localPath = DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $filename;
  699. $fullPath = $saveDir . DS . $filename;
  700. // 3. 下载视频
  701. $videoData = $this->downloadVideo($apiUrl, $apiKey);
  702. // 4. 保存视频文件
  703. if (file_put_contents($fullPath, $videoData) === false) {
  704. throw new Exception('视频保存失败');
  705. }
  706. // 确保路径使用正斜杠,并只保存相对路径部分
  707. $localPath = str_replace('\\', '/', $localPath);
  708. // 移除开头的斜杠,确保路径格式为uploads/videos/...
  709. $savePath = ltrim($localPath, '/');
  710. // 返回成功响应
  711. return json([
  712. 'code' => 0,
  713. 'msg' => '视频下载成功',
  714. 'data' => [
  715. 'video_id' => $responseData['id'],
  716. 'web_url' => $savePath
  717. ]
  718. ]);
  719. }
  720. /**
  721. * 学生端视频状态查询接口 - 用于通过video_id查询视频状态
  722. */
  723. public function Getvideo_id(){
  724. // 获取并验证参数
  725. $params = $this->request->param();
  726. $videoId = $params['video_id'] ?? '';
  727. // 验证video_id参数
  728. if (empty($videoId)) {
  729. return json([
  730. 'code' => 1,
  731. 'msg' => '缺少必要参数:video_id',
  732. 'data' => []
  733. ]);
  734. }
  735. $aiGateway = new AIGatewayService();
  736. // $apiUrl = $aiGateway->config['videos']['api_url'];
  737. $apiKey = $aiGateway->config['videos']['api_key'];
  738. $apiUrl = 'https://chatapi.onechats.ai/v1/videos/' . $videoId;
  739. // 先检查本地是否已经有该视频
  740. $localVideoPath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $videoId . '.mp4';
  741. if (file_exists($localVideoPath)) {
  742. // 视频已存在本地,直接返回
  743. $webPath = '/uploads/videos/' . date('Ymd') . '/' . $videoId . '.mp4';
  744. return json([
  745. 'code' => 0,
  746. 'msg' => '视频下载成功',
  747. 'data' => [
  748. 'video_id' => $videoId,
  749. 'web_url' => substr($webPath, 1) // 移除开头的斜杠
  750. ]
  751. ]);
  752. }
  753. // 检查视频状态
  754. $statusData = $this->fetchVideoStatus($apiUrl, $apiKey);
  755. // 检查视频状态
  756. if ($statusData['status'] !== 'completed') {
  757. return json([
  758. 'code' => 202,
  759. 'msg' => '视频尚未生成完成',
  760. 'data' => [
  761. 'video_id' => $videoId,
  762. 'status' => $statusData['status'],
  763. 'progress' => isset($statusData['progress']) ? $statusData['progress'] : 0,
  764. 'created_at' => $statusData['created_at'],
  765. 'message' => '请稍后再试,视频仍在' . ($statusData['status'] === 'queued' ? '排队中' : '处理中')
  766. ]
  767. ]);
  768. }
  769. // 视频生成完成,下载视频
  770. $downloadUrl = 'https://chatapi.onechats.ai/v1/videos/' . $videoId . '/content';
  771. // 获取可选的variant参数
  772. $variant = $this->request->get('variant', '');
  773. if (!empty($variant)) {
  774. $downloadUrl .= '?variant=' . urlencode($variant);
  775. }
  776. // 创建保存目录
  777. $saveDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd');
  778. if (!is_dir($saveDir)) {
  779. mkdir($saveDir, 0755, true);
  780. }
  781. // 生成唯一文件名
  782. $filename = $videoId . '.mp4';
  783. $localPath = DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $filename;
  784. $fullPath = $saveDir . DS . $filename;
  785. // 下载视频
  786. $videoData = $this->downloadVideo($downloadUrl, $apiKey);
  787. // 保存视频文件
  788. if (file_put_contents($fullPath, $videoData) === false) {
  789. throw new Exception('视频保存失败');
  790. }
  791. // 确保路径使用正斜杠,并只保存相对路径部分
  792. $localPath = str_replace(DIRECTORY_SEPARATOR, '/', $localPath);
  793. // 移除开头的斜杠,确保路径格式为uploads/videos/...
  794. $savePath = ltrim($localPath, '/');
  795. // 返回成功响应
  796. return json([
  797. 'code' => 0,
  798. 'msg' => '视频下载成功',
  799. 'data' => [
  800. 'video_id' => $videoId,
  801. 'web_url' => $savePath
  802. ]
  803. ]);
  804. }
  805. //获取视频列表
  806. public function Getvideolist(){
  807. if (!$this->request->isGet()) {
  808. $this->error('请求方式错误');
  809. }
  810. $params = $this->request->param();
  811. $search = input('search', '');
  812. $page = isset($params['page']) ? (int)$params['page'] : 1;
  813. $limit = isset($params['limit']) ? (int)$params['limit'] : 50;
  814. $where = [];
  815. if (!empty($search)) {
  816. $where['prompt'] = ['like', '%' . $search . '%'];
  817. }
  818. $list = Db::name('video')->where('mod_rq', null)
  819. ->where($where)
  820. ->order('id desc')
  821. ->limit(($page - 1) * $limit, $limit)
  822. ->select();
  823. $total = Db::name('video')->where('mod_rq', null)
  824. ->where($where)
  825. ->count();
  826. $res['code'] = 0;
  827. $res['msg'] = '成功';
  828. $res['count'] = $total;
  829. $res['data'] = $list;
  830. return json($res);
  831. }
  832. /**
  833. * 文生视频/图生视频接口
  834. * @return \think\response\Json
  835. * @throws \Exception
  836. */
  837. //文生视频
  838. public function video(){
  839. $aiGateway = new AIGatewayService();
  840. $apiUrl = $aiGateway->config['videos']['api_url'];
  841. $apiKey = $aiGateway->config['videos']['api_key'];
  842. $params = $this->request->param();
  843. $postData = [
  844. 'prompt' => $params['prompt'],
  845. 'model' => $params['model'],
  846. 'seconds' => $params['seconds'],
  847. 'size' => $params['size'],
  848. ];
  849. // 初始化CURL
  850. $ch = curl_init();
  851. curl_setopt($ch, CURLOPT_URL, $apiUrl);
  852. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  853. curl_setopt($ch, CURLOPT_POST, true);
  854. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  855. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  856. 'Authorization: Bearer ' . $apiKey
  857. ]);
  858. curl_setopt($ch, CURLOPT_TIMEOUT, 300);
  859. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  860. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  861. curl_setopt($ch, CURLOPT_HEADER, true); // 获取响应头
  862. curl_setopt($ch, CURLOPT_VERBOSE, true); // 启用详细输出以进行调试
  863. // 创建临时文件来捕获详细的cURL输出
  864. $verbose = fopen('php://temp', 'w+');
  865. curl_setopt($ch, CURLOPT_STDERR, $verbose);
  866. // 执行请求
  867. $response = curl_exec($ch);
  868. //HTTP状态码
  869. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  870. // 获取详细的cURL调试信息
  871. rewind($verbose);
  872. //CURL调试信息
  873. $verboseLog = stream_get_contents($verbose);
  874. fclose($verbose);
  875. // 分离头部和主体
  876. $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  877. //响应头部
  878. $header = substr($response, 0, $header_size);
  879. //响应主体
  880. $body = substr($response, $header_size);
  881. // 检查CURL错误
  882. $curlError = curl_error($ch);
  883. curl_close($ch);
  884. $responseData = json_decode($body, true);
  885. echo "<pre>";
  886. print_r($responseData);
  887. echo "<pre>";die;
  888. // 检查API是否返回了错误信息
  889. if (isset($responseData['error'])) {
  890. $errorMessage = isset($responseData['error']['message']) ? $responseData['error']['message'] : 'API请求失败';
  891. return json([
  892. 'code' => 1,
  893. 'msg' => '视频生成请求失败',
  894. 'data' => [
  895. 'error_type' => isset($responseData['error']['type']) ? $responseData['error']['type'] : 'unknown',
  896. 'error_code' => isset($responseData['error']['code']) ? $responseData['error']['code'] : 'unknown',
  897. 'error_message' => $errorMessage
  898. ]
  899. ]);
  900. }
  901. // 检查是否有自定义错误格式
  902. if (isset($responseData['code']) && $responseData['code'] === 'fail_to_fetch_task' && isset($responseData['message'])) {
  903. return json([
  904. 'code' => 1,
  905. 'msg' => '视频生成请求失败',
  906. 'data' => [
  907. 'error_code' => $responseData['code'],
  908. 'error_message' => $responseData['message']
  909. ]
  910. ]);
  911. }
  912. // 检查是否存在id字段
  913. if (!isset($responseData['id'])) {
  914. return json([
  915. 'code' => 1,
  916. 'msg' => '无法获取视频ID',
  917. 'data' => [
  918. 'response_data' => $responseData,
  919. 'http_code' => $httpCode
  920. ]
  921. ]);
  922. }
  923. $videoData = [
  924. 'video_id' => $responseData['id'],
  925. 'prompt' => $postData['prompt'],
  926. 'model' => $postData['model'],
  927. 'seconds' => $postData['seconds'],
  928. 'size' => $postData['size'],
  929. 'sys_rq' => date("Y-m-d H:i:s")
  930. ];
  931. echo "<pre>";
  932. print_r($videoData);
  933. echo "<pre>";die;
  934. // 尝试插入数据
  935. try {
  936. $res = Db::name('video')->insert($videoData);
  937. return json([
  938. 'code' => 0,
  939. 'msg' => '视频正在生成中',
  940. 'data ' => [
  941. 'video_id' => $responseData['id'],
  942. 'insert_result' => $res
  943. ]
  944. ]);
  945. } catch (Exception $e) {
  946. return json([
  947. 'code' => 1,
  948. 'msg' => '数据库操作失败',
  949. 'data' => [
  950. 'error_message' => $e->getMessage()
  951. ]
  952. ]);
  953. }
  954. }
  955. /**
  956. * 获取视频内容
  957. * 下载已完成的视频内容
  958. */
  959. public function videoContent(){
  960. // 从请求参数获取video_id,如果没有则使用默认值
  961. $video_id = input('get.video_id');
  962. $apiKey = '';
  963. // 1. 先检查视频状态
  964. $statusUrl = 'https://chatapi.onechats.ai/v1/videos/' . $video_id;
  965. $statusData = $this->fetchVideoStatus($statusUrl, $apiKey);
  966. // 检查视频状态
  967. if ($statusData['status'] !== 'completed') {
  968. return json([
  969. 'code' => 202,
  970. 'msg' => '视频尚未生成完成',
  971. 'data' => [
  972. 'video_id' => $video_id,
  973. 'status' => $statusData['status'],
  974. 'progress' => $statusData['progress'],
  975. 'created_at' => $statusData['created_at'],
  976. 'message' => '请稍后再试,视频仍在' . ($statusData['status'] === 'queued' ? '排队中' : '处理中')
  977. ]
  978. ]);
  979. }
  980. // 2. 视频生成完成,准备下载
  981. $apiUrl = 'https://chatapi.onechats.ai/v1/videos/' . $video_id . '/content';
  982. // 获取可选的variant参数
  983. $variant = $this->request->get('variant', '');
  984. if (!empty($variant)) {
  985. $apiUrl .= '?variant=' . urlencode($variant);
  986. }
  987. // 创建保存目录
  988. $saveDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd');
  989. if (!is_dir($saveDir)) {
  990. mkdir($saveDir, 0755, true);
  991. }
  992. // 生成唯一文件名
  993. $filename = $video_id . '.mp4';
  994. $localPath = DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $filename;
  995. $fullPath = $saveDir . DS . $filename;
  996. // 3. 下载视频
  997. $videoData = $this->downloadVideo($apiUrl, $apiKey);
  998. // 4. 保存视频文件
  999. if (file_put_contents($fullPath, $videoData) === false) {
  1000. throw new Exception('视频保存失败');
  1001. }
  1002. // 确保路径使用正斜杠,并只保存相对路径部分
  1003. $localPath = str_replace('\\', '/', $localPath);
  1004. // 移除开头的斜杠,确保路径格式为uploads/videos/...
  1005. $savePath = ltrim($localPath, '/');
  1006. // 将正确格式的文件路径存入数据库
  1007. Db::name('video')->where('video_id', $video_id)->update([
  1008. 'web_url' => $savePath
  1009. ]);
  1010. // 返回成功响应
  1011. return json([
  1012. 'code' => 0,
  1013. 'msg' => '视频下载成功',
  1014. 'data' => [
  1015. 'video_id' => $video_id,
  1016. 'local_path' => $localPath,
  1017. 'web_url' => $savePath,
  1018. 'file_size' => filesize($fullPath)
  1019. ]
  1020. ]);
  1021. }
  1022. /**
  1023. * 获取视频状态
  1024. */
  1025. private function fetchVideoStatus($url, $apiKey) {
  1026. $ch = curl_init();
  1027. curl_setopt($ch, CURLOPT_URL, $url);
  1028. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1029. curl_setopt($ch, CURLOPT_HTTPGET, true);
  1030. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  1031. 'Authorization: Bearer ' . $apiKey,
  1032. 'Accept: application/json'
  1033. ]);
  1034. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  1035. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  1036. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  1037. $response = curl_exec($ch);
  1038. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  1039. $error = curl_error($ch);
  1040. curl_close($ch);
  1041. if ($error) {
  1042. throw new Exception('获取视频状态失败: ' . $error);
  1043. }
  1044. if ($httpCode < 200 || $httpCode >= 300) {
  1045. throw new Exception('获取视频状态失败,HTTP状态码: ' . $httpCode);
  1046. }
  1047. $data = json_decode($response, true);
  1048. if (!is_array($data)) {
  1049. throw new Exception('视频状态数据格式错误');
  1050. }
  1051. return $data;
  1052. }
  1053. /**
  1054. * 下载视频文件
  1055. */
  1056. private function downloadVideo($url, $apiKey) {
  1057. $ch = curl_init();
  1058. curl_setopt($ch, CURLOPT_URL, $url);
  1059. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1060. curl_setopt($ch, CURLOPT_HTTPGET, true);
  1061. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  1062. 'Authorization: Bearer ' . $apiKey
  1063. ]);
  1064. curl_setopt($ch, CURLOPT_TIMEOUT, 300);
  1065. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  1066. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  1067. $response = curl_exec($ch);
  1068. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  1069. $error = curl_error($ch);
  1070. curl_close($ch);
  1071. if ($error) {
  1072. throw new Exception('视频下载失败: ' . $error);
  1073. }
  1074. if ($httpCode < 200 || $httpCode >= 300) {
  1075. throw new Exception('视频下载失败,HTTP状态码: ' . $httpCode);
  1076. }
  1077. return $response;
  1078. }
  1079. private function sendPostRequest($url, $data, $apiKey)
  1080. {
  1081. $ch = curl_init();
  1082. curl_setopt($ch, CURLOPT_URL, $url);
  1083. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1084. curl_setopt($ch, CURLOPT_POST, true);
  1085. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  1086. 'Authorization: Bearer ' . $apiKey,
  1087. 'Accept: application/json',
  1088. 'Content-Type: application/json'
  1089. ]);
  1090. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  1091. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  1092. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  1093. curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 延长超时时间
  1094. $response = curl_exec($ch);
  1095. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  1096. $error = curl_error($ch);
  1097. curl_close($ch);
  1098. return [
  1099. 'response' => $response,
  1100. 'http_code' => $httpCode,
  1101. 'error' => $error
  1102. ];
  1103. }
  1104. /**
  1105. * 查询队列列表
  1106. * 统计文件对应的队列情况
  1107. */
  1108. public function get_queue_logs()
  1109. {
  1110. $params = $this->request->param('old_image_file', '');
  1111. $queue_logs = Db::name('queue_logs')
  1112. ->where('old_image_file', $params)
  1113. ->order('id desc')
  1114. ->select();
  1115. $result = []; //初始化变量,避免未定义错误
  1116. foreach ($queue_logs as &$log) {
  1117. $taskId = $log['id'];
  1118. $statusCount = Db::name('image_task_log')
  1119. ->field('status, COUNT(*) as count')
  1120. ->where('task_id', $taskId)
  1121. ->where('mod_rq', null)
  1122. ->group('status')
  1123. ->select();
  1124. $log['已完成数量'] = 0;
  1125. $log['处理中数量'] = 0;
  1126. $log['排队中的数量'] = 0;
  1127. $log['失败数量'] = 0;
  1128. foreach ($statusCount as $item) {
  1129. switch ($item['status']) {
  1130. case 0:
  1131. $log['排队中的数量'] = $item['count'];
  1132. break;
  1133. case 1:
  1134. $log['处理中数量'] = $item['count'];
  1135. break;
  1136. case 2:
  1137. $log['已完成数量'] = $item['count'];
  1138. break;
  1139. case -1:
  1140. $log['失败数量'] = $item['count'];
  1141. break;
  1142. }
  1143. }
  1144. // if ($log['排队中的数量'] >$log['已完成数量']) {
  1145. // $result[] = $log;
  1146. // }
  1147. if ($log['排队中的数量']) {
  1148. $result[] = $log;
  1149. }
  1150. // if ($log['处理中数量'] >= 0) {
  1151. // $result[] = $log;
  1152. // }
  1153. }
  1154. return json([
  1155. 'code' => 0,
  1156. 'msg' => '查询成功',
  1157. 'data' => $result,
  1158. 'count' => count($result)
  1159. ]);
  1160. }
  1161. /**
  1162. * 查询总队列状态(统计当前处理的数据量)
  1163. */
  1164. public function queueStats()
  1165. {
  1166. $statusList = Db::name('image_task_log')
  1167. ->field('status, COUNT(*) as total')
  1168. ->where('mod_rq', null)
  1169. ->where('create_time', '>=', date('Y-m-d 00:00:00'))
  1170. ->group('status')
  1171. ->select();
  1172. $statusCount = [];
  1173. foreach ($statusList as $item) {
  1174. $statusCount[$item['status']] = $item['total'];
  1175. }
  1176. // 总数为所有状态和
  1177. $total = array_sum($statusCount);
  1178. //获取队列当前状态
  1179. $statusText = Db::name('queue_logs')->order('id desc')->value('status');
  1180. return json([
  1181. 'code' => 0,
  1182. 'msg' => '获取成功',
  1183. 'data' => [
  1184. '总任务数' => $total,
  1185. '待处理' => $statusCount[0] ?? 0,
  1186. '处理中' => $statusCount[1] ?? 0,
  1187. '成功' => $statusCount[2] ?? 0,
  1188. '失败' => $statusCount[-1] ?? 0,
  1189. '当前状态' => $statusText
  1190. ]
  1191. ]);
  1192. }
  1193. /**
  1194. * 获取 Redis 连接实例
  1195. * @return \Redis|null Redis 实例或 null(如果连接失败)
  1196. */
  1197. private function getRedisConnection()
  1198. {
  1199. if (!class_exists('\Redis')) {
  1200. return null;
  1201. }
  1202. return getTaskRedis();
  1203. }
  1204. /**
  1205. * 显示当前运行中的队列监听进程
  1206. */
  1207. public function viewQueueStatus()
  1208. {
  1209. $redis = $this->getRedisConnection();
  1210. if (!$redis) {
  1211. return json([
  1212. 'code' => 1,
  1213. 'msg' => 'Redis扩展未安装或未启用',
  1214. 'data' => null
  1215. ]);
  1216. }
  1217. $key = 'queues:imgtotxt';
  1218. // 判断 key 是否存在,避免报错
  1219. if (!$redis->exists($key)) {
  1220. return json([
  1221. 'code' => 0,
  1222. 'msg' => '查询成功,队列为空',
  1223. 'count' => 0,
  1224. 'tasks_preview' => []
  1225. ]);
  1226. }
  1227. $count = $redis->lLen($key);
  1228. $list = $redis->lRange($key, 0, 9);
  1229. // 解码 JSON 内容,确保每一项都有效
  1230. $parsed = array_filter(array_map(function ($item) {
  1231. return json_decode($item, true);
  1232. }, $list), function ($item) {
  1233. return !is_null($item);
  1234. });
  1235. return json([
  1236. 'code' => 0,
  1237. 'msg' => '查询成功',
  1238. 'count' => $count,
  1239. 'tasks_preview' => $parsed
  1240. ]);
  1241. }
  1242. /**
  1243. * 清空队列并删除队列日志记录
  1244. */
  1245. public function stopQueueProcesses()
  1246. {
  1247. Db::name('image_task_log')
  1248. ->where('log', '队列中')
  1249. ->whereOr('status', 1)
  1250. ->where('create_time', '>=', date('Y-m-d 00:00:00'))
  1251. ->update([
  1252. 'status' => "-1",
  1253. 'log' => '清空取消队列',
  1254. 'mod_rq' => date('Y-m-d H:i:s')
  1255. ]);
  1256. Db::name('image_task_log')
  1257. ->whereLike('log', '%处理中%')
  1258. ->where('create_time', '>=', date('Y-m-d 00:00:00'))
  1259. ->update([
  1260. 'status' => "-1",
  1261. 'log' => '清空取消队列',
  1262. 'mod_rq' => date('Y-m-d H:i:s')
  1263. ]);
  1264. $redis = $this->getRedisConnection();
  1265. if (!$redis) {
  1266. return json([
  1267. 'code' => 1,
  1268. 'msg' => 'Redis扩展未安装或未启用',
  1269. 'data' => null
  1270. ]);
  1271. }
  1272. $key_txttoimg = 'queues:txttoimg:reserved';
  1273. $key_txttotxt = 'queues:txttotxt:reserved';
  1274. $key_imgtotxt = 'queues:imgtotxt:reserved';
  1275. $key_imgtoimg = 'queues:imgtoimg:reserved';
  1276. // 清空 Redis 队列
  1277. $redis->del($key_txttoimg);
  1278. $redis->del($key_txttotxt);
  1279. $redis->del($key_imgtotxt);
  1280. $redis->del($key_imgtoimg);
  1281. $count = $redis->lLen($key_txttoimg) + $redis->lLen($key_txttotxt) + $redis->lLen($key_imgtotxt) + $redis->lLen($key_imgtoimg);
  1282. // if ($count === 0) {
  1283. // return json([
  1284. // 'code' => 1,
  1285. // 'msg' => '暂无队列需要停止'
  1286. // ]);
  1287. // }
  1288. return json([
  1289. 'code' => 0,
  1290. 'msg' => '成功停止队列任务'
  1291. ]);
  1292. }
  1293. /**
  1294. * 开启队列任务
  1295. * 暂时用不到、服务器已开启自动开启队列模式
  1296. */
  1297. // public function kaiStats()
  1298. // {
  1299. // // 判断是否已有监听进程在运行
  1300. // $check = shell_exec("ps aux | grep 'queue:listen' | grep -v grep");
  1301. // if ($check) {
  1302. // return json([
  1303. // 'code' => 1,
  1304. // 'msg' => '监听进程已存在,请勿重复启动'
  1305. // ]);
  1306. // }
  1307. // // 启动监听
  1308. // $command = 'nohup php think queue:listen --queue --timeout=300 --sleep=3 --memory=256 > /var/log/job_queue.log 2>&1 &';
  1309. // exec($command, $output, $status);
  1310. // if ($status === 0) {
  1311. // return json([
  1312. // 'code' => 0,
  1313. // 'msg' => '队列监听已启动'
  1314. // ]);
  1315. // } else {
  1316. // return json([
  1317. // 'code' => 1,
  1318. // 'msg' => '队列启动失败',
  1319. // 'output' => $output
  1320. // ]);
  1321. // }
  1322. // }
  1323. /**
  1324. * 新增模版
  1325. * (暂时无用)
  1326. */
  1327. public function Add_Product_Template(){
  1328. try {
  1329. $params = $this->request->param();
  1330. $chinese_description = $params['chinese_description'] ?? '';
  1331. $template_image_url = $params['template_image_url'] ?? '';
  1332. $template_name = $params['template_name'] ?? '';
  1333. $size = $params['size'] ?? '';
  1334. $style = $params['style'] ?? '';
  1335. $type = $params['type'] ?? '';
  1336. $user_id = $params['user_id'] ?? '';
  1337. $seconds = $params['seconds'] ?? '';
  1338. $video_id = $params['video_id'] ?? '';
  1339. if (empty($template_name)) {
  1340. return json(['code' => 1, 'msg' => '模板名称不能为空']);
  1341. }
  1342. $data = [
  1343. 'toexamine' => "未审核",
  1344. 'chinese_description' => $chinese_description,
  1345. 'template_image_url' => $template_image_url,
  1346. 'template_name' => $template_name,
  1347. 'type' => $type,
  1348. 'style' => $style,
  1349. 'seconds' => $seconds,
  1350. 'size' => $size,
  1351. 'video_id' => $video_id,
  1352. 'user_id' => $user_id,
  1353. 'sys_rq' => date('Y-m-d'),
  1354. 'create_time' => date('Y-m-d H:i:s')
  1355. ];
  1356. $result = Db::name('product_template')->insert($data);
  1357. if ($result) {
  1358. return json(['code' => 0, 'msg' => '模板保存成功']);
  1359. } else {
  1360. return json(['code' => 1, 'msg' => '模板保存失败: 数据库操作未影响任何行']);
  1361. }
  1362. } catch (\Exception $e) {
  1363. Log::record('模板保存异常: ' . $e->getMessage(), 'error');
  1364. Log::record('异常堆栈: ' . $e->getTraceAsString(), 'error');
  1365. return json(['code' => 1, 'msg' => '模板保存失败: ' . $e->getMessage()]);
  1366. }
  1367. }
  1368. /**
  1369. * 查询模版
  1370. */
  1371. public function product_template()
  1372. {
  1373. $params = $this->request->param();
  1374. // 构建查询条件
  1375. $where = [];
  1376. if (!empty($params['search'])) {
  1377. $where['chinese_description|template_name|style'] = ['like', '%' . $params['search'] . '%'];
  1378. }
  1379. if (!empty($params['sys_id'])) {
  1380. $where['sys_id'] = ['like', '%' . $params['sys_id'] . '%'];
  1381. $products = Db::name('product_template')->order('id desc')->where($where)
  1382. ->whereNull('mod_rq')
  1383. ->select();
  1384. }else{
  1385. $products = Db::name('product_template')->order('id desc')->where($where)
  1386. ->where('release','1')
  1387. ->whereNull('mod_rq')
  1388. ->select();
  1389. }
  1390. return json([
  1391. 'code' => 0,
  1392. 'msg' => '请求成功',
  1393. 'data' => $products
  1394. ]);
  1395. }
  1396. /**
  1397. *获取服务器URL地址和端口 IP地址:端口
  1398. * 用于获取图片路径拼接时
  1399. **/
  1400. public function GetHttpUrl(){
  1401. $data = Db::name('http_url')->find();
  1402. $fullUrl = "http://" . $data['baseUrl'] . ":" . $data['port'];
  1403. $res = [
  1404. 'code' => 0,
  1405. 'msg' => '成功',
  1406. 'data' => [
  1407. 'id' => $data['id'],
  1408. 'full_url' => $fullUrl,
  1409. 'baseUrl' => $data['baseUrl'],
  1410. 'port' => $data['port']
  1411. ]
  1412. ];
  1413. return json($res);
  1414. }
  1415. /**
  1416. * 获取 AI 模型配置
  1417. * status 1 = 启用 0 = 禁用(同一模型内的优先级,数值越小越优先)
  1418. * model_type 支持多能力逗号间隔(如 文生图,图生图),传参精确匹配某一能力
  1419. * 可选参数:manage=1 时返回全部(含禁用),用于管理端
  1420. */
  1421. public function GetAIModel(){
  1422. $params = $this->request->param();
  1423. $query = Db::name('ai_model');
  1424. if (empty($params['manage'])) {
  1425. $query->where('status', '1');
  1426. }
  1427. if (!empty($params['model_type'])) {
  1428. $query->whereRaw('FIND_IN_SET(:mt, model_type) > 0', ['mt' => trim($params['model_type'])]);
  1429. }
  1430. if (!empty($params['supplier'])) {
  1431. $query->where('supplier', 'like', '%' . $params['supplier'] . '%');
  1432. }
  1433. if (!empty($params['model_name'])) {
  1434. $query->where('model_name|model_alias', 'like', '%' . $params['model_name'] . '%');
  1435. }
  1436. $data = $query->order('sort ASC, id ASC')->select();
  1437. return json([
  1438. 'code' => 0,
  1439. 'msg' => '成功',
  1440. 'data' => $data
  1441. ]);
  1442. }
  1443. /**
  1444. * 新增 AI 模型配置
  1445. * POST: status, supplier, api_key, api_url, model_group, model_name, model_alias, model_type, sort
  1446. * model_type 多能力用逗号间隔,如:文生图,图生图
  1447. */
  1448. public function AddAIModel(){
  1449. $params = $this->request->param();
  1450. $required = ['api_url', 'api_key', 'model_name', 'model_type'];
  1451. foreach ($required as $k) {
  1452. if (empty(trim($params[$k] ?? ''))) {
  1453. return json(['code' => 1, 'msg' => $k . ' 不能为空']);
  1454. }
  1455. }
  1456. $insert = [
  1457. 'status' => isset($params['status']) ? trim($params['status']) : '1',
  1458. 'supplier' => trim($params['supplier'] ?? ''),
  1459. 'api_key' => trim($params['api_key']),
  1460. 'api_url' => trim($params['api_url']),
  1461. 'model_group' => trim($params['model_group'] ?? ''),
  1462. 'model_name' => trim($params['model_name']),
  1463. 'model_alias' => trim($params['model_alias'] ?? $params['model_name'] ?? ''),
  1464. 'model_type' => trim($params['model_type']),
  1465. 'sort' => isset($params['sort']) ? intval($params['sort']) : 0,
  1466. ];
  1467. try {
  1468. Db::name('ai_model')->insert($insert);
  1469. return json(['code' => 0, 'msg' => '新增成功']);
  1470. } catch (\Exception $e) {
  1471. return json(['code' => 1, 'msg' => '新增失败: ' . $e->getMessage()]);
  1472. }
  1473. }
  1474. /**
  1475. * 修改 AI 模型配置
  1476. * POST: id(必填), 其余字段同新增
  1477. */
  1478. public function UpdateAIModel(){
  1479. $params = $this->request->param();
  1480. if (empty($params['id'])) {
  1481. return json(['code' => 1, 'msg' => 'id 不能为空']);
  1482. }
  1483. $id = intval($params['id']);
  1484. $exists = Db::name('ai_model')->where('id', $id)->find();
  1485. if (!$exists) {
  1486. return json(['code' => 1, 'msg' => '记录不存在']);
  1487. }
  1488. $update = [];
  1489. $fields = ['status', 'supplier', 'api_key', 'api_url', 'model_group', 'model_name', 'model_alias', 'model_type', 'sort'];
  1490. foreach ($fields as $f) {
  1491. if (array_key_exists($f, $params)) {
  1492. $update[$f] = $f === 'sort' ? intval($params[$f]) : trim($params[$f] ?? '');
  1493. }
  1494. }
  1495. if (empty($update)) {
  1496. return json(['code' => 1, 'msg' => '无有效修改字段']);
  1497. }
  1498. try {
  1499. Db::name('ai_model')->where('id', $id)->update($update);
  1500. return json(['code' => 0, 'msg' => '修改成功']);
  1501. } catch (\Exception $e) {
  1502. return json(['code' => 1, 'msg' => '修改失败: ' . $e->getMessage()]);
  1503. }
  1504. }
  1505. /**
  1506. * 用于获取所有产品记录
  1507. **/
  1508. public function GetProductList(){
  1509. $params = $this->request->param();
  1510. // 构建查询条件
  1511. $where = [];
  1512. if (!empty($params['search'])) {
  1513. $where['prompt|model'] = ['like', '%' . $params['search'] . '%'];
  1514. }
  1515. if (!empty($params['sys_id'])) {
  1516. $where['sys_id'] = ['like', '%' . $params['sys_id'] . '%'];
  1517. }
  1518. $data = Db::name('product_image_generate')->where($where)->order('id desc')->limit(0,10)->select();
  1519. $prompt = Db::name('product_image_generate')->field('prompt')->where($where)->group('prompt')->order('id desc')->select();
  1520. return json([
  1521. 'code' => 0,
  1522. 'msg' => '成功',
  1523. 'prompt' => $prompt,
  1524. 'data' => $data
  1525. ]);
  1526. }
  1527. }