WorkOrder.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  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. private function sendPostRequest($url, $data, $apiKey)
  173. {
  174. $ch = curl_init();
  175. curl_setopt($ch, CURLOPT_URL, $url);
  176. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  177. curl_setopt($ch, CURLOPT_POST, true);
  178. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  179. 'Authorization: Bearer ' . $apiKey,
  180. 'Accept: application/json',
  181. 'Content-Type: application/json'
  182. ]);
  183. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  184. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  185. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  186. curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 延长超时时间
  187. $response = curl_exec($ch);
  188. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  189. $error = curl_error($ch);
  190. curl_close($ch);
  191. return [
  192. 'response' => $response,
  193. 'http_code' => $httpCode,
  194. 'error' => $error
  195. ];
  196. }
  197. /**
  198. * 文本生成图片并保存第一张结果
  199. * @param array $params 请求参数
  200. * @return array 返回结果
  201. */
  202. public function txttowimg()
  203. {
  204. // API配置
  205. $config = [
  206. 'api_url' => 'https://chatapi.onechats.ai/mj/submit/imagine',
  207. 'fetch_url' => 'https://chatapi.onechats.ai/mj/task/',
  208. 'api_key' => 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK',
  209. 'default_prompt' => '一个猫',
  210. 'wait_time' => 3 // 等待生成完成的秒数
  211. ];
  212. try {
  213. // 1. 准备请求数据
  214. $prompt = $config['default_prompt'];
  215. $postData = [
  216. 'botType' => 'MID_JOURNEY',
  217. 'prompt' => $prompt,
  218. 'base64Array' => [],
  219. 'accountFilter' => [
  220. 'channelId' => "",
  221. 'instanceId' => "",
  222. 'modes' => [],
  223. 'remark' => "",
  224. 'remix' => true,
  225. 'remixAutoConsidered' => true
  226. ],
  227. 'notifyHook' => "",
  228. 'state' => ""
  229. ];
  230. // 2. 提交生成请求
  231. $generateResponse = $this->sendApiRequest($config['api_url'], $postData, $config['api_key']);
  232. $generateData = json_decode($generateResponse, true);
  233. if (empty($generateData['result'])) {
  234. throw new Exception('生成失败: '.($generateData['message'] ?? '未知错误'));
  235. }
  236. $taskId = $generateData['result'];
  237. // 3. 等待图片生成完成
  238. sleep($config['wait_time']);
  239. // 4. 获取生成结果
  240. $fetchUrl = $config['fetch_url'].$taskId.'/fetch';
  241. $fetchResponse = $this->sendApiRequest($fetchUrl, [], $config['api_key'], 'GET');
  242. $fetchData = json_decode($fetchResponse, true);
  243. if (empty($fetchData['imageUrl'])) {
  244. throw new Exception('获取图片失败: '.($fetchData['message'] ?? '未知错误'));
  245. }
  246. // 5. 处理返回的图片数组(取第一张)
  247. $imageUrls = is_array($fetchData['imageUrl']) ? $fetchData['imageUrl'] : [$fetchData['imageUrl']];
  248. $firstImageUrl = $imageUrls[0];
  249. // 6. 保存图片到本地
  250. $savePath = $this->saveImage($firstImageUrl);
  251. // 7. 返回结果
  252. return [
  253. 'code' => 200,
  254. 'msg' => '图片生成并保存成功',
  255. 'data' => [
  256. 'local_path' => $savePath,
  257. 'web_url' => request()->domain().$savePath,
  258. 'task_id' => $taskId
  259. ]
  260. ];
  261. } catch (Exception $e) {
  262. // 错误处理
  263. return [
  264. 'code' => 500,
  265. 'msg' => '处理失败: '.$e->getMessage(),
  266. 'data' => null
  267. ];
  268. }
  269. }
  270. /**
  271. * 发送API请求
  272. * @param string $url 请求地址
  273. * @param array $data 请求数据
  274. * @param string $apiKey API密钥
  275. * @param string $method 请求方法
  276. * @return string 响应内容
  277. * @throws Exception
  278. */
  279. private function sendApiRequest($url, $data, $apiKey, $method = 'POST')
  280. {
  281. $ch = curl_init();
  282. curl_setopt_array($ch, [
  283. CURLOPT_URL => $url,
  284. CURLOPT_RETURNTRANSFER => true,
  285. CURLOPT_CUSTOMREQUEST => $method,
  286. CURLOPT_HTTPHEADER => [
  287. 'Authorization: Bearer '.$apiKey,
  288. 'Accept: application/json',
  289. 'Content-Type: application/json'
  290. ],
  291. CURLOPT_POSTFIELDS => $method === 'POST' ? json_encode($data) : null,
  292. CURLOPT_SSL_VERIFYPEER => false,
  293. CURLOPT_SSL_VERIFYHOST => false,
  294. CURLOPT_TIMEOUT => 60,
  295. CURLOPT_FAILONERROR => true
  296. ]);
  297. $response = curl_exec($ch);
  298. $error = curl_error($ch);
  299. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  300. curl_close($ch);
  301. if ($error) {
  302. throw new Exception('API请求失败: '.$error);
  303. }
  304. if ($httpCode < 200 || $httpCode >= 300) {
  305. throw new Exception('API返回错误状态码: '.$httpCode);
  306. }
  307. return $response;
  308. }
  309. /**
  310. * 保存图片到本地
  311. * @param string $imageUrl 图片URL
  312. * @return string 本地保存路径
  313. * @throws Exception
  314. */
  315. private function saveImage($imageUrl)
  316. {
  317. // 1. 创建存储目录
  318. $saveDir = ROOT_PATH.'public'.DS.'uploads'.DS.'midjourney'.DS.date('Ymd');
  319. if (!is_dir($saveDir)) {
  320. mkdir($saveDir, 0755, true);
  321. }
  322. // 2. 生成唯一文件名
  323. $filename = uniqid().'.png';
  324. $localPath = DS.'uploads'.DS.'midjourney'.DS.date('Ymd').DS.$filename;
  325. $fullPath = $saveDir.DS.$filename;
  326. // 3. 下载图片
  327. $ch = curl_init($imageUrl);
  328. curl_setopt_array($ch, [
  329. CURLOPT_RETURNTRANSFER => true,
  330. CURLOPT_FOLLOWLOCATION => true,
  331. CURLOPT_SSL_VERIFYPEER => false,
  332. CURLOPT_CONNECTTIMEOUT => 15
  333. ]);
  334. $imageData = curl_exec($ch);
  335. $error = curl_error($ch);
  336. curl_close($ch);
  337. if (!$imageData) {
  338. throw new Exception('图片下载失败: '.$error);
  339. }
  340. // 4. 验证图片类型
  341. $imageInfo = getimagesizefromstring($imageData);
  342. if (!in_array($imageInfo['mime'] ?? '', ['image/png', 'image/jpeg'])) {
  343. throw new Exception('下载内容不是有效图片');
  344. }
  345. // 5. 保存文件
  346. if (!file_put_contents($fullPath, $imageData)) {
  347. throw new Exception('图片保存失败');
  348. }
  349. return $localPath;
  350. }
  351. /**
  352. * 图生图本地测试
  353. */
  354. public function imgtowimg()
  355. {
  356. $prompt = $this->request->param('prompt', '');
  357. $imgRelPath = 'uploads/operate/ai/Preview/arr/两只手碰拳的黑白线条插画下有Daddy Me字样风格简约质.png';
  358. $imgPath = ROOT_PATH . 'public/' . $imgRelPath;
  359. if (!file_exists($imgPath)) {
  360. return json(['code' => 1, 'msg' => '原图不存在:' . $imgRelPath]);
  361. }
  362. $imgData = file_get_contents($imgPath);
  363. $base64Img = 'data:image/png;base64,' . base64_encode($imgData);
  364. $params = [
  365. 'prompt' => $prompt,
  366. 'negative_prompt' => '(deformed, distorted, disfigured:1.3), poorly drawn, bad anatomy',
  367. 'steps' => 20,
  368. 'sampler_name' => 'DPM++ 2M SDE',
  369. 'cfg_scale' => 7,
  370. 'seed' => -1,
  371. 'width' => 1024,
  372. 'height' => 1303,
  373. 'override_settings' => [
  374. 'sd_model_checkpoint' => 'realisticVisionV51_v51VAE-inpainting',
  375. 'sd_vae' => 'vae-ft-mse-840000-ema-pruned',
  376. 'CLIP_stop_at_last_layers' => 2
  377. ],
  378. 'clip_skip' => 2,
  379. 'alwayson_scripts' => [
  380. 'controlnet' => [
  381. 'args' => [[
  382. 'enabled' => true,
  383. 'input_image' => $base64Img,
  384. 'module' => 'inpaint_only+lama',
  385. 'model' => 'control_v11p_sd15_inpaint_fp16 [be8bc0ed]',
  386. 'weight' => 1,
  387. 'resize_mode' => 'Resize and Fill',
  388. 'pixel_perfect' => false,
  389. 'control_mode' => 'ControlNet is more important',
  390. 'starting_control_step' => 0,
  391. 'ending_control_step' => 1
  392. ]]
  393. ]
  394. ]
  395. ];
  396. $apiUrl = "http://20.0.17.188:45001/sdapi/v1/txt2img";
  397. $headers = ['Content-Type: application/json'];
  398. $ch = curl_init();
  399. curl_setopt($ch, CURLOPT_URL, $apiUrl);
  400. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  401. curl_setopt($ch, CURLOPT_POST, true);
  402. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  403. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params, JSON_UNESCAPED_UNICODE));
  404. curl_setopt($ch, CURLOPT_TIMEOUT, 180);
  405. $response = curl_exec($ch);
  406. $error = curl_error($ch);
  407. curl_close($ch);
  408. if ($error) {
  409. return json(['code' => 1, 'msg' => '请求失败:' . $error]);
  410. }
  411. $data = json_decode($response, true);
  412. if (!isset($data['images'][0])) {
  413. return json(['code' => 1, 'msg' => '接口未返回图像数据']);
  414. }
  415. $resultImg = base64_decode($data['images'][0]);
  416. $saveDir = ROOT_PATH . 'public/uploads/img2img/';
  417. if (!is_dir($saveDir)) {
  418. mkdir($saveDir, 0755, true);
  419. }
  420. $originalBaseName = pathinfo($imgRelPath, PATHINFO_FILENAME);
  421. $fileName = $originalBaseName . '-' . time() . '-1024x1248.png';
  422. $savePath = $saveDir . $fileName;
  423. file_put_contents($savePath, $resultImg);
  424. return json([
  425. 'code' => 0,
  426. 'msg' => '图像生成成功',
  427. 'data' => [
  428. 'origin_url' => '/uploads/img2img/' . $fileName
  429. ]
  430. ]);
  431. }
  432. /**
  433. * 后期图像处理-单张图片高清放大处理
  434. */
  435. public function extra_image()
  436. {
  437. // 配置参数
  438. $config = [
  439. 'input_dir' => 'uploads/operate/ai/Preview/arr/',
  440. 'output_dir' => 'uploads/extra_image/',
  441. 'api_url' => 'http://20.0.17.188:45001/sdapi/v1/extra-single-image',
  442. 'timeout' => 120, // 增加超时时间,高清处理可能耗时较长
  443. 'upscale_params' => [
  444. 'resize_mode' => 0,
  445. 'show_extras_results' => true,
  446. 'gfpgan_visibility' => 0, // 人脸修复关闭
  447. 'codeformer_visibility' => 0, // 人脸修复关闭
  448. 'codeformer_weight' => 0,
  449. 'upscaling_resize' => 2.45, // 放大倍数
  450. 'upscaling_crop' => true,
  451. 'upscaler_1' => 'R-ESRGAN 4x+ Anime6B', // 主放大模型
  452. 'upscaler_2' => 'None', // 不使用第二放大器
  453. 'extras_upscaler_2_visibility' => 0,
  454. 'upscale_first' => false,
  455. ]
  456. ];
  457. // 输入文件处理
  458. $imgRelPath = '图案的整体色调是柔和的蓝色和灰色形成温馨而宁静的视觉效果花卉.png';
  459. $imgPath = ROOT_PATH . 'public/' . $config['input_dir'] . $imgRelPath;
  460. if (!file_exists($imgPath)) {
  461. return json(['code' => 1, 'msg' => '原图不存在:' . $imgRelPath]);
  462. }
  463. // 读取并编码图片
  464. try {
  465. $imgData = file_get_contents($imgPath);
  466. if ($imgData === false) {
  467. throw new Exception('无法读取图片文件');
  468. }
  469. $base64Img = base64_encode($imgData);
  470. } catch (Exception $e) {
  471. return json(['code' => 1, 'msg' => '图片处理失败:' . $e->getMessage()]);
  472. }
  473. // 准备API请求数据
  474. $postData = array_merge($config['upscale_params'], ['image' => $base64Img]);
  475. $jsonData = json_encode($postData);
  476. if ($jsonData === false) {
  477. return json(['code' => 1, 'msg' => 'JSON编码失败']);
  478. }
  479. // 调用API进行高清放大
  480. $ch = curl_init();
  481. curl_setopt_array($ch, [
  482. CURLOPT_URL => $config['api_url'],
  483. CURLOPT_RETURNTRANSFER => true,
  484. CURLOPT_POST => true,
  485. CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
  486. CURLOPT_POSTFIELDS => $jsonData,
  487. CURLOPT_TIMEOUT => $config['timeout'],
  488. CURLOPT_CONNECTTIMEOUT => 30,
  489. ]);
  490. $response = curl_exec($ch);
  491. $error = curl_error($ch);
  492. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  493. curl_close($ch);
  494. if ($error) {
  495. return json(['code' => 1, 'msg' => 'API请求失败:' . $error]);
  496. }
  497. if ($httpCode !== 200) {
  498. return json(['code' => 1, 'msg' => 'API返回错误状态码:' . $httpCode]);
  499. }
  500. $data = json_decode($response, true);
  501. if (json_last_error() !== JSON_ERROR_NONE) {
  502. return json(['code' => 1, 'msg' => 'API返回数据解析失败']);
  503. }
  504. if (!isset($data['image']) || empty($data['image'])) {
  505. return json(['code' => 1, 'msg' => '接口未返回有效的图像数据']);
  506. }
  507. // 保存处理后的图片
  508. try {
  509. $resultImg = base64_decode($data['image']);
  510. if ($resultImg === false) {
  511. throw new Exception('Base64解码失败');
  512. }
  513. $saveDir = ROOT_PATH . 'public/' . $config['output_dir'];
  514. if (!is_dir($saveDir) && !mkdir($saveDir, 0755, true)) {
  515. throw new Exception('无法创建输出目录');
  516. }
  517. $originalBaseName = pathinfo($imgRelPath, PATHINFO_FILENAME);
  518. $fileName = $originalBaseName . '-hd.png'; // 使用-hd后缀更明确
  519. $savePath = $saveDir . $fileName;
  520. if (file_put_contents($savePath, $resultImg) === false) {
  521. throw new Exception('无法保存处理后的图片');
  522. }
  523. // 返回成功响应
  524. return json([
  525. 'code' => 0,
  526. 'msg' => '图像高清放大处理成功',
  527. 'data' => [
  528. 'url' => '/' . $config['output_dir'] . $fileName,
  529. 'original_size' => filesize($imgPath),
  530. 'processed_size' => filesize($savePath),
  531. 'resolution' => getimagesize($savePath), // 返回新图片的分辨率
  532. ]
  533. ]);
  534. } catch (Exception $e) {
  535. return json(['code' => 1, 'msg' => '保存结果失败:' . $e->getMessage()]);
  536. }
  537. }
  538. /**
  539. * 获取 SD 模型列表
  540. * 接口地址: /sdapi/v1/sd-models
  541. */
  542. public function sd_models() {
  543. // $url = "http://20.0.17.188:45001/sdapi/v1/sd-models";
  544. // // 初始化 cURL
  545. // $ch = curl_init();
  546. // // 设置请求参数
  547. // curl_setopt($ch, CURLOPT_URL, $url);
  548. // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  549. // curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  550. // curl_setopt($ch, CURLOPT_HTTPHEADER, [
  551. // 'Content-Type: application/json',
  552. // 'Accept: application/json',
  553. // ]);
  554. // // 发送请求
  555. // $response = curl_exec($ch);
  556. // // 错误处理
  557. // if (curl_errno($ch)) {
  558. // curl_close($ch);
  559. // return json([
  560. // 'code' => 1,
  561. // 'msg' => '请求失败: ' . curl_error($ch),
  562. // 'data' => [],
  563. // 'count' => 0
  564. // ]);
  565. // }
  566. // curl_close($ch);
  567. // // 解析 JSON 响应
  568. // $result = json_decode($response, true);
  569. // // 判断返回数据是否有效
  570. // if (!is_array($result)) {
  571. // return json([
  572. // 'code' => 1,
  573. // 'msg' => '数据解析失败',
  574. // 'data' => [],
  575. // 'count' => 0
  576. // ]);
  577. // }
  578. // 正常返回
  579. return json([
  580. 'code' => 0,
  581. 'msg' => '查询成功',
  582. 'data' => '',
  583. 'count' => 2,
  584. ]);
  585. }
  586. /**
  587. * 查询队列列表
  588. * 统计文件对应的队列情况
  589. */
  590. public function get_queue_logs()
  591. {
  592. $params = $this->request->param('old_image_file', '');
  593. $queue_logs = Db::name('queue_logs')
  594. ->where('old_image_file', $params)
  595. ->order('id desc')
  596. ->select();
  597. $result = []; //初始化变量,避免未定义错误
  598. foreach ($queue_logs as &$log) {
  599. $taskId = $log['id'];
  600. $statusCount = Db::name('image_task_log')
  601. ->field('status, COUNT(*) as count')
  602. ->where('task_id', $taskId)
  603. ->where('mod_rq', null)
  604. ->group('status')
  605. ->select();
  606. $log['已完成数量'] = 0;
  607. $log['处理中数量'] = 0;
  608. $log['排队中的数量'] = 0;
  609. $log['失败数量'] = 0;
  610. foreach ($statusCount as $item) {
  611. switch ($item['status']) {
  612. case 0:
  613. $log['排队中的数量'] = $item['count'];
  614. break;
  615. case 1:
  616. $log['处理中数量'] = $item['count'];
  617. break;
  618. case 2:
  619. $log['已完成数量'] = $item['count'];
  620. break;
  621. case -1:
  622. $log['失败数量'] = $item['count'];
  623. break;
  624. }
  625. }
  626. // if ($log['排队中的数量'] >$log['已完成数量']) {
  627. // $result[] = $log;
  628. // }
  629. if ($log['排队中的数量']) {
  630. $result[] = $log;
  631. }
  632. // if ($log['处理中数量'] >= 0) {
  633. // $result[] = $log;
  634. // }
  635. }
  636. return json([
  637. 'code' => 0,
  638. 'msg' => '查询成功',
  639. 'data' => $result,
  640. 'count' => count($result)
  641. ]);
  642. }
  643. /**
  644. * 查询总队列状态(统计当前处理的数据量)
  645. */
  646. public function queueStats()
  647. {
  648. $statusList = Db::name('image_task_log')
  649. ->field('status, COUNT(*) as total')
  650. ->where('mod_rq', null)
  651. ->where('create_time', '>=', date('Y-m-d 00:00:00'))
  652. ->group('status')
  653. ->select();
  654. $statusCount = [];
  655. foreach ($statusList as $item) {
  656. $statusCount[$item['status']] = $item['total'];
  657. }
  658. // 总数为所有状态和
  659. $total = array_sum($statusCount);
  660. //获取队列当前状态
  661. $statusText = Db::name('queue_logs')->order('id desc')->value('status');
  662. return json([
  663. 'code' => 0,
  664. 'msg' => '获取成功',
  665. 'data' => [
  666. '总任务数' => $total,
  667. '待处理' => $statusCount[0] ?? 0,
  668. '处理中' => $statusCount[1] ?? 0,
  669. '成功' => $statusCount[2] ?? 0,
  670. '失败' => $statusCount[-1] ?? 0,
  671. '当前状态' => $statusText
  672. ]
  673. ]);
  674. }
  675. /**
  676. * 显示当前运行中的队列监听进程
  677. */
  678. public function viewQueueStatus()
  679. {
  680. $redis = new \Redis();
  681. $redis->connect('127.0.0.1', 6379);
  682. $redis->auth('123456');
  683. $redis->select(15);
  684. $key = 'queues:imgtotxt';
  685. // 判断 key 是否存在,避免报错
  686. if (!$redis->exists($key)) {
  687. return json([
  688. 'code' => 0,
  689. 'msg' => '查询成功,队列为空',
  690. 'count' => 0,
  691. 'tasks_preview' => []
  692. ]);
  693. }
  694. $count = $redis->lLen($key);
  695. $list = $redis->lRange($key, 0, 9);
  696. // 解码 JSON 内容,确保每一项都有效
  697. $parsed = array_filter(array_map(function ($item) {
  698. return json_decode($item, true);
  699. }, $list), function ($item) {
  700. return !is_null($item);
  701. });
  702. return json([
  703. 'code' => 0,
  704. 'msg' => '查询成功',
  705. 'count' => $count,
  706. 'tasks_preview' => $parsed
  707. ]);
  708. }
  709. /**
  710. * 清空队列并删除队列日志记录
  711. */
  712. public function stopQueueProcesses()
  713. {
  714. Db::name('image_task_log')
  715. ->where('log', '队列中')
  716. ->whereOr('status', 1)
  717. ->where('create_time', '>=', date('Y-m-d 00:00:00'))
  718. ->update([
  719. 'status' => "-1",
  720. 'log' => '清空取消队列',
  721. 'mod_rq' => date('Y-m-d H:i:s')
  722. ]);
  723. Db::name('image_task_log')
  724. ->whereLike('log', '%处理中%')
  725. ->where('create_time', '>=', date('Y-m-d 00:00:00'))
  726. ->update([
  727. 'status' => "-1",
  728. 'log' => '清空取消队列',
  729. 'mod_rq' => date('Y-m-d H:i:s')
  730. ]);
  731. $redis = new \Redis();
  732. $redis->connect('127.0.0.1', 6379);
  733. $redis->auth('123456');
  734. $redis->select(15);
  735. $key_txttoimg = 'queues:txttoimg:reserved';
  736. $key_txttotxt = 'queues:txttotxt:reserved';
  737. $key_imgtotxt = 'queues:imgtotxt:reserved';
  738. $key_imgtoimg = 'queues:imgtoimg:reserved';
  739. // 清空 Redis 队列
  740. $redis->del($key_txttoimg);
  741. $redis->del($key_txttotxt);
  742. $redis->del($key_imgtotxt);
  743. $redis->del($key_imgtoimg);
  744. $count = $redis->lLen($key_txttoimg) + $redis->lLen($key_txttotxt) + $redis->lLen($key_imgtotxt) + $redis->lLen($key_imgtoimg);
  745. // if ($count === 0) {
  746. // return json([
  747. // 'code' => 1,
  748. // 'msg' => '暂无队列需要停止'
  749. // ]);
  750. // }
  751. return json([
  752. 'code' => 0,
  753. 'msg' => '成功停止队列任务'
  754. ]);
  755. }
  756. /**
  757. * 开启队列任务
  758. * 暂时用不到、服务器已开启自动开启队列模式
  759. */
  760. // public function kaiStats()
  761. // {
  762. // // 判断是否已有监听进程在运行
  763. // $check = shell_exec("ps aux | grep 'queue:listen' | grep -v grep");
  764. // if ($check) {
  765. // return json([
  766. // 'code' => 1,
  767. // 'msg' => '监听进程已存在,请勿重复启动'
  768. // ]);
  769. // }
  770. // // 启动监听
  771. // $command = 'nohup php think queue:listen --queue --timeout=300 --sleep=3 --memory=256 > /var/log/job_queue.log 2>&1 &';
  772. // exec($command, $output, $status);
  773. // if ($status === 0) {
  774. // return json([
  775. // 'code' => 0,
  776. // 'msg' => '队列监听已启动'
  777. // ]);
  778. // } else {
  779. // return json([
  780. // 'code' => 1,
  781. // 'msg' => '队列启动失败',
  782. // 'output' => $output
  783. // ]);
  784. // }
  785. // }
  786. /**
  787. * 通过店铺ID-查询对应店铺表数据
  788. *
  789. */
  790. public function PatternApi()
  791. {
  792. $params = $this->request->param('pattern_id', '');
  793. $tableName = 'pattern-' . $params;
  794. // 连接 MongoDB
  795. $mongo = Db::connect('mongodb');
  796. // 查询指定 skc 的数据
  797. $data = $mongo->table($tableName)
  798. ->field('
  799. name,
  800. skc,
  801. file
  802. ')
  803. ->where("skc", '0853004152036')
  804. ->select();
  805. $data = json_decode(json_encode($data), true); // 数组
  806. return json([
  807. 'code' => 0,
  808. 'msg' => '获取成功',
  809. 'data' => $data
  810. ]);
  811. }
  812. }