WorkOrder.php 43 KB

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