WorkOrder.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  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. {
  16. protected $noNeedLogin = ['*'];
  17. protected $noNeedRight = ['*'];
  18. public function indexx()
  19. {
  20. echo 123;
  21. }
  22. /**
  23. * 出图接口
  24. * 此方法处理图像转换为文本的请求,将图像信息存入队列以供后续处理。
  25. */
  26. public function imageToText()
  27. {
  28. $params = $this->request->param();
  29. $service = new ImageService();
  30. $service->handleImage($params);
  31. $this->success('任务成功提交至队列');
  32. }
  33. //扩写文本内容提示词
  34. public function GetTxtToTxt(){
  35. // 确保所有必要的变量都已初始化
  36. $params = $this->request->param();
  37. $prompt = $params['prompt'];
  38. $ai = new AIGatewayService();
  39. $gptRes = $ai->txtGptApi($prompt,'gemini-2.0-flash');
  40. echo "<pre>";
  41. print_r($gptRes);
  42. echo "<pre>";
  43. }
  44. //获取URL地址与端口
  45. public function GetHttpUrl(){
  46. $data = Db::name('http_url')->find();
  47. // 拼接完整的HTTP URL
  48. $fullUrl = "http://" . $data['baseUrl'] . ":" . $data['port'];
  49. $res = [
  50. 'code' => 0,
  51. 'msg' => '成功',
  52. 'data' => [
  53. 'full_url' => $fullUrl,
  54. 'id' => $data['id'],
  55. 'baseUrl' => $data['baseUrl'],
  56. 'port' => $data['port']
  57. ]
  58. ];
  59. return json($res);
  60. }
  61. public function Getvideolist(){
  62. if (!$this->request->isGet()) {
  63. $this->error('请求方式错误');
  64. }
  65. $params = $this->request->param();
  66. $search = input('search', '');
  67. $page = isset($params['page']) ? (int)$params['page'] : 1;
  68. $limit = isset($params['limit']) ? (int)$params['limit'] : 50;
  69. $where = [];
  70. if (!empty($search)) {
  71. $where['prompt'] = ['like', '%' . $search . '%'];
  72. }
  73. $list = Db::name('video')->where('mod_rq', null)
  74. ->where($where)
  75. ->order('id desc')
  76. ->limit(($page - 1) * $limit, $limit)
  77. ->select();
  78. $total = Db::name('video')->where('mod_rq', null)
  79. ->where($where)
  80. ->count();
  81. $res['code'] = 0;
  82. $res['msg'] = '成功';
  83. $res['count'] = $total;
  84. $res['data'] = $list;
  85. return json($res);
  86. }
  87. //video_691c078dbb648190a17625bbef815ce50cbc1621ce1702d7
  88. public function video()
  89. {
  90. $params = $this->request->param();
  91. $apiUrl = 'https://chatapi.onechats.ai/v1/videos';
  92. $apiKey = 'sk-sWW1GFlnjbrDRb1DkMEzePIxgdvLK6cZt0Qg93yDMVP2z1yN';
  93. $postData = [
  94. 'prompt' => $params['prompt'],
  95. 'model' => $params['model'],
  96. 'seconds' => $params['seconds'],
  97. 'size' => $params['size'],
  98. ];
  99. // 初始化CURL
  100. $ch = curl_init();
  101. curl_setopt($ch, CURLOPT_URL, $apiUrl);
  102. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  103. curl_setopt($ch, CURLOPT_POST, true);
  104. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  105. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  106. 'Authorization: Bearer ' . $apiKey
  107. ]);
  108. curl_setopt($ch, CURLOPT_TIMEOUT, 300);
  109. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  110. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  111. curl_setopt($ch, CURLOPT_HEADER, true); // 获取响应头
  112. curl_setopt($ch, CURLOPT_VERBOSE, true); // 启用详细输出以进行调试
  113. // 创建临时文件来捕获详细的cURL输出
  114. $verbose = fopen('php://temp', 'w+');
  115. curl_setopt($ch, CURLOPT_STDERR, $verbose);
  116. // 执行请求
  117. $response = curl_exec($ch);
  118. //HTTP状态码
  119. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  120. // 获取详细的cURL调试信息
  121. rewind($verbose);
  122. //CURL调试信息
  123. $verboseLog = stream_get_contents($verbose);
  124. fclose($verbose);
  125. // 分离头部和主体
  126. $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  127. //响应头部
  128. $header = substr($response, 0, $header_size);
  129. //响应主体
  130. $body = substr($response, $header_size);
  131. // 检查CURL错误
  132. $curlError = curl_error($ch);
  133. curl_close($ch);
  134. $responseData = json_decode($body, true);
  135. // 检查API是否返回了错误信息
  136. if (isset($responseData['error'])) {
  137. $errorMessage = isset($responseData['error']['message']) ? $responseData['error']['message'] : 'API请求失败';
  138. return json([
  139. 'code' => 1,
  140. 'msg' => '视频生成请求失败',
  141. 'data' => [
  142. 'error_type' => isset($responseData['error']['type']) ? $responseData['error']['type'] : 'unknown',
  143. 'error_code' => isset($responseData['error']['code']) ? $responseData['error']['code'] : 'unknown',
  144. 'error_message' => $errorMessage
  145. ]
  146. ]);
  147. }
  148. // 检查是否有自定义错误格式
  149. if (isset($responseData['code']) && $responseData['code'] === 'fail_to_fetch_task' && isset($responseData['message'])) {
  150. return json([
  151. 'code' => 1,
  152. 'msg' => '视频生成请求失败',
  153. 'data' => [
  154. 'error_code' => $responseData['code'],
  155. 'error_message' => $responseData['message']
  156. ]
  157. ]);
  158. }
  159. // 检查是否存在id字段
  160. if (!isset($responseData['id'])) {
  161. return json([
  162. 'code' => 1,
  163. 'msg' => '无法获取视频ID',
  164. 'data' => [
  165. 'response_data' => $responseData,
  166. 'http_code' => $httpCode
  167. ]
  168. ]);
  169. }
  170. $videoData = [
  171. 'video_id' => $responseData['id'],
  172. 'prompt' => $postData['prompt'],
  173. 'model' => $postData['model'],
  174. 'seconds' => $postData['seconds'],
  175. 'size' => $postData['size'],
  176. 'sys_rq' => date("Y-m-d H:i:s")
  177. ];
  178. // 尝试插入数据
  179. try {
  180. $res = Db::name('video')->insert($videoData);
  181. return json([
  182. 'code' => 0,
  183. 'msg' => '视频正在生成中',
  184. 'data ' => [
  185. 'video_id' => $responseData['id'],
  186. 'insert_result' => $res
  187. ]
  188. ]);
  189. } catch (Exception $e) {
  190. return json([
  191. 'code' => 1,
  192. 'msg' => '数据库操作失败',
  193. 'data' => [
  194. 'error_message' => $e->getMessage()
  195. ]
  196. ]);
  197. }
  198. }
  199. /**
  200. * 获取视频内容
  201. * 下载已完成的视频内容
  202. */
  203. public function videoContent(){
  204. // 从请求参数获取video_id,如果没有则使用默认值
  205. $video_id = input('get.video_id');
  206. $apiKey = 'sk-sWW1GFlnjbrDRb1DkMEzePIxgdvLK6cZt0Qg93yDMVP2z1yN';
  207. // 1. 先检查视频状态
  208. $statusUrl = 'https://chatapi.onechats.ai/v1/videos/' . $video_id;
  209. $statusData = $this->fetchVideoStatus($statusUrl, $apiKey);
  210. // 检查视频状态
  211. if ($statusData['status'] !== 'completed') {
  212. return json([
  213. 'code' => 202,
  214. 'msg' => '视频尚未生成完成',
  215. 'data' => [
  216. 'video_id' => $video_id,
  217. 'status' => $statusData['status'],
  218. 'progress' => $statusData['progress'],
  219. 'created_at' => $statusData['created_at'],
  220. 'message' => '请稍后再试,视频仍在' . ($statusData['status'] === 'queued' ? '排队中' : '处理中')
  221. ]
  222. ]);
  223. }
  224. // 2. 视频生成完成,准备下载
  225. $apiUrl = 'https://chatapi.onechats.ai/v1/videos/' . $video_id . '/content';
  226. // 获取可选的variant参数
  227. $variant = input('get.variant', '');
  228. if (!empty($variant)) {
  229. $apiUrl .= '?variant=' . urlencode($variant);
  230. }
  231. // 创建保存目录
  232. $saveDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd');
  233. if (!is_dir($saveDir)) {
  234. mkdir($saveDir, 0755, true);
  235. }
  236. // 生成唯一文件名
  237. $filename = $video_id . '.mp4';
  238. $localPath = DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $filename;
  239. $fullPath = $saveDir . DS . $filename;
  240. // 3. 下载视频
  241. $videoData = $this->downloadVideo($apiUrl, $apiKey);
  242. // 4. 保存视频文件
  243. if (file_put_contents($fullPath, $videoData) === false) {
  244. throw new Exception('视频保存失败');
  245. }
  246. // 确保路径使用正斜杠,并只保存相对路径部分
  247. $localPath = str_replace('\\', '/', $localPath);
  248. // 移除开头的斜杠,确保路径格式为uploads/videos/...
  249. $savePath = ltrim($localPath, '/');
  250. // 将正确格式的文件路径存入数据库
  251. Db::name('video')->where('video_id', $video_id)->update([
  252. 'web_url' => $savePath
  253. ]);
  254. // 返回成功响应
  255. return json([
  256. 'code' => 0,
  257. 'msg' => '视频下载成功',
  258. 'data' => [
  259. 'video_id' => $video_id,
  260. 'local_path' => $localPath,
  261. 'web_url' => $savePath,
  262. 'file_size' => filesize($fullPath)
  263. ]
  264. ]);
  265. }
  266. /**
  267. * 获取视频状态
  268. */
  269. private function fetchVideoStatus($url, $apiKey) {
  270. $ch = curl_init();
  271. curl_setopt($ch, CURLOPT_URL, $url);
  272. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  273. curl_setopt($ch, CURLOPT_HTTPGET, true);
  274. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  275. 'Authorization: Bearer ' . $apiKey,
  276. 'Accept: application/json'
  277. ]);
  278. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  279. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  280. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  281. $response = curl_exec($ch);
  282. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  283. $error = curl_error($ch);
  284. curl_close($ch);
  285. if ($error) {
  286. throw new Exception('获取视频状态失败: ' . $error);
  287. }
  288. if ($httpCode < 200 || $httpCode >= 300) {
  289. throw new Exception('获取视频状态失败,HTTP状态码: ' . $httpCode);
  290. }
  291. $data = json_decode($response, true);
  292. if (!is_array($data)) {
  293. throw new Exception('视频状态数据格式错误');
  294. }
  295. return $data;
  296. }
  297. /**
  298. * 下载视频文件
  299. */
  300. private function downloadVideo($url, $apiKey) {
  301. $ch = curl_init();
  302. curl_setopt($ch, CURLOPT_URL, $url);
  303. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  304. curl_setopt($ch, CURLOPT_HTTPGET, true);
  305. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  306. 'Authorization: Bearer ' . $apiKey
  307. ]);
  308. curl_setopt($ch, CURLOPT_TIMEOUT, 300);
  309. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  310. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  311. $response = curl_exec($ch);
  312. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  313. $error = curl_error($ch);
  314. curl_close($ch);
  315. if ($error) {
  316. throw new Exception('视频下载失败: ' . $error);
  317. }
  318. if ($httpCode < 200 || $httpCode >= 300) {
  319. throw new Exception('视频下载失败,HTTP状态码: ' . $httpCode);
  320. }
  321. return $response;
  322. }
  323. public function textToImage()
  324. {
  325. $outputDirRaw = 'uploads/operate/ai/Preview/undefined_BRdP4/3';
  326. $img_name = '42131321';
  327. $rootPath = str_replace('\\', '/', ROOT_PATH);
  328. $outputDir = rtrim($rootPath . 'public/' . $outputDirRaw, '/') . '/';
  329. $dateDir = date('Y-m-d') . '/';
  330. $fullBaseDir = $outputDir . $dateDir;
  331. // 确保目录存在
  332. if (!is_dir($fullBaseDir . '2048x2048/')) {
  333. mkdir($fullBaseDir . '2048x2048/', 0755, true);
  334. }
  335. // // API配置
  336. // $config = [
  337. // 'api_url' => 'https://chatapi.onechats.ai/mj/submit/imagine',
  338. // 'fetch_url' => 'https://chatapi.onechats.ai/mj/task/',
  339. // 'api_key' => 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK',
  340. // 'default_prompt' => '恐怖的树状怪物,拥有尖牙利爪和血红眼睛,在蓝色背景下显得阴森可怕,风格为黑暗奇幻。'
  341. // ];
  342. //
  343. // // 1. 准备请求数据
  344. // $prompt = $config['default_prompt'];
  345. // $postData = [
  346. // 'botType' => 'MID_JOURNEY',
  347. // 'prompt' => $prompt,
  348. // 'base64Array' => [],
  349. // 'accountFilter' => [
  350. // 'channelId' => "",
  351. // 'instanceId' => "",
  352. // 'modes' => [],
  353. // 'remark' => "",
  354. // 'remix' => true,
  355. // 'remixAutoConsidered' => true
  356. // ],
  357. // 'notifyHook' => "",
  358. // 'state' => ""
  359. // ];
  360. // // 2. 提交生成请求
  361. // $generateResponse = $this->sendApiRequest($config['api_url'], $postData, $config['api_key']);
  362. // echo "<pre>";
  363. // print_r($generateResponse);
  364. // echo "<pre>";
  365. // $generateData = json_decode($generateResponse, true);
  366. // echo "<pre>";
  367. // print_r($generateData);
  368. // echo "<pre>";
  369. // if (empty($generateData['result'])) {
  370. // throw new Exception('生成失败: '.($generateData['message'] ?? '未知错误'));
  371. // }
  372. //
  373. // die;
  374. // $taskId = "1755229064353588";
  375. $taskId = "1755234114253556";
  376. // $taskId = "1755224966357751";
  377. // 3. 等待图片生成完成
  378. sleep(3);
  379. $imageUrl = $this->getImageSeed($taskId);
  380. echo "<pre>";
  381. print_r($imageUrl);
  382. echo "<pre>";die;
  383. $img_name = mb_substr(preg_replace('/[^\x{4e00}-\x{9fa5}A-Za-z0-9_\- ]/u', '', $img_name), 0, 30);
  384. $filename = $img_name . '.png';
  385. $path512 = $fullBaseDir . '2048x2048/' . $filename;
  386. // 下载并保存图片
  387. // file_get_contents($imageUrl['data']['imageUrl']);
  388. // 下载并保存图片到本地文件夹中
  389. $imageData = file_get_contents($imageUrl['data']['imageUrl']);
  390. $result = file_put_contents($path512, $imageData);
  391. if ($result === false) {
  392. die('保存图片失败,请检查目录权限');
  393. }
  394. // 数据库更新
  395. Db::name('text_to_image')->where('id', '10694')->update([
  396. 'new_image_url' => str_replace($rootPath . 'public/', '', $path512),
  397. 'img_name' => $img_name,
  398. 'model' => 'MID_JOURNEY',
  399. 'status' => trim($img_name) === '' ? 0 : 1,
  400. 'status_name' => "文生图",
  401. 'size' => "2048",
  402. 'quality' => 'standard',
  403. 'style' => 'vivid',
  404. 'error_msg' => '',
  405. 'update_time' => date('Y-m-d H:i:s')
  406. ]);
  407. return "成功";
  408. }
  409. public function getImageSeed($taskId)
  410. {
  411. // 配置参数
  412. $apiUrl = 'https://chatapi.onechats.ai/mj/task/' . $taskId . '/fetch';
  413. $apiKey = 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK';
  414. try {
  415. // 初始化cURL
  416. $ch = curl_init();
  417. // 设置cURL选项
  418. curl_setopt_array($ch, [
  419. CURLOPT_URL => $apiUrl,
  420. CURLOPT_RETURNTRANSFER => true,
  421. CURLOPT_CUSTOMREQUEST => 'GET', // 明确指定GET方法
  422. CURLOPT_HTTPHEADER => [
  423. 'Authorization: Bearer ' . $apiKey,
  424. 'Accept: application/json',
  425. 'Content-Type: application/json'
  426. ],
  427. CURLOPT_SSL_VERIFYPEER => false,
  428. CURLOPT_SSL_VERIFYHOST => false,
  429. CURLOPT_TIMEOUT => 60,
  430. CURLOPT_FAILONERROR => true // 添加失败时返回错误
  431. ]);
  432. // 执行请求
  433. $response = curl_exec($ch);
  434. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  435. // 错误处理
  436. if (curl_errno($ch)) {
  437. throw new Exception('cURL请求失败: ' . curl_error($ch));
  438. }
  439. // 关闭连接
  440. curl_close($ch);
  441. // 验证HTTP状态码
  442. if ($httpCode < 200 || $httpCode >= 300) {
  443. throw new Exception('API返回错误状态码: ' . $httpCode);
  444. }
  445. // 解析JSON响应
  446. $responseData = json_decode($response, true);
  447. if (json_last_error() !== JSON_ERROR_NONE) {
  448. throw new Exception('JSON解析失败: ' . json_last_error_msg());
  449. }
  450. // 返回结构化数据
  451. return [
  452. 'success' => true,
  453. 'http_code' => $httpCode,
  454. 'data' => $responseData
  455. ];
  456. } catch (Exception $e) {
  457. // 确保关闭cURL连接
  458. if (isset($ch) && is_resource($ch)) {
  459. curl_close($ch);
  460. }
  461. return [
  462. 'success' => false,
  463. 'error' => $e->getMessage(),
  464. 'http_code' => $httpCode ?? 0
  465. ];
  466. }
  467. }
  468. private function sendPostRequest($url, $data, $apiKey)
  469. {
  470. $ch = curl_init();
  471. curl_setopt($ch, CURLOPT_URL, $url);
  472. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  473. curl_setopt($ch, CURLOPT_POST, true);
  474. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  475. 'Authorization: Bearer ' . $apiKey,
  476. 'Accept: application/json',
  477. 'Content-Type: application/json'
  478. ]);
  479. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  480. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  481. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  482. curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 延长超时时间
  483. $response = curl_exec($ch);
  484. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  485. $error = curl_error($ch);
  486. curl_close($ch);
  487. return [
  488. 'response' => $response,
  489. 'http_code' => $httpCode,
  490. 'error' => $error
  491. ];
  492. }
  493. /**
  494. * 文本生成图片并保存第一张结果
  495. * @param array $params 请求参数
  496. * @return array 返回结果
  497. */
  498. public function txttowimg()
  499. {
  500. // API配置
  501. $config = [
  502. 'api_url' => 'https://chatapi.onechats.ai/mj/submit/imagine',
  503. 'fetch_url' => 'https://chatapi.onechats.ai/mj/task/',
  504. 'api_key' => 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK',
  505. 'default_prompt' => '一个猫',
  506. 'wait_time' => 3 // 等待生成完成的秒数
  507. ];
  508. try {
  509. // 1. 准备请求数据
  510. $prompt = $config['default_prompt'];
  511. $postData = [
  512. 'botType' => 'MID_JOURNEY',
  513. 'prompt' => $prompt,
  514. 'base64Array' => [],
  515. 'accountFilter' => [
  516. 'channelId' => "",
  517. 'instanceId' => "",
  518. 'modes' => [],
  519. 'remark' => "",
  520. 'remix' => true,
  521. 'remixAutoConsidered' => true
  522. ],
  523. 'notifyHook' => "",
  524. 'state' => ""
  525. ];
  526. // 2. 提交生成请求
  527. $generateResponse = $this->sendApiRequest($config['api_url'], $postData, $config['api_key']);
  528. $generateData = json_decode($generateResponse, true);
  529. if (empty($generateData['result'])) {
  530. throw new Exception('生成失败: '.($generateData['message'] ?? '未知错误'));
  531. }
  532. $taskId = $generateData['result'];
  533. // 3. 等待图片生成完成
  534. sleep($config['wait_time']);
  535. // 4. 获取生成结果
  536. $fetchUrl = $config['fetch_url'].$taskId.'/fetch';
  537. $fetchResponse = $this->sendApiRequest($fetchUrl, [], $config['api_key'], 'GET');
  538. $fetchData = json_decode($fetchResponse, true);
  539. if (empty($fetchData['imageUrl'])) {
  540. throw new Exception('获取图片失败: '.($fetchData['message'] ?? '未知错误'));
  541. }
  542. // 5. 处理返回的图片数组(取第一张)
  543. $imageUrls = is_array($fetchData['imageUrl']) ? $fetchData['imageUrl'] : [$fetchData['imageUrl']];
  544. $firstImageUrl = $imageUrls[0];
  545. // 6. 保存图片到本地
  546. $savePath = $this->saveImage($firstImageUrl);
  547. // 7. 返回结果
  548. return [
  549. 'code' => 200,
  550. 'msg' => '图片生成并保存成功',
  551. 'data' => [
  552. 'local_path' => $savePath,
  553. 'web_url' => request()->domain().$savePath,
  554. 'task_id' => $taskId
  555. ]
  556. ];
  557. } catch (Exception $e) {
  558. // 错误处理
  559. return [
  560. 'code' => 500,
  561. 'msg' => '处理失败: '.$e->getMessage(),
  562. 'data' => null
  563. ];
  564. }
  565. }
  566. /**
  567. * 发送API请求
  568. * @param string $url 请求地址
  569. * @param array $data 请求数据
  570. * @param string $apiKey API密钥
  571. * @param string $method 请求方法
  572. * @return string 响应内容
  573. * @throws Exception
  574. */
  575. private function sendApiRequest($url, $data, $apiKey, $method = 'POST')
  576. {
  577. $ch = curl_init();
  578. curl_setopt_array($ch, [
  579. CURLOPT_URL => $url,
  580. CURLOPT_RETURNTRANSFER => true,
  581. CURLOPT_CUSTOMREQUEST => $method,
  582. CURLOPT_HTTPHEADER => [
  583. 'Authorization: Bearer '.$apiKey,
  584. 'Accept: application/json',
  585. 'Content-Type: application/json'
  586. ],
  587. CURLOPT_POSTFIELDS => $method === 'POST' ? json_encode($data) : null,
  588. CURLOPT_SSL_VERIFYPEER => false,
  589. CURLOPT_SSL_VERIFYHOST => false,
  590. CURLOPT_TIMEOUT => 60,
  591. CURLOPT_FAILONERROR => true
  592. ]);
  593. $response = curl_exec($ch);
  594. $error = curl_error($ch);
  595. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  596. curl_close($ch);
  597. if ($error) {
  598. throw new Exception('API请求失败: '.$error);
  599. }
  600. if ($httpCode < 200 || $httpCode >= 300) {
  601. throw new Exception('API返回错误状态码: '.$httpCode);
  602. }
  603. return $response;
  604. }
  605. /**
  606. * 保存图片到本地
  607. * @param string $imageUrl 图片URL
  608. * @return string 本地保存路径
  609. * @throws Exception
  610. */
  611. private function saveImage($imageUrl)
  612. {
  613. // 1. 创建存储目录
  614. $saveDir = ROOT_PATH.'public'.DS.'uploads'.DS.'midjourney'.DS.date('Ymd');
  615. if (!is_dir($saveDir)) {
  616. mkdir($saveDir, 0755, true);
  617. }
  618. // 2. 生成唯一文件名
  619. $filename = uniqid().'.png';
  620. $localPath = DS.'uploads'.DS.'midjourney'.DS.date('Ymd').DS.$filename;
  621. $fullPath = $saveDir.DS.$filename;
  622. // 3. 下载图片
  623. $ch = curl_init($imageUrl);
  624. curl_setopt_array($ch, [
  625. CURLOPT_RETURNTRANSFER => true,
  626. CURLOPT_FOLLOWLOCATION => true,
  627. CURLOPT_SSL_VERIFYPEER => false,
  628. CURLOPT_CONNECTTIMEOUT => 15
  629. ]);
  630. $imageData = curl_exec($ch);
  631. $error = curl_error($ch);
  632. curl_close($ch);
  633. if (!$imageData) {
  634. throw new Exception('图片下载失败: '.$error);
  635. }
  636. // 4. 验证图片类型
  637. $imageInfo = getimagesizefromstring($imageData);
  638. if (!in_array($imageInfo['mime'] ?? '', ['image/png', 'image/jpeg'])) {
  639. throw new Exception('下载内容不是有效图片');
  640. }
  641. // 5. 保存文件
  642. if (!file_put_contents($fullPath, $imageData)) {
  643. throw new Exception('图片保存失败');
  644. }
  645. return $localPath;
  646. }
  647. /**
  648. * 图生图本地测试
  649. */
  650. public function imgtowimg()
  651. {
  652. $prompt = $this->request->param('prompt', '');
  653. $imgRelPath = 'uploads/operate/ai/Preview/arr/0835006071623.png';
  654. $imgPath = ROOT_PATH . 'public/' . $imgRelPath;
  655. if (!file_exists($imgPath)) {
  656. return json(['code' => 1, 'msg' => '原图不存在:' . $imgRelPath]);
  657. }
  658. $imgData = file_get_contents($imgPath);
  659. $base64Img = 'data:image/png;base64,' . base64_encode($imgData);
  660. $params = [
  661. 'prompt' => $prompt,
  662. 'negative_prompt' => '(deformed, distorted, disfigured:1.3), poorly drawn, bad anatomy',
  663. 'steps' => 20,
  664. 'sampler_name' => 'DPM++ 2M SDE',
  665. 'cfg_scale' => 7,
  666. 'seed' => -1,
  667. 'width' => 1024,
  668. 'height' => 1303,
  669. 'override_settings' => [
  670. 'sd_model_checkpoint' => 'realisticVisionV51_v51VAE-inpainting',
  671. 'sd_vae' => 'vae-ft-mse-840000-ema-pruned',
  672. 'CLIP_stop_at_last_layers' => 2
  673. ],
  674. 'clip_skip' => 2,
  675. 'alwayson_scripts' => [
  676. 'controlnet' => [
  677. 'args' => [[
  678. 'enabled' => true,
  679. 'input_image' => $base64Img,
  680. 'module' => 'inpaint_only+lama',
  681. 'model' => 'control_v11p_sd15_inpaint_fp16 [be8bc0ed]',
  682. 'weight' => 1,
  683. 'resize_mode' => 'Resize and Fill',
  684. 'pixel_perfect' => false,
  685. 'control_mode' => 'ControlNet is more important',
  686. 'starting_control_step' => 0,
  687. 'ending_control_step' => 1
  688. ]]
  689. ]
  690. ]
  691. ];
  692. $apiUrl = "http://20.0.17.188:45001/sdapi/v1/txt2img";
  693. $headers = ['Content-Type: application/json'];
  694. $ch = curl_init();
  695. curl_setopt($ch, CURLOPT_URL, $apiUrl);
  696. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  697. curl_setopt($ch, CURLOPT_POST, true);
  698. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  699. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params, JSON_UNESCAPED_UNICODE));
  700. curl_setopt($ch, CURLOPT_TIMEOUT, 180);
  701. $response = curl_exec($ch);
  702. $error = curl_error($ch);
  703. curl_close($ch);
  704. if ($error) {
  705. return json(['code' => 1, 'msg' => '请求失败:' . $error]);
  706. }
  707. $data = json_decode($response, true);
  708. if (!isset($data['images'][0])) {
  709. return json(['code' => 1, 'msg' => '接口未返回图像数据']);
  710. }
  711. $resultImg = base64_decode($data['images'][0]);
  712. $saveDir = ROOT_PATH . 'public/uploads/img2img/';
  713. if (!is_dir($saveDir)) {
  714. mkdir($saveDir, 0755, true);
  715. }
  716. $originalBaseName = pathinfo($imgRelPath, PATHINFO_FILENAME);
  717. $fileName = $originalBaseName . '-' . time() . '-1024x1248.png';
  718. $savePath = $saveDir . $fileName;
  719. file_put_contents($savePath, $resultImg);
  720. return json([
  721. 'code' => 0,
  722. 'msg' => '图像生成成功',
  723. 'data' => [
  724. 'origin_url' => '/uploads/img2img/' . $fileName
  725. ]
  726. ]);
  727. }
  728. /**
  729. * 后期图像处理-单张图片高清放大处理
  730. */
  731. public function extra_image()
  732. {
  733. // 配置参数
  734. $config = [
  735. 'input_dir' => 'uploads/img2img/',
  736. 'output_dir' => 'uploads/extra_image/',
  737. 'api_url' => 'http://20.0.17.188:45001/sdapi/v1/extra-single-image',
  738. 'timeout' => 120, // 增加超时时间,高清处理可能耗时较长
  739. 'upscale_params' => [
  740. 'resize_mode' => 0,
  741. 'show_extras_results' => true,
  742. 'gfpgan_visibility' => 0, // 人脸修复关闭
  743. 'codeformer_visibility' => 0, // 人脸修复关闭
  744. 'codeformer_weight' => 0,
  745. 'upscaling_resize' => 2.45, // 放大倍数
  746. 'upscaling_crop' => true,
  747. 'upscaler_1' => 'R-ESRGAN 4x+ Anime6B', // 主放大模型
  748. 'upscaler_2' => 'None', // 不使用第二放大器
  749. 'extras_upscaler_2_visibility' => 0,
  750. 'upscale_first' => false,
  751. ]
  752. ];
  753. // 输入文件处理
  754. $imgRelPath = '0835006071623-1757406184-1024x1248.png';
  755. $imgPath = ROOT_PATH . 'public/' . $config['input_dir'] . $imgRelPath;
  756. if (!file_exists($imgPath)) {
  757. return json(['code' => 1, 'msg' => '原图不存在:' . $imgRelPath]);
  758. }
  759. // 读取并编码图片
  760. try {
  761. $imgData = file_get_contents($imgPath);
  762. if ($imgData === false) {
  763. throw new Exception('无法读取图片文件');
  764. }
  765. $base64Img = base64_encode($imgData);
  766. } catch (Exception $e) {
  767. return json(['code' => 1, 'msg' => '图片处理失败:' . $e->getMessage()]);
  768. }
  769. // 准备API请求数据
  770. $postData = array_merge($config['upscale_params'], ['image' => $base64Img]);
  771. $jsonData = json_encode($postData);
  772. if ($jsonData === false) {
  773. return json(['code' => 1, 'msg' => 'JSON编码失败']);
  774. }
  775. // 调用API进行高清放大
  776. $ch = curl_init();
  777. curl_setopt_array($ch, [
  778. CURLOPT_URL => $config['api_url'],
  779. CURLOPT_RETURNTRANSFER => true,
  780. CURLOPT_POST => true,
  781. CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
  782. CURLOPT_POSTFIELDS => $jsonData,
  783. CURLOPT_TIMEOUT => $config['timeout'],
  784. CURLOPT_CONNECTTIMEOUT => 30,
  785. ]);
  786. $response = curl_exec($ch);
  787. $error = curl_error($ch);
  788. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  789. curl_close($ch);
  790. if ($error) {
  791. return json(['code' => 1, 'msg' => 'API请求失败:' . $error]);
  792. }
  793. if ($httpCode !== 200) {
  794. return json(['code' => 1, 'msg' => 'API返回错误状态码:' . $httpCode]);
  795. }
  796. $data = json_decode($response, true);
  797. if (json_last_error() !== JSON_ERROR_NONE) {
  798. return json(['code' => 1, 'msg' => 'API返回数据解析失败']);
  799. }
  800. if (!isset($data['image']) || empty($data['image'])) {
  801. return json(['code' => 1, 'msg' => '接口未返回有效的图像数据']);
  802. }
  803. // 保存处理后的图片
  804. try {
  805. $resultImg = base64_decode($data['image']);
  806. if ($resultImg === false) {
  807. throw new Exception('Base64解码失败');
  808. }
  809. $saveDir = ROOT_PATH . 'public/' . $config['output_dir'];
  810. if (!is_dir($saveDir) && !mkdir($saveDir, 0755, true)) {
  811. throw new Exception('无法创建输出目录');
  812. }
  813. $originalBaseName = pathinfo($imgRelPath, PATHINFO_FILENAME);
  814. $fileName = $originalBaseName . '-hd.png'; // 使用-hd后缀更明确
  815. $savePath = $saveDir . $fileName;
  816. if (file_put_contents($savePath, $resultImg) === false) {
  817. throw new Exception('无法保存处理后的图片');
  818. }
  819. // 返回成功响应
  820. return json([
  821. 'code' => 0,
  822. 'msg' => '图像高清放大处理成功',
  823. 'data' => [
  824. 'url' => '/' . $config['output_dir'] . $fileName,
  825. 'original_size' => filesize($imgPath),
  826. 'processed_size' => filesize($savePath),
  827. 'resolution' => getimagesize($savePath), // 返回新图片的分辨率
  828. ]
  829. ]);
  830. } catch (Exception $e) {
  831. return json(['code' => 1, 'msg' => '保存结果失败:' . $e->getMessage()]);
  832. }
  833. }
  834. /**
  835. * 获取 SD 模型列表
  836. * 接口地址: /sdapi/v1/sd-models
  837. */
  838. public function sd_models() {
  839. // $url = "http://20.0.17.188:45001/sdapi/v1/sd-models";
  840. // // 初始化 cURL
  841. // $ch = curl_init();
  842. // // 设置请求参数
  843. // curl_setopt($ch, CURLOPT_URL, $url);
  844. // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  845. // curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  846. // curl_setopt($ch, CURLOPT_HTTPHEADER, [
  847. // 'Content-Type: application/json',
  848. // 'Accept: application/json',
  849. // ]);
  850. // // 发送请求
  851. // $response = curl_exec($ch);
  852. // // 错误处理
  853. // if (curl_errno($ch)) {
  854. // curl_close($ch);
  855. // return json([
  856. // 'code' => 1,
  857. // 'msg' => '请求失败: ' . curl_error($ch),
  858. // 'data' => [],
  859. // 'count' => 0
  860. // ]);
  861. // }
  862. // curl_close($ch);
  863. // // 解析 JSON 响应
  864. // $result = json_decode($response, true);
  865. // // 判断返回数据是否有效
  866. // if (!is_array($result)) {
  867. // return json([
  868. // 'code' => 1,
  869. // 'msg' => '数据解析失败',
  870. // 'data' => [],
  871. // 'count' => 0
  872. // ]);
  873. // }
  874. // 正常返回
  875. return json([
  876. 'code' => 0,
  877. 'msg' => '查询成功',
  878. 'data' => '',
  879. 'count' => 2,
  880. ]);
  881. }
  882. /**
  883. * 查询队列列表
  884. * 统计文件对应的队列情况
  885. */
  886. public function get_queue_logs()
  887. {
  888. $params = $this->request->param('old_image_file', '');
  889. $queue_logs = Db::name('queue_logs')
  890. ->where('old_image_file', $params)
  891. ->order('id desc')
  892. ->select();
  893. $result = []; //初始化变量,避免未定义错误
  894. foreach ($queue_logs as &$log) {
  895. $taskId = $log['id'];
  896. $statusCount = Db::name('image_task_log')
  897. ->field('status, COUNT(*) as count')
  898. ->where('task_id', $taskId)
  899. ->where('mod_rq', null)
  900. ->group('status')
  901. ->select();
  902. $log['已完成数量'] = 0;
  903. $log['处理中数量'] = 0;
  904. $log['排队中的数量'] = 0;
  905. $log['失败数量'] = 0;
  906. foreach ($statusCount as $item) {
  907. switch ($item['status']) {
  908. case 0:
  909. $log['排队中的数量'] = $item['count'];
  910. break;
  911. case 1:
  912. $log['处理中数量'] = $item['count'];
  913. break;
  914. case 2:
  915. $log['已完成数量'] = $item['count'];
  916. break;
  917. case -1:
  918. $log['失败数量'] = $item['count'];
  919. break;
  920. }
  921. }
  922. // if ($log['排队中的数量'] >$log['已完成数量']) {
  923. // $result[] = $log;
  924. // }
  925. if ($log['排队中的数量']) {
  926. $result[] = $log;
  927. }
  928. // if ($log['处理中数量'] >= 0) {
  929. // $result[] = $log;
  930. // }
  931. }
  932. return json([
  933. 'code' => 0,
  934. 'msg' => '查询成功',
  935. 'data' => $result,
  936. 'count' => count($result)
  937. ]);
  938. }
  939. /**
  940. * 查询总队列状态(统计当前处理的数据量)
  941. */
  942. public function queueStats()
  943. {
  944. $statusList = Db::name('image_task_log')
  945. ->field('status, COUNT(*) as total')
  946. ->where('mod_rq', null)
  947. ->where('create_time', '>=', date('Y-m-d 00:00:00'))
  948. ->group('status')
  949. ->select();
  950. $statusCount = [];
  951. foreach ($statusList as $item) {
  952. $statusCount[$item['status']] = $item['total'];
  953. }
  954. // 总数为所有状态和
  955. $total = array_sum($statusCount);
  956. //获取队列当前状态
  957. $statusText = Db::name('queue_logs')->order('id desc')->value('status');
  958. return json([
  959. 'code' => 0,
  960. 'msg' => '获取成功',
  961. 'data' => [
  962. '总任务数' => $total,
  963. '待处理' => $statusCount[0] ?? 0,
  964. '处理中' => $statusCount[1] ?? 0,
  965. '成功' => $statusCount[2] ?? 0,
  966. '失败' => $statusCount[-1] ?? 0,
  967. '当前状态' => $statusText
  968. ]
  969. ]);
  970. }
  971. /**
  972. * 显示当前运行中的队列监听进程
  973. */
  974. public function viewQueueStatus()
  975. {
  976. $redis = new \Redis();
  977. $redis->connect('127.0.0.1', 6379);
  978. $redis->auth('123456');
  979. $redis->select(15);
  980. $key = 'queues:imgtotxt';
  981. // 判断 key 是否存在,避免报错
  982. if (!$redis->exists($key)) {
  983. return json([
  984. 'code' => 0,
  985. 'msg' => '查询成功,队列为空',
  986. 'count' => 0,
  987. 'tasks_preview' => []
  988. ]);
  989. }
  990. $count = $redis->lLen($key);
  991. $list = $redis->lRange($key, 0, 9);
  992. // 解码 JSON 内容,确保每一项都有效
  993. $parsed = array_filter(array_map(function ($item) {
  994. return json_decode($item, true);
  995. }, $list), function ($item) {
  996. return !is_null($item);
  997. });
  998. return json([
  999. 'code' => 0,
  1000. 'msg' => '查询成功',
  1001. 'count' => $count,
  1002. 'tasks_preview' => $parsed
  1003. ]);
  1004. }
  1005. /**
  1006. * 清空队列并删除队列日志记录
  1007. */
  1008. public function stopQueueProcesses()
  1009. {
  1010. Db::name('image_task_log')
  1011. ->where('log', '队列中')
  1012. ->whereOr('status', 1)
  1013. ->where('create_time', '>=', date('Y-m-d 00:00:00'))
  1014. ->update([
  1015. 'status' => "-1",
  1016. 'log' => '清空取消队列',
  1017. 'mod_rq' => date('Y-m-d H:i:s')
  1018. ]);
  1019. Db::name('image_task_log')
  1020. ->whereLike('log', '%处理中%')
  1021. ->where('create_time', '>=', date('Y-m-d 00:00:00'))
  1022. ->update([
  1023. 'status' => "-1",
  1024. 'log' => '清空取消队列',
  1025. 'mod_rq' => date('Y-m-d H:i:s')
  1026. ]);
  1027. $redis = new \Redis();
  1028. $redis->connect('127.0.0.1', 6379);
  1029. $redis->auth('123456');
  1030. $redis->select(15);
  1031. $key_txttoimg = 'queues:txttoimg:reserved';
  1032. $key_txttotxt = 'queues:txttotxt:reserved';
  1033. $key_imgtotxt = 'queues:imgtotxt:reserved';
  1034. $key_imgtoimg = 'queues:imgtoimg:reserved';
  1035. // 清空 Redis 队列
  1036. $redis->del($key_txttoimg);
  1037. $redis->del($key_txttotxt);
  1038. $redis->del($key_imgtotxt);
  1039. $redis->del($key_imgtoimg);
  1040. $count = $redis->lLen($key_txttoimg) + $redis->lLen($key_txttotxt) + $redis->lLen($key_imgtotxt) + $redis->lLen($key_imgtoimg);
  1041. // if ($count === 0) {
  1042. // return json([
  1043. // 'code' => 1,
  1044. // 'msg' => '暂无队列需要停止'
  1045. // ]);
  1046. // }
  1047. return json([
  1048. 'code' => 0,
  1049. 'msg' => '成功停止队列任务'
  1050. ]);
  1051. }
  1052. /**
  1053. * 开启队列任务
  1054. * 暂时用不到、服务器已开启自动开启队列模式
  1055. */
  1056. // public function kaiStats()
  1057. // {
  1058. // // 判断是否已有监听进程在运行
  1059. // $check = shell_exec("ps aux | grep 'queue:listen' | grep -v grep");
  1060. // if ($check) {
  1061. // return json([
  1062. // 'code' => 1,
  1063. // 'msg' => '监听进程已存在,请勿重复启动'
  1064. // ]);
  1065. // }
  1066. // // 启动监听
  1067. // $command = 'nohup php think queue:listen --queue --timeout=300 --sleep=3 --memory=256 > /var/log/job_queue.log 2>&1 &';
  1068. // exec($command, $output, $status);
  1069. // if ($status === 0) {
  1070. // return json([
  1071. // 'code' => 0,
  1072. // 'msg' => '队列监听已启动'
  1073. // ]);
  1074. // } else {
  1075. // return json([
  1076. // 'code' => 1,
  1077. // 'msg' => '队列启动失败',
  1078. // 'output' => $output
  1079. // ]);
  1080. // }
  1081. // }
  1082. /**
  1083. * 通过店铺ID-查询对应店铺表数据
  1084. *
  1085. */
  1086. public function PatternApi()
  1087. {
  1088. $params = $this->request->param('pattern_id', '');
  1089. $tableName = 'pattern-' . $params;
  1090. // 连接 MongoDB
  1091. $mongo = Db::connect('mongodb');
  1092. // 查询指定 skc 的数据
  1093. $data = $mongo->table($tableName)
  1094. ->field('
  1095. name,
  1096. skc,
  1097. file
  1098. ')
  1099. ->where("skc", '0853004152036')
  1100. ->select();
  1101. $data = json_decode(json_encode($data), true); // 数组
  1102. return json([
  1103. 'code' => 0,
  1104. 'msg' => '获取成功',
  1105. 'data' => $data
  1106. ]);
  1107. }
  1108. }