Facility.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use think\Db;
  5. use think\File;
  6. use think\Request;
  7. use RecursiveIteratorIterator;
  8. use RecursiveDirectoryIterator;
  9. class Facility extends Api
  10. {
  11. protected $noNeedLogin = ['*'];
  12. protected $noNeedRight = ['*'];
  13. public function getPreviewSubDirs()
  14. {
  15. $baseDir = rtrim(str_replace('\\', '/', ROOT_PATH), '/') . '/public/uploads/operate/ai/Preview';
  16. $baseRelativePath = 'uploads/operate/ai/Preview';
  17. if (!is_dir($baseDir)) {
  18. return json(['code' => 1, 'msg' => '目录不存在']);
  19. }
  20. // 包含 DB 时间戳扰动的缓存键
  21. $version = $this->generateFlexibleDirectoryHash($baseDir);
  22. $cacheKey = 'preview_flexible_dirs_' . $version;
  23. $dirList = cache($cacheKey);
  24. if (!$dirList) {
  25. $dirList = $this->scanFlexibleDirectories($baseDir, $baseRelativePath);
  26. cache($cacheKey, $dirList, 300); // 缓存 5 分钟(可调)
  27. } else {
  28. // 实时刷新 new_image_count(避免缓存值过期)
  29. foreach ($dirList as &$dir) {
  30. $dir['new_image_count'] = Db::name('text_to_image')
  31. ->where('status', 1)
  32. ->where('new_image_url', '<>', '')
  33. ->where('img_name', '<>', '')
  34. ->whereLike('old_image_url', $dir['old_image_url'] . '/%')
  35. ->count();
  36. }
  37. }
  38. return json([
  39. 'code' => 0,
  40. 'msg' => '获取成功',
  41. 'data' => $dirList
  42. ]);
  43. }
  44. private function scanFlexibleDirectories($baseDir, $baseRelativePath)
  45. {
  46. $dirs = [];
  47. $index = 1;
  48. $firstLevelDirs = glob($baseDir . '/*', GLOB_ONLYDIR);
  49. foreach ($firstLevelDirs as $level1Path) {
  50. $secondLevelDirs = glob($level1Path . '/*', GLOB_ONLYDIR);
  51. if ($secondLevelDirs) {
  52. foreach ($secondLevelDirs as $level2Path) {
  53. $dirs = array_merge($dirs, $this->processDir($level2Path, $baseDir, $baseRelativePath, $index));
  54. }
  55. } else {
  56. $dirs = array_merge($dirs, $this->processDir($level1Path, $baseDir, $baseRelativePath, $index));
  57. }
  58. }
  59. usort($dirs, function ($a, $b) {
  60. return $b['id'] - $a['id'];
  61. });
  62. return $dirs;
  63. }
  64. private function processDir($fullPath, $baseDir, $baseRelativePath, &$index)
  65. {
  66. $result = [];
  67. $relativeDir = ltrim(str_replace($baseDir, '', $fullPath), '/');
  68. $ctime = @filectime($fullPath) ?: time();
  69. $imageFiles = glob($fullPath . '/*.{jpg,jpeg,png}', GLOB_BRACE);
  70. $originalImageCount = $imageFiles ? count($imageFiles) : 0;
  71. $img_count = Db::name('text_to_image')
  72. ->where('status', 1)
  73. ->where('new_image_url', '<>', '')
  74. ->where('img_name', '<>', '')
  75. ->whereLike('old_image_url', $baseRelativePath . '/' . $relativeDir . '/%')
  76. ->count();
  77. $queueLog = Db::name('image_task_log')
  78. ->whereLike('file_name', $baseRelativePath . '/' . $relativeDir . '/%')
  79. ->whereLike('log', '%处理中%')
  80. ->order('id', 'desc')
  81. ->find();
  82. if ($img_count === 0 && !$queueLog && $originalImageCount === 0) {
  83. return [];
  84. }
  85. $result[] = [
  86. 'id' => $index++,
  87. 'name' => basename($fullPath),
  88. 'ctime' => $ctime,
  89. 'ctime_text' => date('Y-m-d H:i:s', $ctime),
  90. 'old_img_count' => $originalImageCount,
  91. 'new_image_count' => $img_count,
  92. 'old_image_url' => $baseRelativePath . '/' . $relativeDir,
  93. 'new_image_url' => '/uploads/operate/ai/dall-e/',
  94. 'queueLog_id' => $queueLog['id'] ?? '',
  95. 'queueLog_task_id' => $queueLog['task_id'] ?? '',
  96. 'queueLog_model_name' => $queueLog['model_name'] ?? '',
  97. 'queueLog_model_name_status' => $queueLog ? 1 : 0,
  98. ];
  99. return $result;
  100. }
  101. private function generateFlexibleDirectoryHash($baseDir)
  102. {
  103. $hash = '';
  104. $dirPaths = [];
  105. $firstDirs = glob($baseDir . '/*', GLOB_ONLYDIR);
  106. foreach ($firstDirs as $dir1) {
  107. $subDirs = glob($dir1 . '/*', GLOB_ONLYDIR);
  108. if ($subDirs) {
  109. foreach ($subDirs as $sub) {
  110. $dirPaths[] = $sub;
  111. $hash .= basename($dir1) . '/' . basename($sub) . filemtime($sub);
  112. }
  113. } else {
  114. $dirPaths[] = $dir1;
  115. $hash .= basename($dir1) . filemtime($dir1);
  116. }
  117. }
  118. $baseRelativePath = 'uploads/operate/ai/Preview';
  119. $queueStatusBits = [];
  120. foreach ($dirPaths as $fullPath) {
  121. $relativeDir = ltrim(str_replace($baseDir, '', $fullPath), '/');
  122. $fileNameLike = $baseRelativePath . '/' . $relativeDir . '/%';
  123. // 查询是否存在任何“处理中”的记录
  124. $logs = Db::name('image_task_log')
  125. ->whereLike('file_name', $fileNameLike)
  126. ->whereLike('log', '%处理中%')
  127. ->select();
  128. // 转换为布尔状态再转成位标记(0 或 1)
  129. $queueStatusBits[] = count($logs) > 0 ? '1' : '0';
  130. // 可选:调试打印
  131. // echo "<pre>路径:{$fileNameLike} => 状态:" . (count($logs) > 0 ? '有处理中' : '无') . "</pre>";
  132. }
  133. // 队列状态位图拼接
  134. $queueStatusHash = implode('', $queueStatusBits); // 如:'01001'
  135. $hash .= '_QS_' . md5($queueStatusHash); // 状态稳定扰动,无需 time()
  136. return md5($hash);
  137. }
  138. /**
  139. * 获取指定目录所有图片(完全实时版本)
  140. */
  141. public function getPreviewimg()
  142. {
  143. $page = (int)$this->request->param('page', 1);
  144. $limit = (int)$this->request->param('limit', 50);
  145. $status = $this->request->param('status', '');
  146. $status_name = $this->request->param('status_name', '');
  147. $relativePath = $this->request->param('path', '');
  148. $basePath = ROOT_PATH . 'public/';
  149. $fullPath = $basePath . $relativePath;
  150. if (!is_dir($fullPath)) {
  151. return json(['code' => 1, 'msg' => '原图目录不存在']);
  152. }
  153. // 构建缓存键与构建锁键(仅缓存文件系统信息)
  154. $hash = md5($relativePath);
  155. $cacheKey = "previewimg_fileinfo_{$hash}";
  156. $lockKey = "previewimg_building_{$hash}";
  157. $cacheExpire = 600; // 10分钟
  158. $cachedFileInfo = cache($cacheKey);
  159. if (!$cachedFileInfo) {
  160. // 防止缓存"惊群效应"
  161. if (!cache($lockKey)) {
  162. cache($lockKey, 1, 60); // 1分钟构建锁
  163. // 获取所有图片文件信息
  164. $allImages = glob($fullPath . '/*.{jpg,jpeg,png}', GLOB_BRACE);
  165. $fileInfoMap = [];
  166. foreach ($allImages as $imgPath) {
  167. $relative = str_replace('\\', '/', trim(str_replace($basePath, '', $imgPath), '/'));
  168. $info = @getimagesize($imgPath);
  169. $fileInfoMap[$relative] = [
  170. 'width' => $info[0] ?? 0,
  171. 'height' => $info[1] ?? 0,
  172. 'size_kb' => round(filesize($imgPath) / 1024, 2),
  173. 'created_time' => date('Y-m-d H:i:s', filectime($imgPath))
  174. ];
  175. }
  176. // 构建缓存数据(仅文件系统信息)
  177. $cachedFileInfo = [];
  178. foreach (array_keys($fileInfoMap) as $path) {
  179. $cachedFileInfo[] = [
  180. 'path' => $path,
  181. 'info' => $fileInfoMap[$path]
  182. ];
  183. }
  184. // 设置缓存 + 删除构建锁
  185. cache($cacheKey, $cachedFileInfo, $cacheExpire);
  186. cache($lockKey, null);
  187. } else {
  188. // 等待缓存生成
  189. $waitTime = 0;
  190. while (!$cachedFileInfo && $waitTime < 10) {
  191. sleep(1);
  192. $waitTime++;
  193. $cachedFileInfo = cache($cacheKey);
  194. }
  195. if (!$cachedFileInfo) {
  196. return json(['code' => 2, 'msg' => '系统正忙,请稍后重试']);
  197. }
  198. }
  199. }
  200. // 获取所有需要实时查询的路径
  201. $paths = array_column($cachedFileInfo, 'path');
  202. // 实时查询数据库状态信息(单次批量查询)
  203. $dbRecords = Db::name('text_to_image')
  204. ->whereIn('old_image_url', $paths)
  205. ->field('id as img_id, old_image_url, new_image_url, custom_image_url,imgtoimg_url,taskId,chinese_description, english_description, img_name, status, status_name')
  206. ->select();
  207. // 实时查询队列状态(单次批量查询)
  208. $queueRecords = Db::name('image_task_log')
  209. ->where('mod_rq', null)
  210. ->whereIn('file_name', $paths)
  211. ->field('file_name, log')
  212. ->select();
  213. // 实时查询same_count(稍后按需查询)
  214. // 构建映射关系
  215. $processedMap = [];
  216. foreach ($dbRecords as $item) {
  217. $key = str_replace('\\', '/', trim($item['old_image_url'], '/'));
  218. $processedMap[$key] = $item;
  219. }
  220. $queueMap = [];
  221. foreach ($queueRecords as $q) {
  222. $key = str_replace('\\', '/', trim($q['file_name'], '/'));
  223. $queueMap[$key] = $q['log'];
  224. }
  225. // 合并数据
  226. $mergedData = [];
  227. foreach ($cachedFileInfo as $data) {
  228. $path = $data['path'];
  229. $item = $processedMap[$path] ?? [];
  230. $mergedData[] = [
  231. 'path' => $path,
  232. 'item' => $item,
  233. 'info' => $data['info'],
  234. 'dbStatus' => isset($item['status']) ? (int)$item['status'] : 0,
  235. 'dbStatusName' => $item['status_name'] ?? '',
  236. 'isProcessed' => !empty($item['img_name']) && !empty($item['custom_image_url']),
  237. 'queueStatus' => $queueMap[$path] ?? ''
  238. ];
  239. }
  240. // 筛选状态字段
  241. $filtered = array_filter($mergedData, function ($data) use ($status, $status_name) {
  242. // 状态码筛选
  243. if ($status !== '' && (int)$status !== $data['dbStatus']) return false;
  244. // 状态名称筛选
  245. if ($status_name !== '') {
  246. if ($status_name === '未图生文') {
  247. // 当状态名为"未图生文"时,匹配空值或null
  248. if (!empty($data['dbStatusName'])) return false;
  249. } elseif ($status_name === '未文生文') {
  250. if ($data['dbStatusName'] !== '图生文') return false;
  251. } elseif ($status_name === '未文生图') {
  252. if ($data['dbStatusName'] !== '图生文') return false;
  253. } elseif ($status_name === '未图生图') {
  254. if ($data['dbStatusName'] !== '文生图') return false;
  255. } else {
  256. // 其他状态名需要精确匹配
  257. if ($status_name !== $data['dbStatusName']) return false;
  258. }
  259. }
  260. return true;
  261. });
  262. // 分页处理
  263. $total = count($filtered);
  264. $paged = array_slice(array_values($filtered), ($page - 1) * $limit, $limit);
  265. // 实时查询当前页的same_count(优化性能)
  266. $pagedPaths = array_column($paged, 'path');
  267. $sameCountMap = [];
  268. if ($pagedPaths) {
  269. $sameCountMap = Db::name('text_to_image')
  270. ->whereIn('old_image_url', $pagedPaths)
  271. // ->where('new_image_url', '<>', '')
  272. ->where('new_image_url', '<>', '')
  273. ->where('taskId', '<>', '')
  274. ->group('old_image_url')
  275. ->column('count(*) as cnt', 'old_image_url');
  276. }
  277. // 构建最终结果
  278. $result = [];
  279. foreach ($paged as $i => $data) {
  280. $path = $data['path'];
  281. $item = $data['item'];
  282. $info = $data['info'];
  283. $result[] = [
  284. 'id' => ($page - 1) * $limit + $i + 1,
  285. 'ids' => $item['img_id'] ?? '',
  286. 'path' => $path,
  287. // 实时数据
  288. 'status' => $data['dbStatus'],
  289. 'status_name' => $data['dbStatusName'],
  290. 'same_count' => $sameCountMap[$path] ?? 0,
  291. 'is_processed' => $data['isProcessed'] ? 1 : 0,
  292. 'queue_status' => $data['queueStatus'],
  293. 'taskId' => $item['taskId'] ?? '',
  294. 'new_image_url' => $item['new_image_url'] ?? '',
  295. 'custom_image_url' => $item['custom_image_url'] ?? '',
  296. 'imgtoimg_url' => $item['imgtoimg_url'] ?? '',
  297. 'chinese_description' => $item['chinese_description'] ?? '',
  298. 'english_description' => $item['english_description'] ?? '',
  299. 'img_name' => $item['img_name'] ?? '',
  300. // 来自缓存
  301. 'width' => $info['width'],
  302. 'height' => $info['height'],
  303. 'created_time' => $info['created_time']
  304. ];
  305. }
  306. return json([
  307. 'code' => 0,
  308. 'msg' => '获取成功',
  309. 'data' => $result,
  310. 'total' => $total,
  311. 'page' => $page,
  312. 'limit' => $limit
  313. ]);
  314. }
  315. /**
  316. * 通过服务器中获取对应目录
  317. */
  318. public function getlsit()
  319. {
  320. // 获取前端传入的图片路径参数
  321. $params = $this->request->param('path', '');
  322. // 查询数据库
  323. $res = Db::name('text_to_image')
  324. ->field('id,chinese_description,english_description,new_image_url,custom_image_url,size,old_image_url,img_name,model,imgtoimg_url')
  325. ->where('old_image_url', $params)
  326. ->where('img_name', '<>', '')
  327. ->order('id desc')
  328. ->select();
  329. return json(['code' => 0, 'msg' => '查询成功', 'data' => $res,'count'=>count($res)]);
  330. }
  331. /**
  332. * 图片上传
  333. */
  334. public function ImgUpload()
  335. {
  336. // 处理 CORS OPTIONS 预检请求
  337. if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  338. header('Access-Control-Allow-Origin: *');
  339. header('Access-Control-Allow-Methods: POST, OPTIONS');
  340. header('Access-Control-Allow-Headers: Content-Type, Authorization');
  341. header('Access-Control-Max-Age: 86400');
  342. exit(204);
  343. }
  344. // 实际请求必须返回 CORS 头
  345. header('Access-Control-Allow-Origin: *');
  346. // 获取上传的文件
  347. $file = request()->file('image');
  348. if ($file) {
  349. // 指定目标目录(你想上传到的目录)
  350. $targetPath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'operate' . DS . 'ai' . DS . 'Preview';
  351. // 若目录不存在则创建
  352. if (!is_dir($targetPath)) {
  353. mkdir($targetPath, 0755, true);
  354. }
  355. // 移动文件到指定目录,并验证大小/格式
  356. $info = $file->validate([
  357. 'size' => 10485760, // 最大10MB
  358. 'ext' => 'jpg,png'
  359. ])->move($targetPath);
  360. if ($info) {
  361. $fileName = $info->getSaveName();
  362. $imageUrl = '/uploads/operate/ai/Preview/' . str_replace('\\', '/', $fileName);
  363. return json(['code' => 0, 'msg' => '成功', 'data' => ['url' => $imageUrl]]);
  364. } else {
  365. $res = $file->getError();
  366. return json(['code' => 1, 'msg' => '失败', 'data' => $res]);
  367. }
  368. }
  369. return json(['code' => 1, 'msg' => '没有文件上传', 'data' => null]);
  370. }
  371. /**
  372. * 打包图片(支持对象结构中的 path 字段)
  373. */
  374. public function packImagess()
  375. {
  376. try {
  377. $params = $this->request->post();
  378. $paths = $params['paths'] ?? [];
  379. if (empty($paths) || !is_array($paths)) {
  380. return json(['code' => 1, 'msg' => '路径参数不能为空或格式不正确']);
  381. }
  382. // 提取所有合法的路径(支持字符串或对象中带 path 字段)
  383. $validPaths = [];
  384. foreach ($paths as $item) {
  385. if (is_string($item)) {
  386. $validPaths[] = $item;
  387. } elseif (is_array($item) && isset($item['path']) && is_string($item['path'])) {
  388. $validPaths[] = $item['path'];
  389. }
  390. }
  391. if (empty($validPaths)) {
  392. return json(['code' => 1, 'msg' => '没有有效的图片路径']);
  393. }
  394. // 设置基本路径和 zip 目录
  395. $basePath = ROOT_PATH . 'public/';
  396. $zipDir = $basePath . 'uploads/operate/ai/zip/';
  397. if (!is_dir($zipDir)) {
  398. mkdir($zipDir, 0755, true);
  399. }
  400. // 生成压缩文件路径
  401. $fileName = 'images_' . date('Ymd_His') . '.zip';
  402. $zipPath = $zipDir . $fileName;
  403. $zip = new \ZipArchive();
  404. if ($zip->open($zipPath, \ZipArchive::CREATE) !== TRUE) {
  405. return json(['code' => 1, 'msg' => '无法创建压缩包']);
  406. }
  407. $addCount = 0;
  408. foreach ($validPaths as $relativePath) {
  409. $relativePath = ltrim($relativePath, '/'); // 去除前导斜杠
  410. $fullPath = $basePath . $relativePath;
  411. if (file_exists($fullPath)) {
  412. // 使用 basename 作为压缩包内的文件名(不保留路径结构)
  413. $zip->addFile($fullPath, basename($fullPath));
  414. $addCount++;
  415. }
  416. }
  417. $zip->close();
  418. if ($addCount === 0) {
  419. @unlink($zipPath);
  420. return json(['code' => 1, 'msg' => '未找到有效图片文件,未生成压缩包']);
  421. }
  422. $downloadUrl = request()->domain() . '/uploads/operate/ai/zip/' . $fileName;
  423. return json([
  424. 'code' => 0,
  425. 'msg' => '打包成功',
  426. 'download_url' => $downloadUrl
  427. ]);
  428. } catch (\Exception $e) {
  429. return json([
  430. 'code' => 1,
  431. 'msg' => '异常错误:' . $e->getMessage()
  432. ]);
  433. }
  434. }
  435. /**
  436. * 获取所有模版列表,并返回当前使用模版 ID
  437. */
  438. public function TemplateList()
  439. {
  440. $list = Db::name("template")->order('ids desc')->select();
  441. return json([
  442. 'code' => 0,
  443. 'msg' => '模版列表',
  444. 'data' => [
  445. 'list' => $list,
  446. 'usedId' => Db::name("template")->where('ids', 1)->value('id')
  447. ]
  448. ]);
  449. }
  450. /**
  451. * 查询使用模版
  452. */
  453. public function Template_ids(){
  454. $Template = Db::name("template")->where('ids',1)->find();
  455. return json([
  456. 'code' => 0,
  457. 'msg' => '模版',
  458. 'data' => $Template
  459. ]);
  460. }
  461. /**
  462. * 查询模版
  463. */
  464. public function Template()
  465. {
  466. $id = Request::instance()->param('id');
  467. if (!$id) {
  468. return json(['code' => 1, 'msg' => '参数错误']);
  469. }
  470. $template = Db::name("template")->where('id', $id)->find();
  471. return json([
  472. 'code' => 0,
  473. 'msg' => '模版详情',
  474. 'data' => $template
  475. ]);
  476. }
  477. /**
  478. * 更新模版
  479. */
  480. public function updatetemplate()
  481. {
  482. if (!Request::instance()->isPost()) {
  483. return json(['code' => 1, 'msg' => '非法请求']);
  484. }
  485. $params = Request::instance()->post();
  486. if (empty($params['textareaContent']) || empty($params['width']) || empty($params['height'])) {
  487. return json(['code' => 1, 'msg' => '参数缺失']);
  488. }
  489. $data = [
  490. 'english_content' => $params['english_content'],
  491. 'content' => $params['textareaContent'],
  492. 'width' => $params['width'],
  493. 'height' => $params['height'],
  494. ];
  495. if (!empty($params['id'])) {
  496. // 更新已有模版
  497. Db::name("template")->where('id', $params['id'])->update($data);
  498. } else {
  499. // 新增模版,默认设为备用
  500. $data['ids'] = 0;
  501. Db::name("template")->insert($data);
  502. }
  503. return json(['code' => 0, 'msg' => '保存成功']);
  504. }
  505. /**
  506. * 设置默认使用模版
  507. */
  508. public function setActiveTemplate()
  509. {
  510. $id = Request::instance()->param('id');
  511. if (!$id) {
  512. return json(['code' => 1, 'msg' => '参数错误']);
  513. }
  514. Db::name("template")->where('ids', 1)->update(['ids' => 0]); // 清除当前使用
  515. Db::name("template")->where('id', $id)->update(['ids' => 1]); // 设置新的使用模版
  516. return json(['code' => 0, 'msg' => '模版已设为当前使用']);
  517. }
  518. /**
  519. * 文生图查询模型列表
  520. */
  521. public function txttoimg_moxing(){
  522. $list = Db::name("moxing")->order('id asc')->select();
  523. return json([
  524. 'code' => 0,
  525. 'msg' => '模版列表',
  526. 'data' => [
  527. 'list' => $list,
  528. 'usedId' => Db::name("moxing")->where('txttoimg_val', 1)->value('id')
  529. ]
  530. ]);
  531. }
  532. /**
  533. * 文生图设置默认使用模型
  534. * txttoimg_val = 1 默认使用
  535. */
  536. public function txttoimg_update(){
  537. $id = Request::instance()->param('id');
  538. if (!$id) {
  539. return json(['code' => 1, 'msg' => '参数错误']);
  540. }
  541. Db::name("moxing")->where('txttoimg_val', 1)->update(['txttoimg_val' => 0]); // 清除当前使用
  542. Db::name("moxing")->where('id', $id)->update(['txttoimg_val' => 1]); // 设置新的使用模型
  543. return json(['code' => 0, 'msg' => '模版已设为当前使用']);
  544. }
  545. }