Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9c7b695081 | ||
|
|
edfbb67cdb | ||
|
|
254a939f55 | ||
|
|
bf69419c68 | ||
|
|
d6b1989a4c | ||
|
|
f0a59e6642 | ||
|
|
a793eadb32 | ||
|
|
d9c61306fe | ||
|
|
ecb28c3aa5 | ||
|
|
c25f8b474c | ||
|
|
cac9484861 | ||
|
|
4dcc908eaa | ||
|
|
67f8a8f708 | ||
|
|
3c3d834806 | ||
|
|
fa989d0220 | ||
|
|
b6e0c475d3 | ||
|
|
76d9d45770 | ||
|
|
6e086d629d | ||
|
|
c59791f994 | ||
|
|
58900d0d45 | ||
|
|
7d0023949b | ||
|
|
9c7c72e3e7 | ||
|
|
e17b78cd19 | ||
|
|
f07cf7a266 |
No files matched your search
+117
@@ -1,5 +1,122 @@
|
|||||||
# 更新日志
|
# 更新日志
|
||||||
|
|
||||||
|
## 2026-11-19 → v1.4.14
|
||||||
|
|
||||||
|
- ✨ **灯箱只显示图片**:双击图片打开灯箱后,底部缩略图条只列出当前文件夹(含筛选)下的图片,mp4/md 等打不开的文件不再混入(此前显示出来也点不开,纯属干扰)
|
||||||
|
- 灯箱列表本身也同步过滤为纯图片:左右方向键/箭头按钮翻页不会再翻到视频、文档等打不开的项;顶部「序号 / 总数」与缩略图条均按图片计数
|
||||||
|
- 视频、文档的行为不变:双击仍弹出各自的播放/查看器,不进灯箱
|
||||||
|
- 🔧 **新增「素材」目录挂载**:docker-compose.yml 与 README(compose / docker run 两种方式)补挂载 `/vol2/1000/HD2/素材`,该目录可正常添加为素材库(此前报「素材库路径不存在」)
|
||||||
|
- 🔧 **新增「学习资料」目录挂载**:docker-compose.yml 与 README(compose / docker run 两种方式)补挂载 `/vol2/1000/HD2/学习资料`(同上修复「素材库路径不存在」,端到端建库验证通过)
|
||||||
|
- 🔧 **挂载方式升级为整盘**:`/vol2/1000/HD2` 下 5 个逐目录挂载合并为一行整盘挂载 `- /vol2/1000/HD2:/vol2/1000/HD2` —— 该盘下任意子目录(含以后在飞牛上新建的文件夹)可直接在页面添加为素材库,不再需要改配置重启;README compose / docker run 示例同步简化
|
||||||
|
|
||||||
|
## 2026-11-20 → v1.4.15
|
||||||
|
|
||||||
|
- 🐛 **修复「部分目录图片双击不弹出灯箱」**:`getOriginalUrl`/`getThumbnailUrl` 未对含中文/空格/#/? 的路径做 URL 编码,原图请求 404 → 灯箱图片加载失败 → 用户感知「双击不弹」。按 `/` 分段 `encodeURIComponent` 修复,灯箱/新窗口打开/导出/编辑 全链路受益
|
||||||
|
|
||||||
|
- ✨ **灯箱底部新增缩略图条**:双击图片放大后,底部列出当前文件夹(含筛选结果)的全部图片缩略图,点任意一张直接跳转查看,不用一张张翻
|
||||||
|
- 缩略图条显示「当前序号 / 总数」,当前图紫色高亮并自动滚动居中;切图时(含左右方向键/箭头按钮)缩略图条同步跟随
|
||||||
|
- 缩略图走原 thumbnail 缩略图接口全量加载(弹层滚动容器内不使用 lazy,避免 Chromium 中永不加载),无缩略图的文件显示格式角标兜底
|
||||||
|
- 缩略图条通过 portal 挂到 body、层级压在灯箱(z-index 2000)之上,不被祖先层叠上下文遮挡;数据与灯箱图片列表同源同序,跳转序号严格对齐
|
||||||
|
- ✨ **幻灯片播放**:缩略图条左侧新增 ▶ 播放 / ⏸ 暂停按钮,开启后按选定间隔自动切下一张,放完最后一张循环回首张;手动点缩略图或用箭头切图时计时器重新计时,每张图都停留满一个间隔;关闭灯箱自动停播
|
||||||
|
- 切换间隔可选 1 / 2 / 3 / 5 / 10 秒(下拉选择),选择存 localStorage 下次沿用,默认 3 秒
|
||||||
|
- 修复缩略图破图:后端对部分视频缩略图返回 0 字节 webp 导致浏览器显示碎图,加载失败自动退化为格式角标
|
||||||
|
|
||||||
|
## 2026-11-19 → v1.4.12
|
||||||
|
|
||||||
|
- ✨ **设置 → AI 生图新增「免费生图:Cloudflare Workers AI 提供商」说明卡**:标注每日免费额度(10000 neurons/天,北京时间 08:00 重置,FLUX.1 schnell 约 10 neurons/张 ≈ 每天约 1000 张),并给出两步申请地址——① 注册 Cloudflare 账号(免费、无需信用卡)② 创建 API Token(Workers AI Run 权限),含 Token 创建提示
|
||||||
|
- 顶部简介同步补充免费额度入口提示
|
||||||
|
|
||||||
|
## 2026-11-19 → v1.4.11
|
||||||
|
|
||||||
|
- ✨ **AI 生图弹窗新增「生图模型」点选**:按通道分组列出全部可选模型(CF Workers AI / Pollinations),点一下即选中并高亮,所选模型存 localStorage 下次沿用;自定义提供商则显示设置里配置的模型
|
||||||
|
- 生成时把所选模型带给后端(effModel = 前端所选 > 设置默认),后端加模型白名单校验,未知模型名直接 400
|
||||||
|
- 选了参考图时提示会自动切 FLUX.2 图生图模型;右上角保留「通道设置」入口
|
||||||
|
|
||||||
|
## 2026-11-19 → v1.4.10
|
||||||
|
|
||||||
|
- ✨ **提示词全中文化**:40 条图片预设新增中文详细提示词 promptCn(主体+场景+光线+构图+风格+质量),预设卡片、悬浮提示、点击填入全部显示中文;英文 prompt 字段保留作对照与翻译兜底
|
||||||
|
- ✨ 发送时沿用后台自动中译英链路(translatePromptToEnglish),实测中文提示词 7.3 秒翻译并出图成功
|
||||||
|
- 视频弹窗 6 条脚本提示词本就为中文,无需改动
|
||||||
|
|
||||||
|
## 2026-11-19 → v1.4.9
|
||||||
|
|
||||||
|
**AI 生图配置统一到设置 + 提示词全中文化**——模型与通道配置不再在弹窗里重复出现,提示词所见即中文:
|
||||||
|
|
||||||
|
- ✨ **配置去重**:AI 生图弹窗移除「模型提供商」「模型」两个下拉(与右上角设置重复);通道/模型统一在「设置 → AI 生图」配置,弹窗内只留一句「通道与模型在右上角设置里配置」+「去设置」直达按钮
|
||||||
|
- ✨ **设置 → AI 生图新增「默认模型」下拉**(内置 NewAPI 通道):按分组列出 CF Workers AI / Pollinations 模型,与自定义提供商的模型名同在设置页;选参考图时后端自动切 FLUX.2 图生图模型,用户无需手动换模型
|
||||||
|
- ✨ **提示词中文化**:热门提示词按钮显示中文名、点击替换(不追加)输入框;发送前提示词原样传给后端,由后端经聊天模型翻译成英文再发上游(多模型兜底,翻译失败回落原文)
|
||||||
|
- 🐛 修复生图翻译调用早于 `effUrl/effKey` 声明导致的运行时引用错误(TDZ)
|
||||||
|
- 🎨 AI 生图/AI 一键生成视频弹窗改为默认全屏显示
|
||||||
|
- 🐛 所有弹窗仅通过关闭按钮关闭,点击遮罩不再关闭(防误触丢失提示词/参考图)
|
||||||
|
- ✨ **提示词全面详细化**:40 条图片预设从短标签扩写为完整出图提示词(主体+场景+光线+构图+风格+质量,平均 200+ 字符);预设卡片直接显示详细描述(两行预览),点击填入完整提示词而非名称;6 条视频脚本提示词扩为含镜头语言与节奏的完整脚本框架
|
||||||
|
|
||||||
|
## 2026-11-18 → v1.4.8
|
||||||
|
|
||||||
|
**搜索结果批量改名 + 关键词替换**——搜索出一批文件后直接对命中结果批量改名,支持把文件名中的关键词替换掉:
|
||||||
|
|
||||||
|
- ✨ **搜索结果入口**:任意搜索(Header 搜索框,模糊匹配文件名+OCR 文本)后,结果区顶部出现「批量重命名搜索结果…」按钮;打开弹窗头部徽标显示当前搜索词,范围与搜索列表完全一致(选中文件夹时含其子目录,未选中则全库)
|
||||||
|
- ✨ **新重命名模式「关键词替换」**:找什么→替换成(文件名中所有出现处全部替换);**替换成留空 = 删除该关键词**;不含关键词的文件自动跳过并在结果中报告;预览实时显示替换前后对照
|
||||||
|
- ✨ 搜索范围与列表同款 `LIKE` 模糊匹配(多关键词 AND、filename+ocr_text),后端 `POST /api/batch/rename-preview` 与 `/start` 新增 `scope='search'` + `keywords` 参数(folder 可不传,传了则按文件夹递归限定范围)
|
||||||
|
- ✨ 弹窗模式改 2×2 布局(4 种模式);关键词模式下隐藏「包含子目录」开关(搜索范围本身就含子目录);文件夹右键入口的原有三种模式行为不变
|
||||||
|
- 🎨 顶栏副标题「轻量快速的图片素材库管理」→「轻量快速的素材库管理」(去「图片」二字,与全站文件类型通用化口径一致)
|
||||||
|
- 🛡️ 关键词与替换文本同样走文件名非法字符 `\ / : * ? " < > |` 前后端校验;预览与执行共用同一计划(命中数、跳过原因一致)
|
||||||
|
- 端到端实测:preview/scope=search 预览命中数、keyword 执行改名+DB path 同步、搜索态按钮与弹窗渲染
|
||||||
|
|
||||||
|
## 2026-11-18 → v1.4.7
|
||||||
|
|
||||||
|
**文件类型自动识别(通用机制)**——原先统计卡、文件夹卡、多选条等多处硬编码「图片/N 张图片」,库里实际有图片/视频/文档三种类型(356 个文件被显示成「356 图片总数」)。现改为类型注册表驱动,**以后新增文件类型只需在注册表加一行,全站文案与统计自动识别**:
|
||||||
|
|
||||||
|
- ✨ 新建 `frontend/src/utils/fileTypes.js` 类型注册表:image→图片/张、video→视频/个、document→文档/个、audio→音频/个,未知类型一律兜底「文件/个」;提供 `typeMeta`(单文件元信息)、`countLabel`(集合计数文案:单一类型→「102 张图片」,混合→「356 个文件」)、`typeLabelOf`(动词名词:复制图片/复制视频/复制文件自动切换)、`typeCountsOf`(从选中项聚合类型计数)
|
||||||
|
- ✨ 统计卡自动识别:图标与标题按库内实际类型显示(纯图库「图片总数」、混合库「文件总数」),下方分类型图例「图片 102 · 视频 181 · 文档 73」由注册表自动渲染,新类型自动出现
|
||||||
|
- ✨ 文件夹卡与仪表盘提示句:「X 张图片」→ 按该文件夹实际内容显示(`countLabel`,含子目录分类型聚合,后端 `FolderModel.getTree()` 新增 `_attachTypeCounts`)
|
||||||
|
- ✨ 后端 `GET /api/image/stats` 新增 `typeCounts` 字段(按 file_type 分组计数)
|
||||||
|
- ✨ 右侧面板全部计数与动词文案通用化:已选择/基本信息/共同父路径/已复制/复制按钮/导出按钮 —— 消除 v1.4.4 的 `selectionHasVideo ? ... : ...` 硬编码分支(该变量已删除,零引用),选中集合含视频→「个文件/复制视频」、纯图→「张图片/复制图片」、文档→「复制文档」全自动
|
||||||
|
- ✨ 多选工具条「已选 X 张图片」→ 按选中项类型自动(混合「个文件」);批量加水印「X 张图片」→「X 个文件」;扫描进度「X/Y 张图片」→「X/Y 个文件」;评分日志、双击查看 title 同步通用化
|
||||||
|
- 🔍 搜索框 placeholder「搜索图片...」→「搜索文件...」(搜索本就覆盖全类型,OCR 说明保留)
|
||||||
|
- ✨ **右侧面板文件夹信息区(原截图问题点)**:「包含图片: X 张(含子文件夹)」→「包含: X 个视频/张图片/个文件(含子文件夹)」(由该文件夹实际类型自动);「导出文件夹 (X 张)」同步按类型
|
||||||
|
- ✨ 加载进度「已加载 X/Y 张」→「已加载 X/Y 个文件」;评分 toast「(N 张)」→「(N 个)」;批量水印按钮「开始处理 N 张/该文件夹没有图片」→「开始处理 N 个文件/该文件夹没有可处理的文件」(与弹窗头部计数口径一致)
|
||||||
|
- ✨ 合拼入口过滤:多选点「合拼」只把图片送进画布(与 AI 生成视频入口同模式),视频/文档不参与,进入后由「至少需要 2 张图片」校验提示
|
||||||
|
- 保留(功能输入校验,非数据展示):AI 生成视频「请至少选择 2 张图片」、合拼「至少需要 2 张图片」——这两个功能的输入确实限图片,且入口均已有类型过滤
|
||||||
|
- ✨ 注册表与后端分类器完全对齐(backend thumbnail.js getFileType 共 6 类):补 design「设计」(psd/ai/sketch/fig…) 与 other「其他」两行——此前这两个类型在统计卡图例都兜底成「文件」导致出现两个重复的「文件 N」(如「我的素材」库 文件5/文件8);图例改按注册表固定顺序展示(orderedTypeEntries)
|
||||||
|
- 端到端实测:stats.typeCounts 正确、统计卡图例/文件夹卡「5 个视频」/右侧面板文件夹信息区/多选条浏览器核验
|
||||||
|
|
||||||
|
## 2026-11-18 → v1.4.6
|
||||||
|
|
||||||
|
- ✨ **文件夹右键新增「批量重命名文件」**:三种模式 —— 前面加(前缀)、后面加(后缀)、全部改名(原文件名整体替换,扩展名始终保留)
|
||||||
|
- ✨ 支持**包含子目录**开关,递归处理所有层级文件(默认开启,可只改当前文件夹)
|
||||||
|
- ✨ 弹窗**实时预览**改名效果(输入文本后即时显示每个文件的新旧文件名对照与总数)
|
||||||
|
- 🛡️ 全部改名模式同目录多个文件**自动编号**(文本-001、文本-002…,每个子目录独立编号;单文件不编号),避免撞名
|
||||||
|
- 🛡️ 冲突保护:目标文件名已存在(含本次内重复)自动跳过并在结果中报告;文本含文件名非法字符 `\ / : * ? " < > |` 前后端双重校验
|
||||||
|
- ⚡️ 复用批量水印异步任务体系:进度条、可停止(已完成的保留)、完成统计(已重命名/已跳过/失败 + 失败明细)
|
||||||
|
- 🔒 重命名后同步更新数据库记录(path/filename);缩略图按内容 hash 存储、与文件名无关,无需重建;旧路径零残留
|
||||||
|
- 后端新增 `POST /api/batch/rename-preview` 预览接口;`POST /api/batch/start` 的 type 扩展 `rename`
|
||||||
|
- 端到端实测:preview 三模式(含子目录/不含子目录/自动编号)、非法字符 400、suffix/prefix 实际执行 FS+DB 一致、浏览器 UI 右键菜单→弹窗→预览→执行→完成全流程
|
||||||
|
|
||||||
|
## 2026-11-18 → v1.4.5
|
||||||
|
|
||||||
|
**优化:侧栏文件夹按日期倒序,最新的文件夹排最前**——原先侧栏/仪表盘文件夹顺序来自后端 `SELECT ... ORDER BY path`(名称字典序升序),最旧的文件夹排最前,最新日期沉底。现改为在 `FolderModel.getTree()` 按文件夹名解析出的真实日期倒序排序:
|
||||||
|
|
||||||
|
- 兼容两种命名格式混排:`YYYY-MM-DD` 与 `YYYYMMDD`(原纯字符串倒序会把 `20261016` 压过 `2026-11-18`,日期顺序错乱;`_归档` 还会因首字符 `_` 排到最前)
|
||||||
|
- 无法解析为日期的文件夹(如 `_归档`、`1217`)排在所有日期文件夹之后,组内按名称倒序
|
||||||
|
- 子文件夹同样按日期倒序
|
||||||
|
- 侧栏与仪表盘(Dashboard)共用同一接口数据,同步生效
|
||||||
|
|
||||||
|
## 2026-11-18 → v1.4.4
|
||||||
|
|
||||||
|
**修复:选中视频文件,右侧详情面板仍显示图片信息**——根因是 `RightPanel.jsx` 全组件没有任何视频判定(`fileType === 'video'`),预览区把视频当图片渲染缩略图、底部按钮硬编码「编辑图片 / 复制图片 / 导出图片」,点「编辑图片」还会把视频塞进图片编辑器。修复:
|
||||||
|
|
||||||
|
- **预览区**:视频改为直接播放原文件(`<video controls>`,缩略图作 poster),不再以图片形式展示
|
||||||
|
- **按钮按类型分流**:单选视频显示「编辑视频 / 复制视频 / 导出视频」——「编辑视频」打开视频编辑弹窗(水印/字幕声音),「复制视频」只写应用内剪贴板(视频无法转成图片写系统剪贴板,原先会走失败兜底弹 alert)
|
||||||
|
- **新增时长字段**:视频详情显示「时长: m:ss」(取 `duration` 字段,与瀑布流角标同格式)
|
||||||
|
- **多选文案**:选中集合含视频时,「已选择 N 张图片 / 数量 N 张图片 / 复制图片 / 导出图片」等改为「个文件 / 复制文件 / 导出文件」,计数单位「张」→「个」
|
||||||
|
- **弹窗状态提升**:视频编辑弹窗状态从 `ImageWaterfall` 局部 state 提升到 `useUIStore`,弹窗渲染移到 App 层——原先只挂在 `ImageWaterfall` 内,而该组件在 Dashboard 视图下不渲染,某些页面点编辑视频弹窗不会出现;右侧面板与右键菜单现共用同一入口,不再重复挂载
|
||||||
|
|
||||||
|
## 2026-11-18 → v1.4.3
|
||||||
|
|
||||||
|
**优化**:侧栏首项文案「全部图片」改为「全部」(`Sidebar.jsx`)。
|
||||||
|
|
||||||
|
**修复:视频编辑/AI 生成视频点「开始处理」报 `[object Object]`、功能完全不可用**——根因是两处裸 `fetch` 调用没带登录态:`VideoEditModal.jsx`(`/api/video/edit`)与 `AIVideoModal.jsx`(`/api/video/aigenerate`、`/api/video/task/:id`)均未附 `Authorization` 头,而后端 `/api` 全组走认证中间件,一律 401 拒绝;前端又把 `{code, message}` 错误对象直接 `new Error()`,对象转字符串就成了 `[object Object]`。修复:三处请求补 `Authorization: `Bearer ${getToken()}`(与图片编辑器等既有调用一致),错误信息统一经 `errText()` 解析(对象取 `message`,再兜底状态码),不再出现 `[object Object]`。另修复 `MergeCollage.jsx` 拼图找相似接口同样的缺 token 问题(历史遗留)。
|
||||||
|
|
||||||
## 2026-11-18 → v1.4.2
|
## 2026-11-18 → v1.4.2
|
||||||
|
|
||||||
**修复:添加素材库报 `Path does not exist`(视频目录)**——根因是该目录未挂载进容器(容器里看不到宿主机目录)。`docker-compose.yml` 已补挂载 `/vol2/1000/HD2/发布到平台的图片和视频`,README 使用注意新增排查方法(volumes 加一行同路径挂载后 `docker compose up -d`)。后端报错同步中文化:`素材库路径不存在: <路径>(如为宿主机目录,需先在 docker-compose.yml 的 volumes 里挂载进容器再重试)`(创建与更新两处)。
|
**修复:添加素材库报 `Path does not exist`(视频目录)**——根因是该目录未挂载进容器(容器里看不到宿主机目录)。`docker-compose.yml` 已补挂载 `/vol2/1000/HD2/发布到平台的图片和视频`,README 使用注意新增排查方法(volumes 加一行同路径挂载后 `docker compose up -d`)。后端报错同步中文化:`素材库路径不存在: <路径>(如为宿主机目录,需先在 docker-compose.yml 的 volumes 里挂载进容器再重试)`(创建与更新两处)。
|
||||||
|
|||||||
@@ -99,10 +99,8 @@ services:
|
|||||||
ports:
|
ports:
|
||||||
- "15002:15002"
|
- "15002:15002"
|
||||||
volumes:
|
volumes:
|
||||||
# 素材库目录(容器内路径与宿主机一致,中文路径直接填,按需增减)
|
# 数据盘整盘挂载(容器内路径与宿主机一致,中文路径直接填):盘下任意子目录含以后新建的,可直接添加为素材库
|
||||||
- /vol2/1000/HD2/壁纸:/vol2/1000/HD2/壁纸
|
- /vol2/1000/HD2:/vol2/1000/HD2
|
||||||
- /vol2/1000/HD2/我的文档:/vol2/1000/HD2/我的文档
|
|
||||||
- /vol2/1000/HD2/发布到平台的图片和视频:/vol2/1000/HD2/发布到平台的图片和视频
|
|
||||||
# 持久化配置(素材库列表、管理员密码,不用改)
|
# 持久化配置(素材库列表、管理员密码,不用改)
|
||||||
- /vol3/1000/HD3/docker/flypic/config:/root/.flypic
|
- /vol3/1000/HD3/docker/flypic/config:/root/.flypic
|
||||||
environment:
|
environment:
|
||||||
@@ -116,10 +114,10 @@ services:
|
|||||||
```
|
```
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 首次部署(编辑 volumes 换成你的素材库目录)
|
# 首次部署(编辑 volumes 把整盘或你的素材目录挂进来)
|
||||||
docker compose up -d --build
|
docker compose up -d --build
|
||||||
|
|
||||||
# 新增素材库:volumes 加一行挂载后重启
|
# 新增素材库:整盘挂载后直接在页面添加即可,无需改配置
|
||||||
docker compose up -d
|
docker compose up -d
|
||||||
|
|
||||||
# 更新代码
|
# 更新代码
|
||||||
@@ -142,14 +140,13 @@ docker run -d --name flypic --restart unless-stopped \
|
|||||||
-e FRONTEND_DIST=/app/backend/public \
|
-e FRONTEND_DIST=/app/backend/public \
|
||||||
-e NODE_ENV=production \
|
-e NODE_ENV=production \
|
||||||
-v /vol3/1000/HD3/docker/flypic/config:/root/.flypic \
|
-v /vol3/1000/HD3/docker/flypic/config:/root/.flypic \
|
||||||
-v /vol2/1000/HD2/壁纸:/vol2/1000/HD2/壁纸 \
|
-v "/vol2/1000/HD2:/vol2/1000/HD2" \
|
||||||
-v "/vol2/1000/HD2/发布到平台的图片和视频:/vol2/1000/HD2/发布到平台的图片和视频" \
|
|
||||||
jpccr.ccs.tencentyun.com/jinghui/flypic:latest
|
jpccr.ccs.tencentyun.com/jinghui/flypic:latest
|
||||||
```
|
```
|
||||||
|
|
||||||
- 公网镜像 `jpccr.ccs.tencentyun.com/jinghui/flypic:latest`(匿名可拉);内网镜像 `192.168.68.19:3200/jinghui/flypic:latest`
|
- 公网镜像 `jpccr.ccs.tencentyun.com/jinghui/flypic:latest`(匿名可拉);内网镜像 `192.168.68.19:3200/jinghui/flypic:latest`
|
||||||
- 没有镜像就本地构建:`docker build -t flypic:latest .`,替换上面的镜像名
|
- 没有镜像就本地构建:`docker build -t flypic:latest .`,替换上面的镜像名
|
||||||
- 素材库目录按需增减 `-v`(容器内路径与宿主机一致)
|
- 素材库挂载:推荐整盘 `-v "/数据盘:/数据盘"`(盘下任意子目录直接添加、免改配置),也可只挂需要的子目录 `-v`(容器内路径与宿主机一致)
|
||||||
|
|
||||||
## 📝 使用注意
|
## 📝 使用注意
|
||||||
|
|
||||||
|
|||||||
@@ -28,7 +28,68 @@ class FolderModel extends BaseModel {
|
|||||||
*/
|
*/
|
||||||
getTree() {
|
getTree() {
|
||||||
const folders = this.findAll();
|
const folders = this.findAll();
|
||||||
return this._buildTree(folders);
|
// 最新文件夹排最前:按文件夹名解析出的日期倒序(兼容 YYYY-MM-DD 与 YYYYMMDD 两种命名),
|
||||||
|
// 无法解析为日期的(如 _归档、纯数字名)排在日期文件夹之后
|
||||||
|
folders.sort((a, b) => {
|
||||||
|
const diff = this._dateKey(b.name) - this._dateKey(a.name);
|
||||||
|
if (diff !== 0) return diff;
|
||||||
|
return String(b.name).localeCompare(String(a.name));
|
||||||
|
});
|
||||||
|
return this._attachTypeCounts(this._buildTree(folders));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 给树中每个节点附着 typeCounts(按文件类型分组计数,含子目录)
|
||||||
|
* { image: 102, video: 181, document: 73 }
|
||||||
|
* 聚合范围与 updateImageCount 一致:本文件夹 + 所有子目录前缀
|
||||||
|
* 供前端类型注册表自动识别渲染(新增类型无需改代码)
|
||||||
|
*/
|
||||||
|
_attachTypeCounts(tree) {
|
||||||
|
let rows = [];
|
||||||
|
try {
|
||||||
|
rows = this.db.prepare(`
|
||||||
|
SELECT folder, file_type, COUNT(*) as c
|
||||||
|
FROM images
|
||||||
|
GROUP BY folder, file_type
|
||||||
|
`).all();
|
||||||
|
} catch {
|
||||||
|
return tree; // 查询失败时保持无 typeCounts,前端兜底"个文件"
|
||||||
|
}
|
||||||
|
const byFolder = new Map();
|
||||||
|
for (const r of rows) {
|
||||||
|
if (!byFolder.has(r.folder)) byFolder.set(r.folder, {});
|
||||||
|
const m = byFolder.get(r.folder);
|
||||||
|
const t = r.file_type || 'image';
|
||||||
|
m[t] = (m[t] || 0) + r.c;
|
||||||
|
}
|
||||||
|
const walk = (nodes) => {
|
||||||
|
for (const n of nodes) {
|
||||||
|
const counts = {};
|
||||||
|
for (const [f, m] of byFolder) {
|
||||||
|
if (f === n.path || f.startsWith(n.path + '/')) {
|
||||||
|
for (const [t, c] of Object.entries(m)) {
|
||||||
|
counts[t] = (counts[t] || 0) + c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
n.typeCounts = counts;
|
||||||
|
if (n.children && n.children.length) walk(n.children);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk(tree);
|
||||||
|
return tree;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将文件夹名解析为日期键(YYYYMMDD 整数),解析不出返回 0
|
||||||
|
*/
|
||||||
|
_dateKey(name) {
|
||||||
|
const m = String(name || '').match(/(\d{4})-?(\d{2})-?(\d{2})/);
|
||||||
|
if (!m) return 0;
|
||||||
|
const month = Number(m[2]);
|
||||||
|
const day = Number(m[3]);
|
||||||
|
if (month < 1 || month > 12 || day < 1 || day > 31) return 0;
|
||||||
|
return Number(m[1] + m[2] + m[3]);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+159
-15
@@ -7,7 +7,45 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
const express = require('express');
|
const express = require('express');
|
||||||
|
/** 文生图提示词翻译:含中文/非 ASCII 时先翻译成英文,失败则回落原文 */
|
||||||
|
const TEXT_TRANSLATE_MODELS = (process.env.AIGEN_TRANSLATE_MODEL || 'glm-5.3-flash,deepseek-v4.1-flash,mimo-v2.6-flash').split(',').map(s=>s.trim()).filter(Boolean);
|
||||||
|
async function translatePromptToEnglish(prompt, url, key) {
|
||||||
|
const p = String(prompt || '').trim();
|
||||||
|
if (!p || !/[\x80-\uFFFF]/.test(p)) return p; // 已是纯英文/ASCII,无需翻译
|
||||||
|
for (const model of TEXT_TRANSLATE_MODELS) {
|
||||||
|
try {
|
||||||
|
const ctrl = new AbortController();
|
||||||
|
const t = setTimeout(() => ctrl.abort(), 30000);
|
||||||
|
const resp = await fetch(`${url}/chat/completions`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Authorization': `Bearer ${key}`, 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
model,
|
||||||
|
messages: [
|
||||||
|
{ role: 'system', content: 'You are a translator. Translate the user prompt into concise, vivid English suitable for an image generation model. Output ONLY the English prompt, no quotes, no explanation.' },
|
||||||
|
{ role: 'user', content: p }
|
||||||
|
],
|
||||||
|
temperature: 0.2,
|
||||||
|
max_tokens: 300
|
||||||
|
}),
|
||||||
|
signal: ctrl.signal
|
||||||
|
});
|
||||||
|
clearTimeout(t);
|
||||||
|
if (!resp.ok) continue;
|
||||||
|
const d = await resp.json();
|
||||||
|
const out = (d && d.choices && d.choices[0] && d.choices[0].message && d.choices[0].message.content) || '';
|
||||||
|
const clean = String(out).trim().replace(/^["'`]+|["'`]+$/g, '');
|
||||||
|
if (clean) return clean;
|
||||||
|
} catch (e) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return p; // 全部失败回落原文
|
||||||
|
}
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
const { asyncHandler } = require('../middleware/errorHandler');
|
const { asyncHandler } = require('../middleware/errorHandler');
|
||||||
const logger = require('../utils/logger');
|
const logger = require('../utils/logger');
|
||||||
const { getSettings } = require('../../utils/settings');
|
const { getSettings } = require('../../utils/settings');
|
||||||
@@ -38,6 +76,67 @@ const BUILTIN_GROUPS = [
|
|||||||
|
|
||||||
const ALLOWED_SIZES = ['1024x1024', '1280x720', '720x1280', '1536x1024', '1024x1536'];
|
const ALLOWED_SIZES = ['1024x1024', '1280x720', '720x1280', '1536x1024', '1024x1536'];
|
||||||
|
|
||||||
|
// 以图生图(图片编辑)支持的模型:FLUX.2 系列走 /v1/images/edits 的 multipart 上传
|
||||||
|
const EDIT_MODELS = [
|
||||||
|
{ id: 'flux-2', name: 'FLUX.2 [dev](图生图)' },
|
||||||
|
{ id: 'flux-2-klein', name: 'FLUX.2 Klein 9B(图生图·快)' },
|
||||||
|
{ id: 'flux-2-klein-4b', name: 'FLUX.2 Klein 4B(图生图·最省)' }
|
||||||
|
];
|
||||||
|
|
||||||
|
// 文生图允许的模型(内置分组 + 图生图专用),防止任意模型名打到上游
|
||||||
|
const ALLOWED_MODELS = new Set([
|
||||||
|
...BUILTIN_GROUPS.flatMap((g) => g.models.map((m) => m.id)),
|
||||||
|
...EDIT_MODELS.map((m) => m.id)
|
||||||
|
]);
|
||||||
|
|
||||||
|
const REF_EXTS = new Set(['.jpg', '.jpeg', '.png', '.webp', '.bmp', '.avif', '.gif']);
|
||||||
|
const MAX_REFS = 4;
|
||||||
|
const MIME_BY_EXT = {
|
||||||
|
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png',
|
||||||
|
'.webp': 'image/webp', '.bmp': 'image/bmp', '.avif': 'image/avif', '.gif': 'image/gif'
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 归一化基础地址 -> 完整 images/edits URL */
|
||||||
|
function normalizeEditUrl(url) {
|
||||||
|
let u = String(url || '').trim().replace(/\/+$/, '');
|
||||||
|
if (/\/images\/edits$/.test(u)) return u;
|
||||||
|
if (/\/images\/generations$/.test(u)) return u.replace(/\/images\/generations$/, '/images/edits');
|
||||||
|
if (/\/v1$/.test(u)) return u + '/images/edits';
|
||||||
|
if (/\/chat\/completions$/.test(u)) return u.replace(/\/chat\/completions$/, '/images/edits');
|
||||||
|
return u + '/v1/images/edits';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从素材库读取参考图(以图生图用)
|
||||||
|
* refs 支持 ['a.jpg'] 或 [{ path|filename }]
|
||||||
|
*/
|
||||||
|
function loadRefImages(req, libraryId, refs) {
|
||||||
|
const list = Array.isArray(refs) ? refs.filter(Boolean).slice(0, MAX_REFS) : [];
|
||||||
|
if (list.length === 0) return [];
|
||||||
|
const configManager = req.app.get('configManager');
|
||||||
|
if (!configManager) throw new Error('服务未初始化');
|
||||||
|
const config = configManager.load();
|
||||||
|
const library = (config.libraries || []).find((l) => String(l.id) === String(libraryId));
|
||||||
|
if (!library) throw new Error('素材库不存在,请重新选择参考图');
|
||||||
|
|
||||||
|
const out = [];
|
||||||
|
for (const item of list) {
|
||||||
|
const rel = typeof item === 'string' ? item : (item.path || item.filename);
|
||||||
|
if (!rel) continue;
|
||||||
|
const abs = path.resolve(path.join(library.path, rel));
|
||||||
|
if (!abs.startsWith(path.resolve(library.path))) throw new Error('参考图路径非法');
|
||||||
|
if (!fs.existsSync(abs)) throw new Error(`参考图不存在: ${rel}`);
|
||||||
|
const ext = path.extname(abs).toLowerCase();
|
||||||
|
if (!REF_EXTS.has(ext)) throw new Error(`不是图片文件: ${rel}(只能选图片做参考图)`);
|
||||||
|
out.push({
|
||||||
|
name: path.basename(abs),
|
||||||
|
mime: MIME_BY_EXT[ext] || 'application/octet-stream',
|
||||||
|
buf: fs.readFileSync(abs)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
/** 归一化基础地址 -> 完整 images/generations URL */
|
/** 归一化基础地址 -> 完整 images/generations URL */
|
||||||
function normalizeGenUrl(url) {
|
function normalizeGenUrl(url) {
|
||||||
let u = String(url || '').trim().replace(/\/+$/, '');
|
let u = String(url || '').trim().replace(/\/+$/, '');
|
||||||
@@ -70,7 +169,7 @@ function resolveProvider(settings) {
|
|||||||
url: (ig.newapi && ig.newapi.url) || 'http://192.168.68.19:3099/v1',
|
url: (ig.newapi && ig.newapi.url) || 'http://192.168.68.19:3099/v1',
|
||||||
// 内置 key 优先取设置里填的,其次取服务器环境变量
|
// 内置 key 优先取设置里填的,其次取服务器环境变量
|
||||||
apiKey: (ig.newapi && ig.newapi.apiKey) || process.env.NEWAPI_KEY || '',
|
apiKey: (ig.newapi && ig.newapi.apiKey) || process.env.NEWAPI_KEY || '',
|
||||||
model: '',
|
model: (ig.newapi && ig.newapi.model) || 'flux-schnell',
|
||||||
label: 'NewAPI(Pollinations + CF Workers AI)'
|
label: 'NewAPI(Pollinations + CF Workers AI)'
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -87,10 +186,12 @@ router.get('/models', asyncHandler(async (req, res) => {
|
|||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
groups: BUILTIN_GROUPS,
|
groups: BUILTIN_GROUPS,
|
||||||
|
editModels: EDIT_MODELS,
|
||||||
sizes: ALLOWED_SIZES,
|
sizes: ALLOWED_SIZES,
|
||||||
provider: {
|
provider: {
|
||||||
type: cur.provider,
|
type: cur.provider,
|
||||||
label: cur.label,
|
label: cur.label,
|
||||||
|
builtinModel: cur.model || 'flux-schnell',
|
||||||
url: cur.url,
|
url: cur.url,
|
||||||
apiKeyMasked: maskKey(cur.apiKey),
|
apiKeyMasked: maskKey(cur.apiKey),
|
||||||
hasKey: !!cur.apiKey,
|
hasKey: !!cur.apiKey,
|
||||||
@@ -109,7 +210,12 @@ router.get('/models', asyncHandler(async (req, res) => {
|
|||||||
*/
|
*/
|
||||||
router.post('/generate', asyncHandler(async (req, res) => {
|
router.post('/generate', asyncHandler(async (req, res) => {
|
||||||
const t0 = Date.now();
|
const t0 = Date.now();
|
||||||
const { prompt, model, size, provider } = req.body || {};
|
const { prompt, model, size, provider, libraryId } = req.body || {};
|
||||||
|
// 文生图:中文提示词先翻译成英文再发给上游(图生图同样翻译)
|
||||||
|
const originalPrompt = String(prompt || '').trim();
|
||||||
|
|
||||||
|
// 参考图(以图生图):兼容 refImages / refs / refPaths 三种字段
|
||||||
|
const rawRefs = (req.body && (req.body.refImages || req.body.refs || req.body.refPaths)) || [];
|
||||||
|
|
||||||
if (!prompt || !String(prompt).trim()) {
|
if (!prompt || !String(prompt).trim()) {
|
||||||
return res.status(400).json({ success: false, error: '提示词不能为空' });
|
return res.status(400).json({ success: false, error: '提示词不能为空' });
|
||||||
@@ -136,30 +242,62 @@ router.post('/generate', asyncHandler(async (req, res) => {
|
|||||||
if (!effKey) {
|
if (!effKey) {
|
||||||
return res.status(400).json({ success: false, error: '未配置 NewAPI Key,请到设置 → AI 生图填写' });
|
return res.status(400).json({ success: false, error: '未配置 NewAPI Key,请到设置 → AI 生图填写' });
|
||||||
}
|
}
|
||||||
if (!effModel) effModel = 'flux-schnell';
|
if (effModel && !ALLOWED_MODELS.has(effModel)) {
|
||||||
|
return res.status(400).json({ success: false, error: `未知模型: ${effModel}` });
|
||||||
|
}
|
||||||
|
effModel = effModel || cur.model || 'flux-schnell'; // 默认模型统一在设置 → AI 生图里配
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const effPrompt = await translatePromptToEnglish(originalPrompt, effUrl, effKey);
|
||||||
const effSize = ALLOWED_SIZES.includes(size) ? size : '1024x1024';
|
const effSize = ALLOWED_SIZES.includes(size) ? size : '1024x1024';
|
||||||
const genUrl = normalizeGenUrl(effUrl);
|
|
||||||
|
|
||||||
logger.info(`[aigen] generate model=${effModel} size=${effSize} provider=${useCustom ? 'custom' : 'builtin'} prompt=${String(prompt).slice(0, 60)}`);
|
// 读取参考图(有参考图 = 以图生图,走图片编辑接口)
|
||||||
|
let refs = [];
|
||||||
|
if (rawRefs && (Array.isArray(rawRefs) ? rawRefs.length : true)) {
|
||||||
|
try {
|
||||||
|
refs = loadRefImages(req, libraryId, rawRefs);
|
||||||
|
} catch (e) {
|
||||||
|
return res.status(400).json({ success: false, error: e.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const isEdit = refs.length > 0;
|
||||||
|
// 前端不再选模型:有参考图且内置模型不支持编辑时,自动切到图生图模型
|
||||||
|
if (isEdit && !useCustom && !['flux-2', 'flux-2-klein'].includes(effModel)) {
|
||||||
|
effModel = 'flux-2';
|
||||||
|
}
|
||||||
|
const targetUrl = isEdit ? normalizeEditUrl(effUrl) : normalizeGenUrl(effUrl);
|
||||||
|
|
||||||
|
logger.info(`[aigen] ${isEdit ? 'edit' : 'generate'} model=${effModel} size=${effSize} refs=${refs.length} provider=${useCustom ? 'custom' : 'builtin'} prompt=${String(effPrompt).slice(0, 60)} (orig: ${String(originalPrompt).slice(0, 40)})`);
|
||||||
|
|
||||||
const ctrl = new AbortController();
|
const ctrl = new AbortController();
|
||||||
const timer = setTimeout(() => ctrl.abort(), 150000); // 生图最长 150s
|
const timer = setTimeout(() => ctrl.abort(), isEdit ? 300000 : 150000); // 图生图更慢,最长 300s
|
||||||
let result;
|
let result;
|
||||||
try {
|
try {
|
||||||
const resp = await fetch(genUrl, {
|
let body;
|
||||||
method: 'POST',
|
let headers = { 'Authorization': `Bearer ${effKey}` };
|
||||||
headers: {
|
if (isEdit) {
|
||||||
'Authorization': `Bearer ${effKey}`,
|
const form = new FormData();
|
||||||
'Content-Type': 'application/json'
|
form.append('model', String(effModel || 'flux-2'));
|
||||||
},
|
form.append('prompt', String(effPrompt));
|
||||||
body: JSON.stringify({
|
form.append('n', '1');
|
||||||
|
form.append('size', effSize);
|
||||||
|
refs.forEach((r, i) => {
|
||||||
|
form.append(i === 0 ? 'image' : `image_${i}`, new Blob([r.buf], { type: r.mime }), r.name);
|
||||||
|
});
|
||||||
|
body = form;
|
||||||
|
} else {
|
||||||
|
headers['Content-Type'] = 'application/json';
|
||||||
|
body = JSON.stringify({
|
||||||
model: effModel,
|
model: effModel,
|
||||||
prompt: String(prompt),
|
prompt: String(effPrompt),
|
||||||
n: 1,
|
n: 1,
|
||||||
size: effSize
|
size: effSize
|
||||||
}),
|
});
|
||||||
|
}
|
||||||
|
const resp = await fetch(targetUrl, {
|
||||||
|
method: 'POST',
|
||||||
|
headers,
|
||||||
|
body,
|
||||||
signal: ctrl.signal
|
signal: ctrl.signal
|
||||||
});
|
});
|
||||||
const text = await resp.text();
|
const text = await resp.text();
|
||||||
@@ -171,6 +309,9 @@ router.post('/generate', asyncHandler(async (req, res) => {
|
|||||||
if (j.error && j.error.message) msg = j.error.message;
|
if (j.error && j.error.message) msg = j.error.message;
|
||||||
else if (j.message) msg = j.message;
|
else if (j.message) msg = j.message;
|
||||||
} catch (e) { /* 保留默认信息 */ }
|
} catch (e) { /* 保留默认信息 */ }
|
||||||
|
if (isEdit && /not found|404|not support|unsupported|invalid model/i.test(msg + ' ' + resp.status)) {
|
||||||
|
msg += '(当前模型可能不支持以图生图,请在设置里换成 flux-2 系列或支持图片编辑的模型)';
|
||||||
|
}
|
||||||
return res.status(502).json({ success: false, error: msg });
|
return res.status(502).json({ success: false, error: msg });
|
||||||
}
|
}
|
||||||
result = JSON.parse(text);
|
result = JSON.parse(text);
|
||||||
@@ -227,6 +368,9 @@ router.post('/generate', asyncHandler(async (req, res) => {
|
|||||||
revisedPrompt: result.data && result.data[0] && result.data[0].revised_prompt,
|
revisedPrompt: result.data && result.data[0] && result.data[0].revised_prompt,
|
||||||
model: effModel,
|
model: effModel,
|
||||||
size: effSize,
|
size: effSize,
|
||||||
|
promptEn: effPrompt,
|
||||||
|
edited: isEdit,
|
||||||
|
refCount: refs.length,
|
||||||
ms: Date.now() - t0
|
ms: Date.now() - t0
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
+242
-10
@@ -1,6 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
* 文件夹批量水印路由
|
* 文件夹批量水印/重命名路由
|
||||||
* - POST /api/batch/start 启动批量任务(加水印 / 去水印),返回 taskId 立即返回
|
* - POST /api/batch/start 启动批量任务(加水印 / 去水印 / 重命名),返回 taskId 立即返回
|
||||||
|
* - POST /api/batch/rename-preview 批量重命名预览(不执行)
|
||||||
* - GET /api/batch/status/:id 查询任务进度
|
* - GET /api/batch/status/:id 查询任务进度
|
||||||
* - POST /api/batch/cancel/:id 取消任务
|
* - POST /api/batch/cancel/:id 取消任务
|
||||||
*
|
*
|
||||||
@@ -194,6 +195,15 @@ async function callInpaint(imageBuffer, maskBuffer) {
|
|||||||
|
|
||||||
/** 收集文件夹内图片(含子文件夹) */
|
/** 收集文件夹内图片(含子文件夹) */
|
||||||
function collectImages(req, libraryId, folder) {
|
function collectImages(req, libraryId, folder) {
|
||||||
|
return collectRenameTargets(req, { libraryId, folder, scope: 'folder' });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 收集重命名目标
|
||||||
|
* scope=folder(默认):文件夹递归(沿用 collectImages 语义)
|
||||||
|
* scope=search:按关键词模糊匹配整个库(filename/ocr_text LIKE,跨文件夹)
|
||||||
|
*/
|
||||||
|
function collectRenameTargets(req, { libraryId, folder, scope, keywords }) {
|
||||||
const configManager = req.app.get('configManager');
|
const configManager = req.app.get('configManager');
|
||||||
const dbPool = req.app.get('dbPool');
|
const dbPool = req.app.get('dbPool');
|
||||||
if (!configManager || !dbPool) throw new ValidationError('服务未初始化');
|
if (!configManager || !dbPool) throw new ValidationError('服务未初始化');
|
||||||
@@ -205,6 +215,13 @@ function collectImages(req, libraryId, folder) {
|
|||||||
const db = dbPool.acquire(library.path);
|
const db = dbPool.acquire(library.path);
|
||||||
try {
|
try {
|
||||||
const model = new ImageModel(db.db);
|
const model = new ImageModel(db.db);
|
||||||
|
if (scope === 'search') {
|
||||||
|
const kw = String(keywords || '').trim();
|
||||||
|
if (!kw) throw new ValidationError('搜索关键词不能为空');
|
||||||
|
// folder 与搜索列表同款过滤(含子目录):选中文件夹时范围一致,未选中则全库
|
||||||
|
const { images } = model.search({ keywords: kw, folder: folder || undefined }, null);
|
||||||
|
return { library, images };
|
||||||
|
}
|
||||||
const { images } = model.search({ folder }, null);
|
const { images } = model.search({ folder }, null);
|
||||||
return { library, images };
|
return { library, images };
|
||||||
} finally {
|
} finally {
|
||||||
@@ -312,8 +329,193 @@ async function runRemoveWatermark(req, task) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------- 批量重命名 ----------
|
||||||
|
|
||||||
|
/** 文件系统非法文件名字符(Windows 兼容) */
|
||||||
|
const ILLEGAL_NAME_RE = /[\\/:*?"<>|]/;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算重命名计划(preview 与执行共用,保证一致)
|
||||||
|
* @param {object} opts { images, folder, mode: 'prefix'|'suffix'|'replace'|'keyword', text, find?, includeSubdirs }
|
||||||
|
* keyword 模式:把文件名中的 find 全部替换为 text(text 可为空 = 删除关键词),
|
||||||
|
* 不含 find 的文件标记 skipReason='不含关键词'
|
||||||
|
* @returns {Array<{img, newFilename, newPath, absNew, skipReason?}>}
|
||||||
|
*/
|
||||||
|
function computeRenamePlan({ images, folder, mode, text, find, includeSubdirs }) {
|
||||||
|
const cleanText = String(text || '').trim();
|
||||||
|
const cleanFind = String(find || '').trim();
|
||||||
|
let list = images;
|
||||||
|
if (!includeSubdirs) {
|
||||||
|
// 只重命名该文件夹直接子项,排除子目录内文件
|
||||||
|
list = images.filter((img) => img.folder === folder);
|
||||||
|
}
|
||||||
|
// 按目录分组 + 原文件名升序,保证序号顺序稳定
|
||||||
|
const sorted = [...list].sort(
|
||||||
|
(a, b) => a.folder.localeCompare(b.folder) || a.filename.localeCompare(b.filename)
|
||||||
|
);
|
||||||
|
|
||||||
|
const dirGroups = new Map();
|
||||||
|
for (const img of sorted) {
|
||||||
|
if (!dirGroups.has(img.folder)) dirGroups.set(img.folder, []);
|
||||||
|
dirGroups.get(img.folder).push(img);
|
||||||
|
}
|
||||||
|
|
||||||
|
const used = new Set(); // 已分配的目标路径(小写归一,防大小写不敏感 FS 撞名)
|
||||||
|
const plan = [];
|
||||||
|
for (const [, group] of dirGroups) {
|
||||||
|
const width = Math.max(3, String(group.length).length);
|
||||||
|
for (let i = 0; i < group.length; i++) {
|
||||||
|
const img = group[i];
|
||||||
|
const ext = path.extname(img.filename); // 含点,保留原样
|
||||||
|
const base = img.filename.slice(0, img.filename.length - ext.length);
|
||||||
|
let newBase;
|
||||||
|
if (mode === 'prefix') newBase = cleanText + base;
|
||||||
|
else if (mode === 'suffix') newBase = base + cleanText;
|
||||||
|
else if (mode === 'replace') {
|
||||||
|
// 全部改名:整段替换原文件名,同目录多个文件自动编号避免撞名
|
||||||
|
newBase = group.length > 1
|
||||||
|
? `${cleanText}-${String(i + 1).padStart(width, '0')}`
|
||||||
|
: cleanText;
|
||||||
|
} else if (mode === 'keyword') {
|
||||||
|
// 关键词替换:文件名中所有出现的 find 换成 text;不含 find 跳过
|
||||||
|
newBase = base.includes(cleanFind) ? base.split(cleanFind).join(cleanText) : base;
|
||||||
|
} else newBase = base;
|
||||||
|
|
||||||
|
const newFilename = `${newBase}${ext}`;
|
||||||
|
const newPath = `${img.folder ? img.folder + '/' : ''}${newFilename}`;
|
||||||
|
const absNew = newPath; // 相对库根,执行时再 join
|
||||||
|
|
||||||
|
const entry = { img, newFilename, newPath, skipReason: null };
|
||||||
|
if (mode === 'keyword' && !base.includes(cleanFind)) {
|
||||||
|
entry.skipReason = '不含关键词';
|
||||||
|
} else if (newFilename === img.filename) {
|
||||||
|
entry.skipReason = '文件名未变化';
|
||||||
|
} else if (used.has(newPath.toLowerCase())) {
|
||||||
|
entry.skipReason = '目标文件名冲突(本次内)';
|
||||||
|
}
|
||||||
|
used.add(newPath.toLowerCase());
|
||||||
|
plan.push(entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return plan;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runRename(req, task) {
|
||||||
|
const p = task.payload;
|
||||||
|
const { library, images } = collectRenameTargets(req, {
|
||||||
|
libraryId: p.libraryId,
|
||||||
|
folder: p.folder,
|
||||||
|
scope: p.scope,
|
||||||
|
keywords: p.keywords
|
||||||
|
});
|
||||||
|
const opts = task.payload.options;
|
||||||
|
const isSearch = p.scope === 'search';
|
||||||
|
|
||||||
|
const plan = computeRenamePlan({
|
||||||
|
images,
|
||||||
|
folder: task.payload.folder,
|
||||||
|
mode: opts.mode,
|
||||||
|
text: opts.text,
|
||||||
|
find: opts.find,
|
||||||
|
includeSubdirs: isSearch ? true : opts.includeSubdirs !== false
|
||||||
|
});
|
||||||
|
task.total = plan.length;
|
||||||
|
|
||||||
|
const dbPool = req.app.get('dbPool');
|
||||||
|
const dbUpdates = [];
|
||||||
|
|
||||||
|
for (const entry of plan) {
|
||||||
|
if (task.cancelled) break;
|
||||||
|
const { img, newFilename, newPath, skipReason } = entry;
|
||||||
|
task.current = img.path;
|
||||||
|
if (skipReason) {
|
||||||
|
task.skipped++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const absOld = path.join(library.path, img.path);
|
||||||
|
const absNew = path.join(library.path, newPath);
|
||||||
|
try {
|
||||||
|
if (!fs.existsSync(absOld)) {
|
||||||
|
task.skipped++;
|
||||||
|
if (task.errors.length < 20) task.errors.push({ path: img.path, error: '源文件不存在' });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (absOld !== absNew && fs.existsSync(absNew)) {
|
||||||
|
task.skipped++;
|
||||||
|
if (task.errors.length < 20) task.errors.push({ path: img.path, error: `目标已存在: ${newFilename}` });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (absOld !== absNew) await fs.promises.rename(absOld, absNew);
|
||||||
|
dbUpdates.push({ oldPath: img.path, newPath, newFilename });
|
||||||
|
task.done++;
|
||||||
|
} catch (err) {
|
||||||
|
task.failed++;
|
||||||
|
if (task.errors.length < 20) task.errors.push({ path: img.path, error: err.message });
|
||||||
|
logger.warn(`⚠️ 批量重命名失败 ${img.path}: ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 统一更新 DB(缩略图按内容 hash 存储,与文件名无关,无需重建)
|
||||||
|
if (dbUpdates.length > 0) {
|
||||||
|
const db = dbPool.acquire(library.path);
|
||||||
|
try {
|
||||||
|
const stmt = db.db.prepare('UPDATE images SET path = ?, filename = ? WHERE path = ?');
|
||||||
|
for (const u of dbUpdates) stmt.run(u.newPath, u.newFilename, u.oldPath);
|
||||||
|
} finally {
|
||||||
|
dbPool.release(library.path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ---------- 路由 ----------
|
// ---------- 路由 ----------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/batch/rename-preview
|
||||||
|
* body: { libraryId, folder?, scope?: 'folder'|'search', keywords?, options: { mode, text, find?, includeSubdirs } }
|
||||||
|
* scope=search 时按 keywords 模糊匹配全库(跨文件夹),folder 可不传
|
||||||
|
* 返回重命名预览(不执行)
|
||||||
|
*/
|
||||||
|
router.post(
|
||||||
|
'/rename-preview',
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const { libraryId, folder, scope, options } = req.body || {};
|
||||||
|
if (!libraryId) throw new ValidationError('缺少 libraryId');
|
||||||
|
const isSearch = scope === 'search';
|
||||||
|
if (!isSearch && !folder) throw new ValidationError('缺少 libraryId 或 folder');
|
||||||
|
const mode = options && options.mode;
|
||||||
|
if (!['prefix', 'suffix', 'replace', 'keyword'].includes(mode)) {
|
||||||
|
throw new ValidationError('mode 必须是 prefix / suffix / replace / keyword');
|
||||||
|
}
|
||||||
|
const text = String((options && options.text) || '').trim();
|
||||||
|
const find = String((options && options.find) || '').trim();
|
||||||
|
if (mode === 'keyword') {
|
||||||
|
if (!find) throw new ValidationError('请填写要查找的关键词');
|
||||||
|
if (ILLEGAL_NAME_RE.test(find)) throw new ValidationError('关键词包含文件名非法字符 \\ / : * ? " < > |');
|
||||||
|
if (ILLEGAL_NAME_RE.test(text)) throw new ValidationError('替换文本包含文件名非法字符 \\ / : * ? " < > |');
|
||||||
|
} else {
|
||||||
|
if (!text) throw new ValidationError('重命名文本不能为空');
|
||||||
|
if (ILLEGAL_NAME_RE.test(text)) throw new ValidationError('文本包含文件名非法字符 \\ / : * ? " < > |');
|
||||||
|
}
|
||||||
|
|
||||||
|
const targets = collectRenameTargets(req, {
|
||||||
|
libraryId, folder, scope, keywords: options && options.keywords
|
||||||
|
});
|
||||||
|
const plan = computeRenamePlan({
|
||||||
|
images: targets.images,
|
||||||
|
folder: isSearch ? null : folder,
|
||||||
|
mode, text, find,
|
||||||
|
includeSubdirs: isSearch ? true : options.includeSubdirs !== false
|
||||||
|
});
|
||||||
|
const effective = plan.filter((p) => !p.skipReason);
|
||||||
|
res.json({
|
||||||
|
count: effective.length,
|
||||||
|
total: plan.length,
|
||||||
|
samples: plan.slice(0, 6).map((p) => ({ from: p.img.filename, to: p.newFilename })),
|
||||||
|
skipped: plan.filter((p) => p.skipReason).length
|
||||||
|
});
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* POST /api/batch/start
|
* POST /api/batch/start
|
||||||
* body: { libraryId, folder, type: 'add'|'remove', output?: 'overwrite'|'new', options }
|
* body: { libraryId, folder, type: 'add'|'remove', output?: 'overwrite'|'new', options }
|
||||||
@@ -323,12 +525,29 @@ async function runRemoveWatermark(req, task) {
|
|||||||
router.post(
|
router.post(
|
||||||
'/start',
|
'/start',
|
||||||
asyncHandler(async (req, res) => {
|
asyncHandler(async (req, res) => {
|
||||||
const { libraryId, folder, type, output, options } = req.body || {};
|
const { libraryId, folder, type, output, options, scope } = req.body || {};
|
||||||
if (!libraryId || !folder) throw new ValidationError('缺少 libraryId 或 folder');
|
if (!libraryId) throw new ValidationError('缺少 libraryId');
|
||||||
if (type !== 'add' && type !== 'remove') throw new ValidationError('type 必须是 add 或 remove');
|
const isSearch = type === 'rename' && scope === 'search';
|
||||||
|
if (!folder && !isSearch) throw new ValidationError('缺少 libraryId 或 folder');
|
||||||
|
if (!['add', 'remove', 'rename'].includes(type)) throw new ValidationError('type 必须是 add / remove / rename');
|
||||||
|
|
||||||
if (type === 'add') {
|
if (type === 'add') {
|
||||||
if (!options || !String(options.text || '').trim()) throw new ValidationError('水印文字不能为空');
|
if (!options || !String(options.text || '').trim()) throw new ValidationError('水印文字不能为空');
|
||||||
|
} else if (type === 'rename') {
|
||||||
|
const mode = options && options.mode;
|
||||||
|
if (!['prefix', 'suffix', 'replace', 'keyword'].includes(mode)) {
|
||||||
|
throw new ValidationError('mode 必须是 prefix / suffix / replace / keyword');
|
||||||
|
}
|
||||||
|
const text = String((options && options.text) || '').trim();
|
||||||
|
const find = String((options && options.find) || '').trim();
|
||||||
|
if (mode === 'keyword') {
|
||||||
|
if (!find) throw new ValidationError('请填写要查找的关键词');
|
||||||
|
if (ILLEGAL_NAME_RE.test(find)) throw new ValidationError('关键词包含文件名非法字符 \\ / : * ? " < > |');
|
||||||
|
if (ILLEGAL_NAME_RE.test(text)) throw new ValidationError('替换文本包含文件名非法字符 \\ / : * ? " < > |');
|
||||||
|
} else {
|
||||||
|
if (!text) throw new ValidationError('重命名文本不能为空');
|
||||||
|
if (ILLEGAL_NAME_RE.test(text)) throw new ValidationError('文本包含文件名非法字符 \\ / : * ? " < > |');
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
const r = options && options.region;
|
const r = options && options.region;
|
||||||
if (!r || [r.x, r.y, r.w, r.h].some((v) => typeof v !== 'number' || v < 0)) {
|
if (!r || [r.x, r.y, r.w, r.h].some((v) => typeof v !== 'number' || v < 0)) {
|
||||||
@@ -337,15 +556,28 @@ router.post(
|
|||||||
if (r.w <= 0 || r.h <= 0) throw new ValidationError('水印区域宽高必须大于 0');
|
if (r.w <= 0 || r.h <= 0) throw new ValidationError('水印区域宽高必须大于 0');
|
||||||
}
|
}
|
||||||
|
|
||||||
const { images } = collectImages(req, libraryId, folder);
|
const { images } = collectRenameTargets(req, {
|
||||||
if (images.length === 0) throw new ValidationError('该文件夹下没有图片');
|
libraryId, folder, scope, keywords: options && options.keywords
|
||||||
|
});
|
||||||
|
if (images.length === 0) {
|
||||||
|
throw new ValidationError(
|
||||||
|
scope === 'search' ? '搜索没有匹配到文件' : (type === 'rename' ? '该文件夹下没有文件' : '该文件夹下没有图片')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const task = newTask(type, { libraryId, folder, output, options });
|
const task = newTask(type, {
|
||||||
|
libraryId,
|
||||||
|
folder: folder || null,
|
||||||
|
scope: scope || 'folder',
|
||||||
|
keywords: scope === 'search' ? String(options?.keywords || '').trim() : null,
|
||||||
|
output,
|
||||||
|
options
|
||||||
|
});
|
||||||
task.total = images.length;
|
task.total = images.length;
|
||||||
logger.info(`▶️ 批量${type === 'add' ? '加水印' : '去水印'}启动: ${folder} (${images.length} 张)`);
|
logger.info(`▶️ 批量${type === 'add' ? '加水印' : type === 'remove' ? '去水印' : '重命名'}启动: ${folder} (${images.length} 张)`);
|
||||||
|
|
||||||
// 立即返回,后台执行
|
// 立即返回,后台执行
|
||||||
const runner = type === 'add' ? runAddWatermark : runRemoveWatermark;
|
const runner = type === 'add' ? runAddWatermark : type === 'remove' ? runRemoveWatermark : runRename;
|
||||||
runner(req, task)
|
runner(req, task)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
task.status = task.cancelled ? 'cancelled' : 'done';
|
task.status = task.cancelled ? 'cancelled' : 'done';
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ router.get('/', (req, res) => {
|
|||||||
provider: ig.provider === 'custom' ? 'custom' : 'newapi',
|
provider: ig.provider === 'custom' ? 'custom' : 'newapi',
|
||||||
newapi: {
|
newapi: {
|
||||||
url: (ig.newapi && ig.newapi.url) || '',
|
url: (ig.newapi && ig.newapi.url) || '',
|
||||||
|
model: (ig.newapi && ig.newapi.model) || 'flux-schnell',
|
||||||
apiKeyMasked: maskKey((ig.newapi && ig.newapi.apiKey) || ''),
|
apiKeyMasked: maskKey((ig.newapi && ig.newapi.apiKey) || ''),
|
||||||
// 真正生效的 key:设置里的或环境变量兜底
|
// 真正生效的 key:设置里的或环境变量兜底
|
||||||
hasKey: !!((ig.newapi && ig.newapi.apiKey) || process.env.NEWAPI_KEY)
|
hasKey: !!((ig.newapi && ig.newapi.apiKey) || process.env.NEWAPI_KEY)
|
||||||
@@ -40,6 +41,15 @@ router.get('/', (req, res) => {
|
|||||||
apiKeyMasked: maskKey((ig.custom && ig.custom.apiKey) || ''),
|
apiKeyMasked: maskKey((ig.custom && ig.custom.apiKey) || ''),
|
||||||
configured: !!(ig.custom && ig.custom.url && ig.custom.apiKey)
|
configured: !!(ig.custom && ig.custom.url && ig.custom.apiKey)
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
videoai: {
|
||||||
|
provider: (s.videoai && s.videoai.provider) === 'custom' ? 'custom' : 'inherit',
|
||||||
|
custom: {
|
||||||
|
url: (s.videoai && s.videoai.custom && s.videoai.custom.url) || '',
|
||||||
|
model: (s.videoai && s.videoai.custom && s.videoai.custom.model) || '',
|
||||||
|
apiKeyMasked: maskKey((s.videoai && s.videoai.custom && s.videoai.custom.apiKey) || ''),
|
||||||
|
configured: !!(s.videoai && s.videoai.custom && s.videoai.custom.url && s.videoai.custom.apiKey)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -64,6 +74,7 @@ router.put('/', (req, res) => {
|
|||||||
provider: ig.provider,
|
provider: ig.provider,
|
||||||
newapi: {
|
newapi: {
|
||||||
url: ig.newapi.url,
|
url: ig.newapi.url,
|
||||||
|
model: ig.newapi.model || 'flux-schnell',
|
||||||
apiKeyMasked: maskKey(ig.newapi.apiKey),
|
apiKeyMasked: maskKey(ig.newapi.apiKey),
|
||||||
hasKey: !!(ig.newapi.apiKey || process.env.NEWAPI_KEY)
|
hasKey: !!(ig.newapi.apiKey || process.env.NEWAPI_KEY)
|
||||||
},
|
},
|
||||||
@@ -73,6 +84,15 @@ router.put('/', (req, res) => {
|
|||||||
apiKeyMasked: maskKey(ig.custom.apiKey),
|
apiKeyMasked: maskKey(ig.custom.apiKey),
|
||||||
configured: !!(ig.custom.url && ig.custom.apiKey)
|
configured: !!(ig.custom.url && ig.custom.apiKey)
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
videoai: {
|
||||||
|
provider: (saved.videoai && saved.videoai.provider) === 'custom' ? 'custom' : 'inherit',
|
||||||
|
custom: {
|
||||||
|
url: (saved.videoai && saved.videoai.custom && saved.videoai.custom.url) || '',
|
||||||
|
model: (saved.videoai && saved.videoai.custom && saved.videoai.custom.model) || '',
|
||||||
|
apiKeyMasked: maskKey((saved.videoai && saved.videoai.custom && saved.videoai.custom.apiKey) || ''),
|
||||||
|
configured: !!(saved.videoai && saved.videoai.custom && saved.videoai.custom.url && saved.videoai.custom.apiKey)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
+259
-11
@@ -14,9 +14,11 @@ const fs = require('fs');
|
|||||||
const os = require('os');
|
const os = require('os');
|
||||||
const { asyncHandler, ValidationError, NotFoundError } = require('../middleware/errorHandler');
|
const { asyncHandler, ValidationError, NotFoundError } = require('../middleware/errorHandler');
|
||||||
const { processImage } = require('../../utils/scanner');
|
const { processImage } = require('../../utils/scanner');
|
||||||
const { getSettings } = require('../../utils/settings');
|
const { getSettings, resolveVideoGen } = require('../../utils/settings');
|
||||||
const logger = require('../utils/logger');
|
const logger = require('../utils/logger');
|
||||||
const videotool = require('../../utils/videotool');
|
const videotool = require('../../utils/videotool');
|
||||||
|
const multer = require('multer');
|
||||||
|
const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 20 * 1024 * 1024 } });
|
||||||
|
|
||||||
const VIDEO_EXTS = new Set(['.mp4', '.mov', '.m4v', '.webm', '.mkv', '.avi', '.flv', '.wmv', '.mpg', '.mpeg', '.3gp', '.ts']);
|
const VIDEO_EXTS = new Set(['.mp4', '.mov', '.m4v', '.webm', '.mkv', '.avi', '.flv', '.wmv', '.mpg', '.mpeg', '.3gp', '.ts']);
|
||||||
|
|
||||||
@@ -133,7 +135,10 @@ router.post(
|
|||||||
model, // 模型名
|
model, // 模型名
|
||||||
voice = 'zh-CN-XiaoxiaoNeural',
|
voice = 'zh-CN-XiaoxiaoNeural',
|
||||||
resolution = '1920x1080',
|
resolution = '1920x1080',
|
||||||
extraPrompt = ''
|
extraPrompt = '',
|
||||||
|
saveDir = '',
|
||||||
|
duration = 0,
|
||||||
|
subtitleStyle = {}
|
||||||
} = req.body || {};
|
} = req.body || {};
|
||||||
|
|
||||||
if (!libraryId || !Array.isArray(images) || images.length < 2) {
|
if (!libraryId || !Array.isArray(images) || images.length < 2) {
|
||||||
@@ -156,14 +161,13 @@ router.post(
|
|||||||
if (!library) throw new NotFoundError('Library', libraryId);
|
if (!library) throw new NotFoundError('Library', libraryId);
|
||||||
|
|
||||||
const settings = getSettings();
|
const settings = getSettings();
|
||||||
const gen = (settings.imagegen && settings.imagegen.provider === 'custom')
|
// 设置 - AI 视频(或复用 AI 生图)中的文本模型配置;请求参数可临时覆盖
|
||||||
? settings.imagegen.custom
|
const gen = resolveVideoGen(settings);
|
||||||
: settings.imagegen.newapi;
|
|
||||||
const url = (baseUrl || gen.url || '').replace(/\/+$/, '');
|
const url = (baseUrl || gen.url || '').replace(/\/+$/, '');
|
||||||
const key = apiKey || gen.apiKey || process.env.NEWAPI_KEY || '';
|
const key = apiKey || gen.apiKey || process.env.NEWAPI_KEY || '';
|
||||||
const mdl = model || gen.model || 'mimo-v2.6-flash';
|
const mdl = model || gen.model || 'mimo-v2.6-flash';
|
||||||
if (!url) throw new ValidationError('未配置模型接口地址(填 BASE URL 或在设置里配置)');
|
if (!url) throw new ValidationError('未配置模型接口地址(请到右上角设置 → AI 视频里填写)');
|
||||||
if (!key) throw new ValidationError('请填写模型 KEY(或在设置-生图里配置)');
|
if (!key) throw new ValidationError('请先在右上角设置 → AI 视频里填写模型 KEY');
|
||||||
|
|
||||||
const id = `vt${++aiTaskSeq}_${Date.now()}`;
|
const id = `vt${++aiTaskSeq}_${Date.now()}`;
|
||||||
const [w, h] = String(resolution).split('x').map((n) => parseInt(n, 10));
|
const [w, h] = String(resolution).split('x').map((n) => parseInt(n, 10));
|
||||||
@@ -185,7 +189,7 @@ router.post(
|
|||||||
runAiVideo({
|
runAiVideo({
|
||||||
task, library, images, title: String(title).trim(), url, key, model: mdl,
|
task, library, images, title: String(title).trim(), url, key, model: mdl,
|
||||||
voice, width: Number.isFinite(w) ? w : 1920, height: Number.isFinite(h) ? h : 1080,
|
voice, width: Number.isFinite(w) ? w : 1920, height: Number.isFinite(h) ? h : 1080,
|
||||||
extraPrompt: String(extraPrompt || ''),
|
extraPrompt: String(extraPrompt || ''), duration: Math.min(600, Math.max(0, Number(duration) || 0)), subtitleStyle: subtitleStyle || {},
|
||||||
req
|
req
|
||||||
}).catch((err) => {
|
}).catch((err) => {
|
||||||
task.status = 'error';
|
task.status = 'error';
|
||||||
@@ -200,7 +204,7 @@ router.post(
|
|||||||
router.get(
|
router.get(
|
||||||
'/task/:id',
|
'/task/:id',
|
||||||
asyncHandler(async (req, res) => {
|
asyncHandler(async (req, res) => {
|
||||||
const task = aiTasks.get(req.params.id);
|
const task = aiTasks.get(req.params.id) || textTasks.get(req.params.id);
|
||||||
if (!task) throw new NotFoundError('Task', req.params.id);
|
if (!task) throw new NotFoundError('Task', req.params.id);
|
||||||
res.json(task);
|
res.json(task);
|
||||||
})
|
})
|
||||||
@@ -255,7 +259,7 @@ async function llmScript({ url, key, model, title, count, extraPrompt }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function runAiVideo(ctx) {
|
async function runAiVideo(ctx) {
|
||||||
const { task, library, images, title, url, key, model, voice, width, height, extraPrompt, req } = ctx;
|
const { task, library, images, title, url, key, model, voice, width, height, extraPrompt, subtitleStyle, req } = ctx;
|
||||||
|
|
||||||
// 1) 校验图片文件
|
// 1) 校验图片文件
|
||||||
const files = [];
|
const files = [];
|
||||||
@@ -301,10 +305,24 @@ async function runAiVideo(ctx) {
|
|||||||
imagePath: files[i],
|
imagePath: files[i],
|
||||||
subtitle: seg.subtitle || seg.tts || title,
|
subtitle: seg.subtitle || seg.tts || title,
|
||||||
ttsFile,
|
ttsFile,
|
||||||
|
ttsSeconds: dur,
|
||||||
duration: Math.max(2.5, Math.min(12, dur || 4))
|
duration: Math.max(2.5, Math.min(12, dur || 4))
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 目标时长:按各段自然时长比例分配(该路径无转场重叠)
|
||||||
|
const targetDur = Number(ctx.duration) > 0 ? Number(ctx.duration) : 0;
|
||||||
|
if (targetDur > 0 && segments.length) {
|
||||||
|
const avail = Math.max(segments.length * 1.0, targetDur);
|
||||||
|
const natural = segments.reduce((s, x) => s + x.duration, 0) || 1;
|
||||||
|
for (const s of segments) {
|
||||||
|
const d = Math.max(1.0, (s.duration / natural) * avail);
|
||||||
|
s.duration = d;
|
||||||
|
s.audioDuration = d;
|
||||||
|
}
|
||||||
|
logger.info(`⏱ AI 视频目标时长 ${targetDur}s → 分配 ${segments.length} 段`);
|
||||||
|
}
|
||||||
|
|
||||||
// 4) 逐段合成
|
// 4) 逐段合成
|
||||||
const segFiles = [];
|
const segFiles = [];
|
||||||
for (let i = 0; i < segments.length; i++) {
|
for (let i = 0; i < segments.length; i++) {
|
||||||
@@ -313,7 +331,7 @@ async function runAiVideo(ctx) {
|
|||||||
task.stepLabel = `正在合成画面 ${i + 1}/${segments.length}`;
|
task.stepLabel = `正在合成画面 ${i + 1}/${segments.length}`;
|
||||||
task.progress = 50 + Math.round((i / segments.length) * 45);
|
task.progress = 50 + Math.round((i / segments.length) * 45);
|
||||||
const out = path.join(work, `seg${i}.mp4`);
|
const out = path.join(work, `seg${i}.mp4`);
|
||||||
await videotool.buildSegment(segments[i], out, { width, height });
|
await videotool.buildSegment(segments[i], out, { width, height, subtitleStyle: ctx.subtitleStyle });
|
||||||
segFiles.push(out);
|
segFiles.push(out);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -348,4 +366,234 @@ async function runAiVideo(ctx) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------- URL 抓取:内容 + 图片 ----------
|
||||||
|
router.post(
|
||||||
|
'/extract-url',
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const { url } = req.body || {};
|
||||||
|
if (!url) throw new ValidationError('缺少 url');
|
||||||
|
let html = '';
|
||||||
|
try {
|
||||||
|
const r = await fetch(url, { headers: { 'User-Agent': 'Mozilla/5.0' }, signal: AbortSignal.timeout(20000) });
|
||||||
|
html = await r.text();
|
||||||
|
} catch (e) { throw new ValidationError('抓取失败: ' + (e.message || e)); }
|
||||||
|
const titleMatch = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
|
||||||
|
const title = titleMatch ? titleMatch[1].replace(/\s+/g, ' ').trim().slice(0, 80) : '';
|
||||||
|
// images
|
||||||
|
const imgs = [];
|
||||||
|
const imgRe = /<img[^>]+src=["']([^"']+)["']/gi;
|
||||||
|
let m;
|
||||||
|
while ((m = imgRe.exec(html)) && imgs.length < 8) {
|
||||||
|
let src = m[1];
|
||||||
|
if (src.startsWith('//')) src = 'https:' + src;
|
||||||
|
else if (src.startsWith('/')) { try { src = new URL(src, url).href; } catch (_) {} }
|
||||||
|
else if (!/^https?:/i.test(src)) { try { src = new URL(src, url).href; } catch (_) {} }
|
||||||
|
if (/^https?:/i.test(src) && !imgs.includes(src)) imgs.push(src);
|
||||||
|
}
|
||||||
|
// text: strip tags
|
||||||
|
const text = html
|
||||||
|
.replace(/<script[\s\S]*?<\/script>/gi, '')
|
||||||
|
.replace(/<style[\s\S]*?<\/style>/gi, '')
|
||||||
|
.replace(/<[^>]+>/g, ' ')
|
||||||
|
.replace(/\s+/g, ' ')
|
||||||
|
.trim()
|
||||||
|
.slice(0, 4000);
|
||||||
|
res.json({ success: true, title, text, images: imgs });
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
// ---------- 文档/PDF 提取 ----------
|
||||||
|
router.post(
|
||||||
|
'/extract-doc',
|
||||||
|
upload.single('file'),
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
if (!req.file) throw new ValidationError('缺少文件');
|
||||||
|
const name = req.file.originalname || 'doc';
|
||||||
|
let text = '';
|
||||||
|
const ext = path.extname(name).toLowerCase();
|
||||||
|
if (ext === '.pdf') {
|
||||||
|
const tmp = path.join(os.tmpdir(), `doc_${Date.now()}.pdf`);
|
||||||
|
fs.writeFileSync(tmp, req.file.buffer);
|
||||||
|
try {
|
||||||
|
const { stdout } = await videotool.run('pdftotext', ['-layout', tmp, '-'], { timeoutMs: 60000 });
|
||||||
|
text = stdout;
|
||||||
|
} catch (e) {
|
||||||
|
text = req.file.buffer.toString('utf8').replace(/[^\x20-\x7E\u4e00-\u9fa5]/g, ' ');
|
||||||
|
} finally {
|
||||||
|
try { fs.unlinkSync(tmp); } catch (_) {}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
text = req.file.buffer.toString('utf8');
|
||||||
|
}
|
||||||
|
text = String(text).replace(/\s+/g, ' ').trim().slice(0, 6000);
|
||||||
|
res.json({ success: true, title: name.replace(/\.[^.]+$/, ''), text, images: [] });
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
// ---------- 文本源 AI 生成视频(提示词/URL/文档) ----------
|
||||||
|
const textTasks = new Map();
|
||||||
|
let textTaskSeq = 0;
|
||||||
|
router.post(
|
||||||
|
'/aigenerate-text',
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const {
|
||||||
|
libraryId, title, content, images = [],
|
||||||
|
apiKey, baseUrl, model,
|
||||||
|
voice = 'zh-CN-XiaoxiaoNeural',
|
||||||
|
resolution = '1920x1080',
|
||||||
|
extraPrompt = '',
|
||||||
|
saveDir = '',
|
||||||
|
transition = 'fade',
|
||||||
|
duration = 0,
|
||||||
|
subtitleStyle = {}
|
||||||
|
} = req.body || {};
|
||||||
|
if (!libraryId) throw new ValidationError('缺少 libraryId');
|
||||||
|
if (!title || !String(title).trim()) throw new ValidationError('请填写视频标题');
|
||||||
|
const text = String(content || '').trim();
|
||||||
|
if (!text && (!Array.isArray(images) || images.length === 0)) throw new ValidationError('缺少内容或图片');
|
||||||
|
|
||||||
|
const configManager = req.app.get('configManager');
|
||||||
|
const config = configManager.load();
|
||||||
|
const library = config.libraries.find((l) => String(l.id) === String(libraryId));
|
||||||
|
if (!library) throw new NotFoundError('Library', libraryId);
|
||||||
|
|
||||||
|
const settings = getSettings();
|
||||||
|
// 设置 - AI 视频(或复用 AI 生图)中的文本模型配置;请求参数可临时覆盖
|
||||||
|
const gen = resolveVideoGen(settings);
|
||||||
|
const url = (baseUrl || gen.url || '').replace(/\/+$/, '');
|
||||||
|
const key = apiKey || gen.apiKey || process.env.NEWAPI_KEY || '';
|
||||||
|
const mdl = model || gen.model || 'mimo-v2.6-flash';
|
||||||
|
if (!url) throw new ValidationError('未配置模型接口地址(请到右上角设置 → AI 视频里填写)');
|
||||||
|
if (!key) throw new ValidationError('请先在右上角设置 → AI 视频里填写模型 KEY');
|
||||||
|
|
||||||
|
// 转场效果白名单(防注入 ffmpeg filter)
|
||||||
|
const TRANSITIONS = new Set(['cut','fade','fadeblack','fadewhite','slideleft','slideright','slideup','slidedown','circlecrop','circleopen','circleclose','dissolve','smoothleft','smoothright','wipeleft','wiperight','pixelize','radial','hblur']);
|
||||||
|
const trans = TRANSITIONS.has(String(transition)) ? String(transition) : 'fade';
|
||||||
|
|
||||||
|
const id = `vt${++textTaskSeq}_${Date.now()}`;
|
||||||
|
const [w, h] = String(resolution).split('x').map((n) => parseInt(n, 10));
|
||||||
|
const task = { id, status: 'running', step: 'script', stepLabel: '正在生成', progress: 0, error: '', resultPath: '', createdAt: Date.now() };
|
||||||
|
textTasks.set(id, task);
|
||||||
|
setTimeout(() => textTasks.delete(id), 30 * 60 * 1000);
|
||||||
|
|
||||||
|
const durSec = Math.min(600, Math.max(0, Number(duration) || 0)); // 目标时长(秒),0=自动
|
||||||
|
runTextVideo({ task, library, title: String(title).trim(), content: text, images, url, key, model: mdl, voice, width: Number.isFinite(w)?w:1920, height: Number.isFinite(h)?h:1080, extraPrompt: String(extraPrompt||''), saveDir: String(saveDir||''), transition: trans, duration: durSec, subtitleStyle: subtitleStyle||{}, req }).catch((err) => {
|
||||||
|
task.status = 'error'; task.error = err.message || String(err);
|
||||||
|
});
|
||||||
|
res.json({ success: true, taskId: id });
|
||||||
|
})
|
||||||
|
);
|
||||||
|
async function runTextVideo(ctx) {
|
||||||
|
const { task, library, title, content, images, url, key, model, voice, width, height, extraPrompt, saveDir, transition, subtitleStyle, req } = ctx;
|
||||||
|
const work = fs.mkdtempSync(path.join(os.tmpdir(), 'flypic-tv-'));
|
||||||
|
try {
|
||||||
|
// 生成背景图(若无图片)
|
||||||
|
// 解析全部选中图片(本地库路径 / 远程 URL 下载)—— 让每张选中图片都进视频
|
||||||
|
const imagePaths = [];
|
||||||
|
if (Array.isArray(images) && images.length) {
|
||||||
|
for (const it of images) {
|
||||||
|
const rel = typeof it === 'string' ? it : (it && (it.path || it.url)) || '';
|
||||||
|
if (!rel) continue;
|
||||||
|
if (/^https?:/i.test(rel)) {
|
||||||
|
try {
|
||||||
|
const r = await fetch(rel);
|
||||||
|
const buf = Buffer.from(await r.arrayBuffer());
|
||||||
|
const ext = (path.extname(new URL(rel).pathname) || '.jpg').toLowerCase();
|
||||||
|
const fp = path.join(work, `img${imagePaths.length}${ext}`);
|
||||||
|
fs.writeFileSync(fp, buf);
|
||||||
|
imagePaths.push(fp);
|
||||||
|
} catch (e) { logger.warn('图片下载失败: ' + e.message); }
|
||||||
|
} else {
|
||||||
|
const abs = path.join(library.path, rel);
|
||||||
|
if (fs.existsSync(abs)) imagePaths.push(abs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 兜底:无图时生成纯色背景
|
||||||
|
if (!imagePaths.length) {
|
||||||
|
const bgPath = path.join(work, 'bg.png');
|
||||||
|
await videotool.run('ffmpeg', ['-y', '-f', 'lavfi', '-i', `color=c=0x1a1a2e:s=${width}x${height}`, '-frames:v', '1', bgPath], { timeoutMs: 60000 });
|
||||||
|
imagePaths.push(bgPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
// LLM 生成分镜:基于内容切分
|
||||||
|
task.step = 'script'; task.stepLabel = '正在生成脚本'; task.progress = 5;
|
||||||
|
let script = [];
|
||||||
|
const targetDur0 = Number(ctx.duration) > 0 ? Number(ctx.duration) : 0;
|
||||||
|
if (content) {
|
||||||
|
// 让模型按内容生成 N 段(N = min(8, 句子数))
|
||||||
|
const sentences = content.split(/[。!?.!?]/).map(s=>s.trim()).filter(Boolean);
|
||||||
|
const baseN = Math.min(8, Math.max(2, sentences.length));
|
||||||
|
let n = Math.max(baseN, imagePaths.length); // 分镜数 ≥ 选中图片数,保证每张图都出现
|
||||||
|
if (targetDur0 > 0) n = Math.max(n, Math.min(30, Math.ceil(targetDur0 / 5))); // 时长越长分镜越多(约5s/段)
|
||||||
|
script = await llmScript({ url, key, model, title, count: n, extraPrompt: (extraPrompt + ' 内容:' + content.slice(0, 1500)).trim() });
|
||||||
|
} else {
|
||||||
|
script = [{ subtitle: title, tts: title }];
|
||||||
|
}
|
||||||
|
if (!Array.isArray(script) || !script.length) script = [{ subtitle: title, tts: title }];
|
||||||
|
|
||||||
|
// TTS + segments:每段轮换使用选中图片,保证所有图片都出现
|
||||||
|
const segments = [];
|
||||||
|
let segCount = Math.max(script.length, imagePaths.length);
|
||||||
|
if (targetDur0 > 0) segCount = Math.max(segCount, Math.min(30, Math.ceil(targetDur0 / 5))); // 按目标时长补齐段数
|
||||||
|
for (let i = 0; i < segCount; i++) {
|
||||||
|
task.step = 'tts'; task.stepLabel = `正在朗读 ${i+1}/${segCount}`; task.progress = 10 + Math.round((i/segCount)*40);
|
||||||
|
const seg = script[i % script.length] || {};
|
||||||
|
let ttsFile = ''; let dur = 0;
|
||||||
|
if (seg.tts) {
|
||||||
|
try {
|
||||||
|
const t = await videotool.generateTts(seg.tts, { voice, outPath: path.join(work, `tts${i}.mp3`) });
|
||||||
|
ttsFile = t.file; dur = t.seconds;
|
||||||
|
} catch (e) { logger.warn('TTS fail: ' + e.message); }
|
||||||
|
}
|
||||||
|
segments.push({ imagePath: imagePaths[i % imagePaths.length], subtitle: seg.subtitle || seg.tts || title, ttsFile, ttsSeconds: dur, duration: Math.max(2.5, Math.min(12, dur || 4)) });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 目标时长:画面段总长 = 目标 + 转场重叠(xfade 每次吃掉 0.6s),
|
||||||
|
// 配音段总长 = 目标(音频走 concat 无重叠),使音画总长都精确等于目标时长
|
||||||
|
const targetDur = Number(ctx.duration) > 0 ? Number(ctx.duration) : 0;
|
||||||
|
if (targetDur > 0 && segments.length) {
|
||||||
|
const n = segments.length;
|
||||||
|
const overlap = (transition && transition !== 'cut' && n > 1) ? 0.6 * (n - 1) : 0;
|
||||||
|
const natural = segments.reduce((s, x) => s + x.duration, 0) || 1;
|
||||||
|
const videoTotal = targetDur + overlap; // 画面段之和
|
||||||
|
const audioShare = overlap / n; // 每段配音比画面短的秒数(落在转场区)
|
||||||
|
for (const s of segments) {
|
||||||
|
const d = Math.max(1.0, (s.duration / natural) * videoTotal);
|
||||||
|
s.duration = d;
|
||||||
|
s.audioDuration = Math.max(0.5, d - audioShare); // 精确模式:配音对齐
|
||||||
|
}
|
||||||
|
logger.info(`⏱ AI 视频目标时长 ${targetDur}s → 画面 ${videoTotal.toFixed(1)}s + 转场重叠 ${overlap.toFixed(1)}s,分 ${n} 段`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// compose
|
||||||
|
const segFiles = [];
|
||||||
|
for (let i = 0; i < segments.length; i++) {
|
||||||
|
task.step = 'compose'; task.stepLabel = `合成 ${i+1}/${segments.length}`; task.progress = 50 + Math.round((i/segments.length)*45);
|
||||||
|
const out = path.join(work, `seg${i}.mp4`);
|
||||||
|
await videotool.buildSegment(segments[i], out, { width, height, subtitleStyle });
|
||||||
|
segFiles.push(out);
|
||||||
|
}
|
||||||
|
task.step = 'merge'; task.stepLabel = '合并'; task.progress = 96;
|
||||||
|
const finalTmp = path.join(work, 'final.mp4');
|
||||||
|
await videotool.concatWithTransition(segFiles, finalTmp, { transition: transition || 'fade', width, height });
|
||||||
|
|
||||||
|
// 6) 落库:保存到用户选择的目录(默认素材库根目录)
|
||||||
|
const safeDir = String(saveDir || '').replace(/^\/+/, '').replace(/\.\./g, '');
|
||||||
|
const baseDir = safeDir ? path.join(library.path, safeDir) : library.path;
|
||||||
|
try { fs.mkdirSync(baseDir, { recursive: true }); } catch (_) {}
|
||||||
|
const safeTitle = String(title).replace(/[\\/:*?"<>|]/g, '_').slice(0, 60) || 'AI视频';
|
||||||
|
let target = path.join(baseDir, `${safeTitle}.mp4`);
|
||||||
|
let n = 1;
|
||||||
|
while (fs.existsSync(target)) { target = path.join(baseDir, `${safeTitle}_${n}.mp4`); n++; }
|
||||||
|
fs.copyFileSync(finalTmp, target);
|
||||||
|
await reindex(req, library.path, target);
|
||||||
|
|
||||||
|
task.status = 'done'; task.progress = 100; task.step = 'done'; task.stepLabel = '完成'; task.resultPath = path.relative(library.path, target);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(work, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// llmScript is defined later? it's a function declaration in same module scope (hoisted). ok.
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
@@ -112,9 +112,21 @@ class ImageService {
|
|||||||
ORDER BY count DESC
|
ORDER BY count DESC
|
||||||
`).all();
|
`).all();
|
||||||
|
|
||||||
|
// 按文件类型分组计数(image/video/document/...),供前端类型注册表自动识别渲染
|
||||||
|
const typeCountsList = db.db.prepare(`
|
||||||
|
SELECT file_type, COUNT(*) as count
|
||||||
|
FROM images
|
||||||
|
GROUP BY file_type
|
||||||
|
`).all();
|
||||||
|
const typeCounts = {};
|
||||||
|
for (const row of typeCountsList) {
|
||||||
|
typeCounts[row.file_type || 'image'] = row.count;
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...stats,
|
...stats,
|
||||||
formats: formatStats
|
formats: formatStats,
|
||||||
|
typeCounts
|
||||||
};
|
};
|
||||||
} finally {
|
} finally {
|
||||||
this.dbPool.release(library.path);
|
this.dbPool.release(library.path);
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ const { getSettings } = require('./settings');
|
|||||||
const HUB_URL = (process.env.HUB_URL || 'https://auth.88531.cn/api').replace(/\/+$/, '');
|
const HUB_URL = (process.env.HUB_URL || 'https://auth.88531.cn/api').replace(/\/+$/, '');
|
||||||
const HUB_PROJECT_ID = process.env.HUB_PROJECT_ID || '';
|
const HUB_PROJECT_ID = process.env.HUB_PROJECT_ID || '';
|
||||||
const HUB_API_KEY = process.env.HUB_API_KEY || '';
|
const HUB_API_KEY = process.env.HUB_API_KEY || '';
|
||||||
const SITE_VERSION = process.env.SITE_VERSION || '1.4.2';
|
const SITE_VERSION = process.env.SITE_VERSION || '1.4.15';
|
||||||
const TIMEOUT_MS = 8000;
|
const TIMEOUT_MS = 8000;
|
||||||
|
|
||||||
const state = {
|
const state = {
|
||||||
|
|||||||
@@ -23,13 +23,24 @@ const DEFAULTS = {
|
|||||||
provider: 'newapi', // 'newapi' | 'custom'
|
provider: 'newapi', // 'newapi' | 'custom'
|
||||||
newapi: {
|
newapi: {
|
||||||
url: 'http://192.168.68.19:3099/v1',
|
url: 'http://192.168.68.19:3099/v1',
|
||||||
apiKey: '' // 留空则用服务器环境变量 NEWAPI_KEY
|
apiKey: '', // 留空则用服务器环境变量 NEWAPI_KEY
|
||||||
|
model: 'flux-schnell' // 默认生图模型(弹窗不再选模型,统一在设置里配)
|
||||||
},
|
},
|
||||||
custom: {
|
custom: {
|
||||||
url: '',
|
url: '',
|
||||||
apiKey: '',
|
apiKey: '',
|
||||||
model: ''
|
model: ''
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
// AI 视频:一句话/文本/网页/文档 → 带字幕配音的成片
|
||||||
|
// provider='inherit' 复用上面的 AI 生图配置;'custom' 用下面自定义的文本模型
|
||||||
|
videoai: {
|
||||||
|
provider: 'inherit',
|
||||||
|
custom: {
|
||||||
|
url: '',
|
||||||
|
model: '',
|
||||||
|
apiKey: ''
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -57,6 +68,7 @@ function getSettings() {
|
|||||||
provider: (data.imagegen && data.imagegen.provider) === 'custom' ? 'custom' : 'newapi',
|
provider: (data.imagegen && data.imagegen.provider) === 'custom' ? 'custom' : 'newapi',
|
||||||
newapi: {
|
newapi: {
|
||||||
url: (data.imagegen && data.imagegen.newapi && data.imagegen.newapi.url) || DEFAULTS.imagegen.newapi.url,
|
url: (data.imagegen && data.imagegen.newapi && data.imagegen.newapi.url) || DEFAULTS.imagegen.newapi.url,
|
||||||
|
model: (data.imagegen && data.imagegen.newapi && data.imagegen.newapi.model) || DEFAULTS.imagegen.newapi.model,
|
||||||
apiKey: (data.imagegen && data.imagegen.newapi && data.imagegen.newapi.apiKey) || ''
|
apiKey: (data.imagegen && data.imagegen.newapi && data.imagegen.newapi.apiKey) || ''
|
||||||
},
|
},
|
||||||
custom: {
|
custom: {
|
||||||
@@ -64,6 +76,14 @@ function getSettings() {
|
|||||||
apiKey: (data.imagegen && data.imagegen.custom && data.imagegen.custom.apiKey) || '',
|
apiKey: (data.imagegen && data.imagegen.custom && data.imagegen.custom.apiKey) || '',
|
||||||
model: (data.imagegen && data.imagegen.custom && data.imagegen.custom.model) || ''
|
model: (data.imagegen && data.imagegen.custom && data.imagegen.custom.model) || ''
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
videoai: {
|
||||||
|
provider: (data.videoai && data.videoai.provider) === 'custom' ? 'custom' : 'inherit',
|
||||||
|
custom: {
|
||||||
|
url: (data.videoai && data.videoai.custom && data.videoai.custom.url) || '',
|
||||||
|
model: (data.videoai && data.videoai.custom && data.videoai.custom.model) || '',
|
||||||
|
apiKey: (data.videoai && data.videoai.custom && data.videoai.custom.apiKey) || ''
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -93,6 +113,7 @@ function saveSettings(settings) {
|
|||||||
if (ig.provider === 'custom' || ig.provider === 'newapi') merged.imagegen.provider = ig.provider;
|
if (ig.provider === 'custom' || ig.provider === 'newapi') merged.imagegen.provider = ig.provider;
|
||||||
if (ig.newapi) {
|
if (ig.newapi) {
|
||||||
if (typeof ig.newapi.url === 'string') merged.imagegen.newapi.url = ig.newapi.url.trim();
|
if (typeof ig.newapi.url === 'string') merged.imagegen.newapi.url = ig.newapi.url.trim();
|
||||||
|
if (typeof ig.newapi.model === 'string') merged.imagegen.newapi.model = ig.newapi.model.trim() || 'flux-schnell';
|
||||||
const k = ig.newapi.apiKey;
|
const k = ig.newapi.apiKey;
|
||||||
// 空串/掩码 = 保持原值(与 OCR 行为一致)
|
// 空串/掩码 = 保持原值(与 OCR 行为一致)
|
||||||
if (typeof k === 'string' && k.trim() && !k.includes('***')) {
|
if (typeof k === 'string' && k.trim() && !k.includes('***')) {
|
||||||
@@ -108,6 +129,19 @@ function saveSettings(settings) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (settings.videoai) {
|
||||||
|
const va = settings.videoai;
|
||||||
|
if (va.provider === 'custom' || va.provider === 'inherit') merged.videoai.provider = va.provider;
|
||||||
|
if (va.custom) {
|
||||||
|
if (typeof va.custom.url === 'string') merged.videoai.custom.url = va.custom.url.trim();
|
||||||
|
if (typeof va.custom.model === 'string') merged.videoai.custom.model = va.custom.model.trim();
|
||||||
|
const vk = va.custom.apiKey;
|
||||||
|
// 空串/掩码 = 保持原密钥
|
||||||
|
if (typeof vk === 'string' && vk.trim() && !vk.includes('***')) {
|
||||||
|
merged.videoai.custom.apiKey = vk.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
fs.writeFileSync(p, JSON.stringify(merged, null, 2));
|
fs.writeFileSync(p, JSON.stringify(merged, null, 2));
|
||||||
return merged;
|
return merged;
|
||||||
}
|
}
|
||||||
@@ -119,4 +153,36 @@ function maskKey(key) {
|
|||||||
return `${key.slice(0, 4)}***${key.slice(-4)}`;
|
return `${key.slice(0, 4)}***${key.slice(-4)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { getSettings, saveSettings, maskKey, settingsPath };
|
/**
|
||||||
|
* 解析 AI 视频使用的文本大模型配置
|
||||||
|
* - 设置-AI 视频里选了「自定义」且填了地址 → 用自定义
|
||||||
|
* - 否则复用 AI 生图配置(内置 NewAPI / 自定义提供商)
|
||||||
|
* 普通文本模型(chat/completions)即可,全流程由后端写分镜、TTS 配音、合成字幕。
|
||||||
|
*/
|
||||||
|
function resolveVideoGen(settings) {
|
||||||
|
const s = settings || getSettings();
|
||||||
|
const va = (s && s.videoai) || {};
|
||||||
|
const ig = (s && s.imagegen) || {};
|
||||||
|
const defModel = process.env.NEWAPI_TEXT_MODEL || 'mimo-v2.6-flash';
|
||||||
|
if (va.provider === 'custom' && va.custom && va.custom.url) {
|
||||||
|
return {
|
||||||
|
url: String(va.custom.url).replace(/\/+$/, ''),
|
||||||
|
model: va.custom.model || defModel,
|
||||||
|
apiKey: va.custom.apiKey || process.env.NEWAPI_KEY || ''
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (ig.provider === 'custom' && ig.custom) {
|
||||||
|
return {
|
||||||
|
url: String(ig.custom.url || '').replace(/\/+$/, ''),
|
||||||
|
model: ig.custom.model || defModel,
|
||||||
|
apiKey: ig.custom.apiKey || process.env.NEWAPI_KEY || ''
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
url: String((ig.newapi && ig.newapi.url) || 'http://192.168.68.19:3099/v1').replace(/\/+$/, ''),
|
||||||
|
model: defModel,
|
||||||
|
apiKey: ((ig.newapi && ig.newapi.apiKey) || process.env.NEWAPI_KEY || '')
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { getSettings, saveSettings, maskKey, settingsPath, resolveVideoGen };
|
||||||
@@ -365,23 +365,43 @@ async function stripSubtitleAudio(input, output, { removeAudio = true, removeSub
|
|||||||
* AI 生成视频素材装配(分段:图 + 该段字幕 + 该段配音)
|
* AI 生成视频素材装配(分段:图 + 该段字幕 + 该段配音)
|
||||||
* @param {object} seg { imagePath, subtitle, ttsFile, duration } duration=该段秒数
|
* @param {object} seg { imagePath, subtitle, ttsFile, duration } duration=该段秒数
|
||||||
*/
|
*/
|
||||||
async function buildSegment(seg, outPath, { width = 1920, height = 1080, fontSizePct = 5 } = {}) {
|
async function buildSegment(seg, outPath, { width = 1920, height = 1080, fontSizePct = 5, subtitleStyle = {} } = {}) {
|
||||||
const dir = tmpDir();
|
const dir = tmpDir();
|
||||||
try {
|
try {
|
||||||
const tFile = path.join(dir, 'sub.txt');
|
const tFile = path.join(dir, 'sub.txt');
|
||||||
fs.writeFileSync(tFile, seg.subtitle || '', 'utf8');
|
fs.writeFileSync(tFile, seg.subtitle || '', 'utf8');
|
||||||
const textFile = tFile;
|
const textFile = tFile;
|
||||||
const fontSize = Math.max(12, Math.round((height * fontSizePct) / 100));
|
const fontSize = Math.max(12, Math.round((height * (subtitleStyle.fontSizePct || fontSizePct)) / 100));
|
||||||
|
const color = subtitleStyle.color || 'white';
|
||||||
|
const pos = subtitleStyle.position || 'bottom-center';
|
||||||
|
const yExpr = pos.startsWith('top') ? 'h*0.07' : pos === 'center' ? '(h-text_h)/2' : 'h-text_h-h*0.07';
|
||||||
|
const xExpr = pos.endsWith('left') ? 'w*0.05' : pos.endsWith('right') ? 'w-text_w-w*0.05' : '(w-text_w)/2';
|
||||||
const vf = [
|
const vf = [
|
||||||
`scale=${width}:${height}:force_original_aspect_ratio=decrease`,
|
`scale=${width}:${height}:force_original_aspect_ratio=decrease`,
|
||||||
`pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2:color=black`,
|
`pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2:color=black`,
|
||||||
`drawtext=fontfile=/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc:textfile=${textFile}:fontsize=${fontSize}:fontcolor=white@0.95:borderw=2:bordercolor=black@0.6:x=(w-text_w)/2:y=h-text_h-h*0.07:line_spacing=8`
|
`drawtext=fontfile=/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc:textfile=${textFile}:fontsize=${fontSize}:fontcolor=${color}@0.95:borderw=2:bordercolor=black@0.6:x=${xExpr}:y=${yExpr}:line_spacing=8`
|
||||||
].join(',');
|
].join(',');
|
||||||
|
|
||||||
|
const exact = seg.audioDuration != null; // 目标时长模式:画面用 duration,配音对齐 audioDuration
|
||||||
|
const vDur = Math.max(0.5, Number(seg.duration) || 4);
|
||||||
const args = [
|
const args = [
|
||||||
'-y', '-loop', '1', '-t', seg.duration.toFixed(3), '-i', seg.imagePath
|
'-y', '-loop', '1', '-t', vDur.toFixed(3), '-i', seg.imagePath
|
||||||
];
|
];
|
||||||
if (seg.ttsFile) {
|
if (exact) {
|
||||||
|
const aDur = Math.max(0.5, Number(seg.audioDuration) || vDur);
|
||||||
|
const ttsDur = Number(seg.ttsSeconds) || 0;
|
||||||
|
let chain = '';
|
||||||
|
if (seg.ttsFile && ttsDur > aDur + 0.05) {
|
||||||
|
const f = Math.min(4.0, ttsDur / aDur); // 配音超长则加速(最多4倍),避免截断内容
|
||||||
|
chain += `atempo=${f.toFixed(4)},`;
|
||||||
|
}
|
||||||
|
chain += `atrim=0:${aDur.toFixed(3)},apad=whole_dur=${aDur.toFixed(3)}`;
|
||||||
|
const src = seg.ttsFile
|
||||||
|
? ['-i', seg.ttsFile]
|
||||||
|
: ['-f', 'lavfi', '-i', 'anullsrc=channel_layout=stereo:sample_rate=44100'];
|
||||||
|
args.push(...src, '-filter_complex', `[1:a]${chain}[a]`,
|
||||||
|
'-map', '0:v', '-map', '[a]', '-c:a', 'aac', '-ar', '44100', '-ac', '2');
|
||||||
|
} else if (seg.ttsFile) {
|
||||||
args.push('-i', seg.ttsFile, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-ar', '44100', '-ac', '2', '-shortest');
|
args.push('-i', seg.ttsFile, '-map', '0:v', '-map', '1:a', '-c:a', 'aac', '-ar', '44100', '-ac', '2', '-shortest');
|
||||||
} else {
|
} else {
|
||||||
args.push('-f', 'lavfi', '-i', 'anullsrc=channel_layout=stereo:sample_rate=44100', '-map', '0:v', '-map', '1:a', '-shortest');
|
args.push('-f', 'lavfi', '-i', 'anullsrc=channel_layout=stereo:sample_rate=44100', '-map', '0:v', '-map', '1:a', '-shortest');
|
||||||
@@ -420,6 +440,57 @@ async function concatSegments(segFiles, outPath) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 带转场拼接分段 mp4(xfade 交叉过渡 + 音频直拼)
|
||||||
|
* transition: cut/fade/slideleft/slideright/circleopen/dissolve/wipeleft/... (ffmpeg xfade 名)
|
||||||
|
* 失败时回退为普通硬拼接
|
||||||
|
*/
|
||||||
|
async function concatWithTransition(segFiles, outPath, { transition = 'fade', width = 1920, height = 1080 } = {}) {
|
||||||
|
const n = segFiles.length;
|
||||||
|
if (n <= 1 || !transition || transition === 'cut') return concatSegments(segFiles, outPath);
|
||||||
|
const F = 0.6; // 转场时长(秒)
|
||||||
|
const dir = tmpDir();
|
||||||
|
try {
|
||||||
|
// 探测每段真实时长,用于计算 xfade offset
|
||||||
|
const durs = [];
|
||||||
|
for (const f of segFiles) {
|
||||||
|
const p = await probeVideo(f);
|
||||||
|
durs.push(p.duration > 0.2 ? p.duration : 4);
|
||||||
|
}
|
||||||
|
const inputs = [];
|
||||||
|
for (const f of segFiles) inputs.push('-i', f);
|
||||||
|
const filters = [];
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
filters.push(`[${i}:v]scale=${width}:${height}:force_original_aspect_ratio=decrease,pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2,setsar=1,format=yuv420p,fps=30[v${i}]`);
|
||||||
|
}
|
||||||
|
let prev = 'v0';
|
||||||
|
let acc = durs[0];
|
||||||
|
for (let i = 1; i < n; i++) {
|
||||||
|
const offset = Math.max(0, acc - F);
|
||||||
|
const out = i === n - 1 ? 'vx' : `x${i}`;
|
||||||
|
filters.push(`[${prev}][v${i}]xfade=transition=${transition}:duration=${F}:offset=${offset.toFixed(3)}[${out}]`);
|
||||||
|
prev = out;
|
||||||
|
acc = acc + durs[i] - F;
|
||||||
|
}
|
||||||
|
const audioInputs = segFiles.map((_, i) => `[${i}:a]`).join('');
|
||||||
|
filters.push(`${audioInputs}concat=n=${n}:v=0:a=1[aout]`);
|
||||||
|
const args = [
|
||||||
|
'-y', ...inputs, '-filter_complex', filters.join(';'),
|
||||||
|
'-map', '[vx]', '-map', '[aout]',
|
||||||
|
'-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20',
|
||||||
|
'-pix_fmt', 'yuv420p', '-movflags', '+faststart', outPath
|
||||||
|
];
|
||||||
|
await run(FFMPEG, args, { timeoutMs: 600 * 1000 });
|
||||||
|
return outPath;
|
||||||
|
} catch (err) {
|
||||||
|
// 转场失败回退硬拼接,保证出片
|
||||||
|
logger.warn && logger.warn(`⚠️ 转场拼接失败,回退硬拼接: ${err.message}`);
|
||||||
|
return concatSegments(segFiles, outPath);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
run,
|
run,
|
||||||
probeVideo,
|
probeVideo,
|
||||||
@@ -430,5 +501,6 @@ module.exports = {
|
|||||||
generateTts,
|
generateTts,
|
||||||
buildSegment,
|
buildSegment,
|
||||||
concatSegments,
|
concatSegments,
|
||||||
|
concatWithTransition,
|
||||||
textToSrt
|
textToSrt
|
||||||
};
|
};
|
||||||
+3
-5
@@ -10,10 +10,8 @@ services:
|
|||||||
ports:
|
ports:
|
||||||
- "15002:15002"
|
- "15002:15002"
|
||||||
volumes:
|
volumes:
|
||||||
# 素材库目录(容器内路径与飞牛一致,直接填实际路径即可)
|
# 数据盘整盘挂载(容器内路径与飞牛一致):/vol2/1000/HD2 下任意子目录(含以后新建的)可直接添加为素材库,无需改配置
|
||||||
- /vol2/1000/HD2/壁纸:/vol2/1000/HD2/壁纸
|
- /vol2/1000/HD2:/vol2/1000/HD2
|
||||||
- /vol2/1000/HD2/我的文档:/vol2/1000/HD2/我的文档
|
|
||||||
- /vol2/1000/HD2/发布到平台的图片和视频:/vol2/1000/HD2/发布到平台的图片和视频
|
|
||||||
# 持久化配置(config.json 存储素材库路径、密码等,不用改)
|
# 持久化配置(config.json 存储素材库路径、密码等,不用改)
|
||||||
- /vol3/1000/HD3/docker/flypic/config:/root/.flypic
|
- /vol3/1000/HD3/docker/flypic/config:/root/.flypic
|
||||||
environment:
|
environment:
|
||||||
@@ -28,7 +26,7 @@ services:
|
|||||||
- HUB_API_KEY=${HUB_API_KEY:-}
|
- HUB_API_KEY=${HUB_API_KEY:-}
|
||||||
- NEWAPI_KEY=${NEWAPI_KEY:-}
|
- NEWAPI_KEY=${NEWAPI_KEY:-}
|
||||||
# 当前站点版本(与 frontend/package.json、CHANGELOG 保持一致,界面版本徽标来源)
|
# 当前站点版本(与 frontend/package.json、CHANGELOG 保持一致,界面版本徽标来源)
|
||||||
- SITE_VERSION=1.4.2
|
- SITE_VERSION=1.4.18
|
||||||
# 让容器经 host.docker.internal 访问宿主机的 AI 侧车
|
# 让容器经 host.docker.internal 访问宿主机的 AI 侧车
|
||||||
extra_hosts:
|
extra_hosts:
|
||||||
- "host.docker.internal:host-gateway"
|
- "host.docker.internal:host-gateway"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "flypic-frontend",
|
"name": "flypic-frontend",
|
||||||
"version": "1.4.0",
|
"version": "1.4.18",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
+27
-5
@@ -14,6 +14,7 @@ import Header from './components/Header';
|
|||||||
import LibraryMissingModal from './components/LibraryMissingModal';
|
import LibraryMissingModal from './components/LibraryMissingModal';
|
||||||
import BackToTop from './components/BackToTop';
|
import BackToTop from './components/BackToTop';
|
||||||
import ImageEditor from './components/ImageEditor';
|
import ImageEditor from './components/ImageEditor';
|
||||||
|
import VideoEditModal from './components/VideoEditModal';
|
||||||
import { createLogger } from './utils/logger';
|
import { createLogger } from './utils/logger';
|
||||||
|
|
||||||
const logger = createLogger('App');
|
const logger = createLogger('App');
|
||||||
@@ -22,13 +23,14 @@ function App() {
|
|||||||
// 使用统一的主题管理 Hook
|
// 使用统一的主题管理 Hook
|
||||||
useTheme();
|
useTheme();
|
||||||
|
|
||||||
const { mobileView, setMobileView } = useUIStore();
|
const { mobileView, setMobileView, videoEditFile, setVideoEditFile } = useUIStore();
|
||||||
const {
|
const {
|
||||||
setLibraries,
|
setLibraries,
|
||||||
setCurrentLibrary,
|
setCurrentLibrary,
|
||||||
removeLibrary,
|
removeLibrary,
|
||||||
setShowAddLibraryForm,
|
setShowAddLibraryForm,
|
||||||
triggerExpandLibrarySelector
|
triggerExpandLibrarySelector,
|
||||||
|
currentLibraryId
|
||||||
} = useLibraryStore();
|
} = useLibraryStore();
|
||||||
const { selectedImage } = useImageStore();
|
const { selectedImage } = useImageStore();
|
||||||
const { setScanProgress } = useScanStore();
|
const { setScanProgress } = useScanStore();
|
||||||
@@ -147,6 +149,7 @@ function App() {
|
|||||||
}
|
}
|
||||||
useImageStore.getState().setTotalImageCount(statsRes.total || 0);
|
useImageStore.getState().setTotalImageCount(statsRes.total || 0);
|
||||||
useImageStore.getState().setTotalSize(statsRes.totalSize || 0);
|
useImageStore.getState().setTotalSize(statsRes.totalSize || 0);
|
||||||
|
useImageStore.getState().setTypeCounts(statsRes.typeCounts);
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
logger.error('扫描完成后加载数据失败:', err.message);
|
logger.error('扫描完成后加载数据失败:', err.message);
|
||||||
}).finally(() => {
|
}).finally(() => {
|
||||||
@@ -186,6 +189,7 @@ function App() {
|
|||||||
// 注意:后端返回的字段是 total 和 totalSize
|
// 注意:后端返回的字段是 total 和 totalSize
|
||||||
useImageStore.getState().setTotalImageCount(statsResponse.total || 0);
|
useImageStore.getState().setTotalImageCount(statsResponse.total || 0);
|
||||||
useImageStore.getState().setTotalSize(statsResponse.totalSize || 0);
|
useImageStore.getState().setTotalSize(statsResponse.totalSize || 0);
|
||||||
|
useImageStore.getState().setTypeCounts(statsResponse.typeCounts);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('加载文件夹失败:', error.message);
|
logger.error('加载文件夹失败:', error.message);
|
||||||
}
|
}
|
||||||
@@ -515,6 +519,15 @@ function App() {
|
|||||||
onCreateNew={handleCreateNewLibrary}
|
onCreateNew={handleCreateNewLibrary}
|
||||||
/>
|
/>
|
||||||
<ImageEditor />
|
<ImageEditor />
|
||||||
|
{/* 视频编辑弹窗(store 全局状态,右侧面板/瀑布流均可触发) */}
|
||||||
|
{videoEditFile && (
|
||||||
|
<VideoEditModal
|
||||||
|
file={videoEditFile}
|
||||||
|
libraryId={currentLibraryId}
|
||||||
|
onClose={() => setVideoEditFile(null)}
|
||||||
|
onDone={() => { setVideoEditFile(null); window.location.reload(); }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
<div className="flex-1 overflow-hidden relative">
|
<div className="flex-1 overflow-hidden relative">
|
||||||
{/* 侧边栏视图 */}
|
{/* 侧边栏视图 */}
|
||||||
<div className={`absolute inset-0 transition-transform duration-300 ${mobileView === 'sidebar' ? 'translate-x-0' : '-translate-x-full'
|
<div className={`absolute inset-0 transition-transform duration-300 ${mobileView === 'sidebar' ? 'translate-x-0' : '-translate-x-full'
|
||||||
@@ -590,6 +603,15 @@ function App() {
|
|||||||
onCreateNew={handleCreateNewLibrary}
|
onCreateNew={handleCreateNewLibrary}
|
||||||
/>
|
/>
|
||||||
<ImageEditor />
|
<ImageEditor />
|
||||||
|
{/* 视频编辑弹窗(store 全局状态,右侧面板/瀑布流均可触发) */}
|
||||||
|
{videoEditFile && (
|
||||||
|
<VideoEditModal
|
||||||
|
file={videoEditFile}
|
||||||
|
libraryId={currentLibraryId}
|
||||||
|
onClose={() => setVideoEditFile(null)}
|
||||||
|
onDone={() => { setVideoEditFile(null); window.location.reload(); }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
<div ref={containerRef} className="flex flex-1 overflow-hidden">
|
<div ref={containerRef} className="flex flex-1 overflow-hidden">
|
||||||
{/* 左侧边栏 */}
|
{/* 左侧边栏 */}
|
||||||
<div id="left-panel" style={{ width: `${leftWidth}px` }} className="flex-shrink-0 h-full bg-white dark:bg-gray-800">
|
<div id="left-panel" style={{ width: `${leftWidth}px` }} className="flex-shrink-0 h-full bg-white dark:bg-gray-800">
|
||||||
|
|||||||
@@ -19,3 +19,9 @@ export async function status(taskId) {
|
|||||||
export async function cancel(taskId) {
|
export async function cancel(taskId) {
|
||||||
return api.post(`/batch/cancel/${taskId}`);
|
return api.post(`/batch/cancel/${taskId}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 批量重命名预览(不执行),返回 { count, total, samples: [{from,to}], skipped } */
|
||||||
|
export async function renamePreview(payload) {
|
||||||
|
// payload: { libraryId, folder, options: { mode, text, includeSubdirs } }
|
||||||
|
return api.post('/batch/rename-preview', payload);
|
||||||
|
}
|
||||||
@@ -50,7 +50,8 @@ export async function getCacheMeta(libraryId) {
|
|||||||
* 使用分片结构,不再需要 size 参数
|
* 使用分片结构,不再需要 size 参数
|
||||||
*/
|
*/
|
||||||
export function getThumbnailUrl(libraryId, filename, version) {
|
export function getThumbnailUrl(libraryId, filename, version) {
|
||||||
const base = `/api/image/thumbnail/${libraryId}/${filename}`;
|
const encoded = encodeURIComponent(filename);
|
||||||
|
const base = `/api/image/thumbnail/${libraryId}/${encoded}`;
|
||||||
// version=文件 modified_at,编辑保存后变化以穿透浏览器缓存
|
// version=文件 modified_at,编辑保存后变化以穿透浏览器缓存
|
||||||
return version ? `${base}?v=${version}` : base;
|
return version ? `${base}?v=${version}` : base;
|
||||||
}
|
}
|
||||||
@@ -59,7 +60,9 @@ export function getThumbnailUrl(libraryId, filename, version) {
|
|||||||
* 获取原图 URL
|
* 获取原图 URL
|
||||||
*/
|
*/
|
||||||
export function getOriginalUrl(libraryId, path) {
|
export function getOriginalUrl(libraryId, path) {
|
||||||
return `/api/image/original/${libraryId}/${path}`;
|
// 按 '/' 分段编码,避免中文/空格/#/? 等字符导致原图 URL 404(灯箱/新窗口打开失败)
|
||||||
|
const encoded = String(path).split('/').map(encodeURIComponent).join('/');
|
||||||
|
return `/api/image/original/${libraryId}/${encoded}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { useState, useEffect, useRef, useCallback } from 'react';
|
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||||
import {
|
import {
|
||||||
X, Wand2, Loader2, Download, Save, RefreshCw, Sparkles,
|
X, Wand2, Loader2, Download, Save, RefreshCw, Sparkles,
|
||||||
ChevronDown, FolderOpen, CheckCircle2, AlertTriangle
|
ChevronDown, FolderOpen, CheckCircle2, AlertTriangle,
|
||||||
|
Image as ImageIcon, Search, Plus, Trash2
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { aigenAPI, fileAPI, imageAPI } from '../api';
|
import { aigenAPI, fileAPI, imageAPI } from '../api';
|
||||||
import { useLibraryStore } from '../stores/useLibraryStore';
|
import { useLibraryStore } from '../stores/useLibraryStore';
|
||||||
@@ -11,7 +12,7 @@ import { PROMPT_CATEGORIES } from '../constants/promptPresets';
|
|||||||
/**
|
/**
|
||||||
* AI 生图弹窗
|
* AI 生图弹窗
|
||||||
* - 热门提示词分类(点击填入/追加)
|
* - 热门提示词分类(点击填入/追加)
|
||||||
* - 内置模型(NewAPI:CF Workers AI / Pollinations)+ 自定义提供商
|
* - 弹窗内点选生图模型(列表来自设置配置的模型分组),KEY/通道仍在「设置 → AI 生图」
|
||||||
* - 生成 → 预览 → 保存到素材库 / 下载 / 重新生成
|
* - 生成 → 预览 → 保存到素材库 / 下载 / 重新生成
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -34,12 +35,11 @@ export default function AIGenModal({ open, onClose, onSaved }) {
|
|||||||
|
|
||||||
const [prompt, setPrompt] = useState('');
|
const [prompt, setPrompt] = useState('');
|
||||||
const [cat, setCat] = useState('hot');
|
const [cat, setCat] = useState('hot');
|
||||||
const [groups, setGroups] = useState([]);
|
|
||||||
const [sizes, setSizes] = useState([]);
|
const [sizes, setSizes] = useState([]);
|
||||||
const [providerInfo, setProviderInfo] = useState(null);
|
const [providerInfo, setProviderInfo] = useState(null);
|
||||||
const [model, setModel] = useState('flux-schnell');
|
const [modelGroups, setModelGroups] = useState([]); // 可选生图模型分组
|
||||||
|
const [selModel, setSelModel] = useState(''); // 用户点选的模型 id(空=设置默认)
|
||||||
const [size, setSize] = useState('1024x1024');
|
const [size, setSize] = useState('1024x1024');
|
||||||
const [useCustom, setUseCustom] = useState(false);
|
|
||||||
|
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
@@ -49,6 +49,13 @@ export default function AIGenModal({ open, onClose, onSaved }) {
|
|||||||
const [saved, setSaved] = useState(false);
|
const [saved, setSaved] = useState(false);
|
||||||
const [showFolderPick, setShowFolderPick] = useState(false);
|
const [showFolderPick, setShowFolderPick] = useState(false);
|
||||||
const [advanced, setAdvanced] = useState(false);
|
const [advanced, setAdvanced] = useState(false);
|
||||||
|
|
||||||
|
// 参考图(以图生图)
|
||||||
|
const [refs, setRefs] = useState([]); // [{ path, filename, thumbnailPath }]
|
||||||
|
const [showRefPicker, setShowRefPicker] = useState(false);
|
||||||
|
const [refList, setRefList] = useState([]);
|
||||||
|
const [refQuery, setRefQuery] = useState('');
|
||||||
|
const [refLoading, setRefLoading] = useState(false);
|
||||||
const imgRef = useRef(null);
|
const imgRef = useRef(null);
|
||||||
|
|
||||||
// 打开时拉模型列表 + 当前配置
|
// 打开时拉模型列表 + 当前配置
|
||||||
@@ -57,19 +64,66 @@ export default function AIGenModal({ open, onClose, onSaved }) {
|
|||||||
setError('');
|
setError('');
|
||||||
setResult(null);
|
setResult(null);
|
||||||
setSaved(false);
|
setSaved(false);
|
||||||
|
setRefs([]);
|
||||||
|
setShowRefPicker(false);
|
||||||
|
setRefQuery('');
|
||||||
aigenAPI.getModels()
|
aigenAPI.getModels()
|
||||||
.then((d) => {
|
.then((d) => {
|
||||||
setGroups(d.groups || []);
|
|
||||||
setSizes(d.sizes || []);
|
setSizes(d.sizes || []);
|
||||||
setProviderInfo(d.provider || null);
|
setProviderInfo(d.provider || null);
|
||||||
const first = (d.groups || [])[0];
|
const groups = d.groups || [];
|
||||||
if (first && first.models && first.models[0]) setModel(first.models[0].id);
|
setModelGroups(groups);
|
||||||
if (d.provider && d.provider.type === 'custom') setUseCustom(true);
|
const all = groups.flatMap((g) => (g.models || []).map((m) => m.id));
|
||||||
|
const p = d.provider || {};
|
||||||
|
// 自定义提供商:只有设置里填的那个模型可用
|
||||||
|
if (p.type === 'custom') { setSelModel(p.customModel || ''); return; }
|
||||||
|
const def = p.builtinModel || 'flux-schnell';
|
||||||
|
const saved = localStorage.getItem('flypic_aigen_model');
|
||||||
|
setSelModel(all.includes(saved) ? saved : (all.includes(def) ? def : (all[0] || def)));
|
||||||
})
|
})
|
||||||
.catch((e) => setError('读取模型列表失败: ' + (e.data?.error || e.message)));
|
.catch((e) => setError('读取模型列表失败: ' + (e.data?.error || e.message)));
|
||||||
}, [open]);
|
}, [open]);
|
||||||
|
|
||||||
const currentModelId = useCustom ? (providerInfo?.customModel || '') : model;
|
/** 素材库缩略图地址 */
|
||||||
|
const thumbUrl = (img) => {
|
||||||
|
if (!img || !currentLibraryId) return '';
|
||||||
|
const raw = img.thumbnailPath || img.path || img.filename || '';
|
||||||
|
const fn = String(raw).replace(/\\/g, '/').split('/').pop();
|
||||||
|
return `/api/image/thumbnail/${currentLibraryId}/${encodeURIComponent(fn)}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 打开素材库选图:读当前库的图片(只图片,不含视频) */
|
||||||
|
const openRefPicker = async () => {
|
||||||
|
setShowRefPicker(true);
|
||||||
|
setRefLoading(true);
|
||||||
|
setRefList([]);
|
||||||
|
try {
|
||||||
|
const resp = await imageAPI.search(currentLibraryId, { limit: 200, offset: 0, q: refQuery || undefined });
|
||||||
|
const list = (resp.images || []).filter((it) => {
|
||||||
|
const t = String(it.fileType || it.type || '').toLowerCase();
|
||||||
|
if (t === 'video') return false;
|
||||||
|
const ext = String(it.filename || it.path || '').split('.').pop().toLowerCase();
|
||||||
|
return !['mp4', 'mov', 'mkv', 'webm', 'avi', 'm4v', 'ts', 'flv'].includes(ext);
|
||||||
|
});
|
||||||
|
setRefList(list);
|
||||||
|
} catch (e) {
|
||||||
|
setError('读取素材库图片失败: ' + (e.data?.error || e.message));
|
||||||
|
} finally {
|
||||||
|
setRefLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const isPickedRef = (img) => refs.some((r) => r.path === img.path);
|
||||||
|
|
||||||
|
const toggleRef = (img) => {
|
||||||
|
setError('');
|
||||||
|
if (isPickedRef(img)) {
|
||||||
|
setRefs((prev) => prev.filter((r) => r.path !== img.path));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (refs.length >= 4) { setError('最多选 4 张参考图'); return; }
|
||||||
|
setRefs((prev) => [...prev, img]);
|
||||||
|
};
|
||||||
const handleGenerate = async () => {
|
const handleGenerate = async () => {
|
||||||
if (!prompt.trim()) { setError('请先输入提示词,或点一个热门提示词'); return; }
|
if (!prompt.trim()) { setError('请先输入提示词,或点一个热门提示词'); return; }
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -78,9 +132,10 @@ export default function AIGenModal({ open, onClose, onSaved }) {
|
|||||||
try {
|
try {
|
||||||
const d = await aigenAPI.generate({
|
const d = await aigenAPI.generate({
|
||||||
prompt: prompt.trim(),
|
prompt: prompt.trim(),
|
||||||
model: useCustom ? undefined : model,
|
model: selModel || undefined,
|
||||||
size,
|
size,
|
||||||
provider: useCustom ? 'custom' : 'builtin'
|
libraryId: currentLibraryId,
|
||||||
|
refImages: refs.map((r) => ({ path: r.path, filename: r.filename })),
|
||||||
});
|
});
|
||||||
const img = d.images && d.images[0];
|
const img = d.images && d.images[0];
|
||||||
if (!img || !img.b64) throw new Error('未返回图片数据');
|
if (!img || !img.b64) throw new Error('未返回图片数据');
|
||||||
@@ -138,19 +193,19 @@ export default function AIGenModal({ open, onClose, onSaved }) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const appendPrompt = (p) => {
|
const appendPrompt = (p) => {
|
||||||
setPrompt((prev) => (prev.trim() ? prev.replace(/[,,、\s]+$/, '') + ',' + p : p));
|
setPrompt(p);
|
||||||
setError('');
|
setError('');
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!open) return null;
|
if (!open) return null;
|
||||||
|
|
||||||
const activeCat = PROMPT_CATEGORIES.find((c) => c.key === cat) || PROMPT_CATEGORIES[0];
|
const activeCat = PROMPT_CATEGORIES.find((c) => c.key === cat) || PROMPT_CATEGORIES[0];
|
||||||
const noKey = providerInfo && !providerInfo.hasKey && !useCustom;
|
const noKey = providerInfo && !providerInfo.hasKey && providerInfo.type !== 'custom';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
|
||||||
<div
|
<div
|
||||||
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-5xl max-h-[90vh] overflow-hidden flex flex-col"
|
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-[98vw] h-[98vh] max-w-none max-h-none overflow-hidden flex flex-col"
|
||||||
onClick={(e) => e.stopPropagation()}
|
onClick={(e) => e.stopPropagation()}
|
||||||
>
|
>
|
||||||
{/* 头部 */}
|
{/* 头部 */}
|
||||||
@@ -210,14 +265,16 @@ export default function AIGenModal({ open, onClose, onSaved }) {
|
|||||||
{activeCat.prompts.map((p) => (
|
{activeCat.prompts.map((p) => (
|
||||||
<button
|
<button
|
||||||
key={p.name}
|
key={p.name}
|
||||||
onClick={() => appendPrompt(p.prompt)}
|
onClick={() => appendPrompt(p.promptCn)}
|
||||||
title={p.prompt}
|
title={p.promptCn}
|
||||||
className="text-left px-2.5 py-2 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-purple-400 dark:hover:border-purple-500 hover:bg-purple-50 dark:hover:bg-purple-500/10 transition-colors group"
|
className="text-left px-2.5 py-2 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-purple-400 dark:hover:border-purple-500 hover:bg-purple-50 dark:hover:bg-purple-500/10 transition-colors group"
|
||||||
>
|
>
|
||||||
<div className="text-xs font-medium text-gray-800 dark:text-gray-200 truncate group-hover:text-purple-700 dark:group-hover:text-purple-300">
|
<div className="text-xs font-medium text-gray-800 dark:text-gray-200 truncate group-hover:text-purple-700 dark:group-hover:text-purple-300">
|
||||||
{p.name}
|
{p.name}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-[10px] text-gray-400 dark:text-gray-500 truncate">{p.prompt}</div>
|
<div className="mt-0.5 text-[10px] leading-4 text-gray-400 dark:text-gray-500 line-clamp-2 group-hover:text-gray-500 dark:group-hover:text-gray-400">
|
||||||
|
{p.promptCn}
|
||||||
|
</div>
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -226,62 +283,112 @@ export default function AIGenModal({ open, onClose, onSaved }) {
|
|||||||
|
|
||||||
{/* 右:参数 + 生成 */}
|
{/* 右:参数 + 生成 */}
|
||||||
<div className="lg:col-span-2 space-y-3.5">
|
<div className="lg:col-span-2 space-y-3.5">
|
||||||
{/* 提供商 */}
|
{/* 生图模型:列出可点选的模型 */}
|
||||||
<div>
|
<div className="px-3 py-2.5 rounded-lg bg-gray-50 dark:bg-gray-900/40 border border-gray-200 dark:border-gray-700">
|
||||||
<label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">模型提供商</label>
|
<div className="flex items-center justify-between mb-2">
|
||||||
<select
|
<span className="text-xs font-medium text-gray-500 dark:text-gray-400">生图模型</span>
|
||||||
value={useCustom ? 'custom' : 'builtin'}
|
|
||||||
onChange={(e) => setUseCustom(e.target.value === 'custom')}
|
|
||||||
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
|
|
||||||
>
|
|
||||||
<option value="builtin">内置 NewAPI(Pollinations + CF Workers AI)</option>
|
|
||||||
<option value="custom" disabled={!providerInfo?.customModel && !providerInfo?.customUrl}>
|
|
||||||
自定义提供商{providerInfo?.customModel ? `(${providerInfo.customModel})` : '(未配置)'}
|
|
||||||
</option>
|
|
||||||
</select>
|
|
||||||
{providerInfo && !providerInfo.hasKey && !useCustom && (
|
|
||||||
<div className="mt-1.5 flex items-start gap-1.5 text-[11px] text-amber-600 dark:text-amber-400">
|
|
||||||
<AlertTriangle className="w-3.5 h-3.5 flex-shrink-0 mt-px" />
|
|
||||||
<span>
|
|
||||||
未配置 API Key。到「设置 → AI 生图」填写,或由服务器环境变量注入。
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 模型 */}
|
|
||||||
{!useCustom && (
|
|
||||||
<div>
|
|
||||||
<label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">模型</label>
|
|
||||||
<select
|
|
||||||
value={model}
|
|
||||||
onChange={(e) => setModel(e.target.value)}
|
|
||||||
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
|
|
||||||
>
|
|
||||||
{groups.map((g) => (
|
|
||||||
<optgroup key={g.key} label={g.label}>
|
|
||||||
{g.models.map((m) => (
|
|
||||||
<option key={m.id} value={m.id}>{m.name}</option>
|
|
||||||
))}
|
|
||||||
</optgroup>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{useCustom && (
|
|
||||||
<div className="p-3 bg-amber-50 dark:bg-amber-500/10 border border-amber-200 dark:border-amber-500/30 rounded-lg text-xs text-amber-700 dark:text-amber-300">
|
|
||||||
使用设置中配置的自定义提供商({providerInfo?.customUrl || '未配置地址'})。
|
|
||||||
模型:{providerInfo?.customModel || '(未配置)'}
|
|
||||||
<button
|
<button
|
||||||
onClick={() => window.dispatchEvent(new CustomEvent('open:settings', { detail: { tab: 'aigen' } }))}
|
onClick={() => window.dispatchEvent(new CustomEvent('open:settings', { detail: { tab: 'aigen' } }))}
|
||||||
className="ml-1 underline hover:text-amber-900 dark:hover:text-amber-100"
|
className="text-[11px] text-purple-600 dark:text-purple-400 hover:underline"
|
||||||
>
|
>
|
||||||
去配置
|
通道设置
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
{providerInfo && providerInfo.type === 'custom' ? (
|
||||||
|
<div className="flex flex-wrap gap-1.5">
|
||||||
|
<span className="px-2.5 py-1 rounded-full text-[11px] bg-purple-600 text-white border border-purple-600">
|
||||||
|
{providerInfo.customModel || '自定义模型'}
|
||||||
|
</span>
|
||||||
|
<span className="px-1 py-1 text-[11px] text-gray-400 dark:text-gray-500 self-center">
|
||||||
|
自定义提供商的模型在设置里配置
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
{modelGroups.map((g) => (
|
||||||
|
<div key={g.key} className="flex items-start gap-2">
|
||||||
|
<span className="text-[10px] text-gray-400 dark:text-gray-500 w-[76px] flex-shrink-0 pt-1 leading-4">{g.label}</span>
|
||||||
|
<div className="flex flex-wrap gap-1.5">
|
||||||
|
{(g.models || []).map((m) => (
|
||||||
|
<button
|
||||||
|
key={m.id}
|
||||||
|
type="button"
|
||||||
|
title={m.id}
|
||||||
|
onClick={() => { setSelModel(m.id); localStorage.setItem('flypic_aigen_model', m.id); }}
|
||||||
|
className={`px-2.5 py-1 rounded-full text-[11px] border transition-colors ${selModel === m.id
|
||||||
|
? 'bg-purple-600 text-white border-purple-600'
|
||||||
|
: 'bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-300 border-gray-200 dark:border-gray-600 hover:border-purple-400 hover:text-purple-600 dark:hover:text-purple-300'}`}
|
||||||
|
>
|
||||||
|
{m.name}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{!modelGroups.length && (
|
||||||
|
<span className="text-[11px] text-gray-400 dark:text-gray-500">读取模型列表中…</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{refs.length > 0 && (
|
||||||
|
<p className="mt-1.5 text-[11px] text-amber-600 dark:text-amber-400">
|
||||||
|
已选参考图:后端会自动切到 FLUX.2 图生图模型
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{noKey && (
|
||||||
|
<div className="flex items-start gap-1.5 text-[11px] text-amber-600 dark:text-amber-400">
|
||||||
|
<AlertTriangle className="w-3.5 h-3.5 flex-shrink-0 mt-px" />
|
||||||
|
<span>未配置 API Key。到「设置 → AI 生图」填写,或由服务器环境变量注入。</span>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* 参考图:以图生图 */}
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center justify-between mb-1.5">
|
||||||
|
<label className="text-xs font-medium text-gray-500 dark:text-gray-400">
|
||||||
|
参考图(以图生图){refs.length > 0 && <span className="text-purple-600 dark:text-purple-400">· 已选 {refs.length}/4</span>}
|
||||||
|
</label>
|
||||||
|
{refs.length > 0 && (
|
||||||
|
<button
|
||||||
|
onClick={() => setRefs([])}
|
||||||
|
className="text-[11px] text-gray-400 hover:text-red-500 flex items-center gap-0.5"
|
||||||
|
>
|
||||||
|
<Trash2 className="w-3 h-3" />清空
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1.5 flex-wrap">
|
||||||
|
{refs.map((r, i) => (
|
||||||
|
<div key={r.path || i} className="relative w-14 h-14 rounded-lg overflow-hidden border border-gray-200 dark:border-gray-600">
|
||||||
|
<img src={thumbUrl(r)} alt={r.filename || ''} className="w-full h-full object-cover" />
|
||||||
|
<button
|
||||||
|
onClick={() => toggleRef(r)}
|
||||||
|
className="absolute top-0 right-0 p-0.5 bg-black/60 text-white rounded-bl"
|
||||||
|
title="移除"
|
||||||
|
>
|
||||||
|
<X className="w-3 h-3" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{refs.length < 4 && (
|
||||||
|
<button
|
||||||
|
onClick={openRefPicker}
|
||||||
|
className="w-14 h-14 rounded-lg border-2 border-dashed border-gray-300 dark:border-gray-600 text-gray-400 hover:border-purple-400 hover:text-purple-500 flex flex-col items-center justify-center gap-0.5"
|
||||||
|
title="从素材库选择参考图"
|
||||||
|
>
|
||||||
|
<Plus className="w-4 h-4" />
|
||||||
|
<span className="text-[9px]">选图</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="mt-1 text-[11px] text-gray-400 dark:text-gray-500">
|
||||||
|
{refs.length > 0
|
||||||
|
? '将按参考图生成(自动切到 FLUX.2 图生图模型),图片只在本机读取,不上传到第三方'
|
||||||
|
: '选 1-4 张素材库图片做参考,即可换背景、改风格、保持人物一致'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* 尺寸 */}
|
{/* 尺寸 */}
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">尺寸</label>
|
<label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">尺寸</label>
|
||||||
@@ -323,7 +430,8 @@ export default function AIGenModal({ open, onClose, onSaved }) {
|
|||||||
|
|
||||||
{loading && (
|
{loading && (
|
||||||
<div className="text-[11px] text-gray-400 dark:text-gray-500 text-center">
|
<div className="text-[11px] text-gray-400 dark:text-gray-500 text-center">
|
||||||
正在调用 {useCustom ? '自定义提供商' : (model || '')},超时上限 150 秒
|
正在调用生图服务
|
||||||
|
{refs.length > 0 ? '(以图生图,约 20-60 秒)' : ',超时上限 150 秒'}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -390,7 +498,7 @@ export default function AIGenModal({ open, onClose, onSaved }) {
|
|||||||
</button>
|
</button>
|
||||||
{showFolderPick && (
|
{showFolderPick && (
|
||||||
<>
|
<>
|
||||||
<div className="fixed inset-0 z-10" onClick={() => setShowFolderPick(false)}></div>
|
<div className="fixed inset-0 z-10"></div>
|
||||||
<div className="absolute left-0 bottom-full mb-1 z-20 w-64 max-h-64 overflow-y-auto bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-xl p-1">
|
<div className="absolute left-0 bottom-full mb-1 z-20 w-64 max-h-64 overflow-y-auto bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-xl p-1">
|
||||||
{flattenFolders(folders).map((f) => (
|
{flattenFolders(folders).map((f) => (
|
||||||
<button
|
<button
|
||||||
@@ -427,6 +535,93 @@ export default function AIGenModal({ open, onClose, onSaved }) {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* 素材库选图(以图生图) */}
|
||||||
|
{showRefPicker && (
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 p-4"
|
||||||
|
onClick={() => setShowRefPicker(false)}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-3xl max-h-[85vh] flex flex-col overflow-hidden"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-700">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<ImageIcon className="w-4 h-4 text-purple-500" />
|
||||||
|
<h3 className="text-sm font-semibold text-gray-900 dark:text-white">从素材库选择参考图</h3>
|
||||||
|
<span className="text-[11px] text-gray-400">已选 {refs.length}/4</span>
|
||||||
|
</div>
|
||||||
|
<button onClick={() => setShowRefPicker(false)} className="p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-700">
|
||||||
|
<X className="w-4 h-4 text-gray-500" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="px-4 py-2.5 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
|
||||||
|
<div className="relative flex-1">
|
||||||
|
<Search className="w-3.5 h-3.5 text-gray-400 absolute left-2.5 top-1/2 -translate-y-1/2" />
|
||||||
|
<input
|
||||||
|
value={refQuery}
|
||||||
|
onChange={(e) => setRefQuery(e.target.value)}
|
||||||
|
onKeyDown={(e) => { if (e.key === 'Enter') openRefPicker(); }}
|
||||||
|
placeholder="搜索文件名,回车查询"
|
||||||
|
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={openRefPicker}
|
||||||
|
className="px-3 py-1.5 text-xs rounded-lg bg-purple-600 text-white hover:bg-purple-700"
|
||||||
|
>
|
||||||
|
查询
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1 overflow-y-auto p-3">
|
||||||
|
{refLoading ? (
|
||||||
|
<div className="flex items-center justify-center py-16 text-xs text-gray-400 gap-2">
|
||||||
|
<Loader2 className="w-4 h-4 animate-spin" />读取图片中…
|
||||||
|
</div>
|
||||||
|
) : refList.length === 0 ? (
|
||||||
|
<div className="py-16 text-center text-xs text-gray-400">这个素材库里没有可选图片</div>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-4 sm:grid-cols-5 md:grid-cols-6 gap-2">
|
||||||
|
{refList.map((img) => {
|
||||||
|
const picked = isPickedRef(img);
|
||||||
|
const idx = refs.findIndex((r) => r.path === img.path);
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={img.path || img.filename}
|
||||||
|
onClick={() => toggleRef(img)}
|
||||||
|
title={img.filename || img.path}
|
||||||
|
className={`relative aspect-square rounded-lg overflow-hidden border-2 transition-all ${
|
||||||
|
picked ? 'border-purple-500 ring-2 ring-purple-300' : 'border-transparent hover:border-gray-300'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<img src={thumbUrl(img)} alt={img.filename || ''} className="w-full h-full object-cover" />
|
||||||
|
{picked && (
|
||||||
|
<span className="absolute top-1 left-1 w-5 h-5 rounded-full bg-purple-600 text-white text-[11px] flex items-center justify-center font-medium">
|
||||||
|
{idx + 1}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between px-4 py-2.5 border-t border-gray-200 dark:border-gray-700">
|
||||||
|
<span className="text-[11px] text-gray-400">点图多选,按点选顺序作为参考顺序</span>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowRefPicker(false)}
|
||||||
|
className="px-4 py-1.5 text-xs font-medium rounded-lg bg-purple-600 text-white hover:bg-purple-700"
|
||||||
|
>
|
||||||
|
完成
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -6,6 +6,14 @@
|
|||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import { X, Loader2, Film, CheckCircle2, AlertCircle, KeyRound } from 'lucide-react';
|
import { X, Loader2, Film, CheckCircle2, AlertCircle, KeyRound } from 'lucide-react';
|
||||||
import { imageAPI } from '../api';
|
import { imageAPI } from '../api';
|
||||||
|
import { getToken } from '../api/client';
|
||||||
|
|
||||||
|
// 后端错误可能为字符串或 {code,message} 对象,统一取可读文本
|
||||||
|
const errText = (e, fallback) => {
|
||||||
|
if (!e) return fallback;
|
||||||
|
if (typeof e === 'string') return e;
|
||||||
|
return e.message || JSON.stringify(e);
|
||||||
|
};
|
||||||
|
|
||||||
const VOICES = [
|
const VOICES = [
|
||||||
{ key: 'zh-CN-XiaoxiaoNeural', label: '晓晓(女声·自然)' },
|
{ key: 'zh-CN-XiaoxiaoNeural', label: '晓晓(女声·自然)' },
|
||||||
@@ -51,7 +59,9 @@ function AIVideoModal({ libraryId, images, onClose, onDone }) {
|
|||||||
if (!taskId) return;
|
if (!taskId) return;
|
||||||
timerRef.current = setInterval(async () => {
|
timerRef.current = setInterval(async () => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/video/task/${taskId}`);
|
const res = await fetch(`/api/video/task/${taskId}`, {
|
||||||
|
headers: { Authorization: `Bearer ${getToken()}` }
|
||||||
|
});
|
||||||
if (!res.ok) return;
|
if (!res.ok) return;
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
setTask(data);
|
setTask(data);
|
||||||
@@ -74,7 +84,10 @@ function AIVideoModal({ libraryId, images, onClose, onDone }) {
|
|||||||
try {
|
try {
|
||||||
const res = await fetch('/api/video/aigenerate', {
|
const res = await fetch('/api/video/aigenerate', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Authorization: `Bearer ${getToken()}`
|
||||||
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
libraryId,
|
libraryId,
|
||||||
images: list.map((img) => ({ path: img.path })),
|
images: list.map((img) => ({ path: img.path })),
|
||||||
@@ -86,7 +99,7 @@ function AIVideoModal({ libraryId, images, onClose, onDone }) {
|
|||||||
})
|
})
|
||||||
});
|
});
|
||||||
const data = await res.json().catch(() => ({}));
|
const data = await res.json().catch(() => ({}));
|
||||||
if (!res.ok || data.error) throw new Error(data.error || `启动失败 (${res.status})`);
|
if (!res.ok || data.error) throw new Error(errText(data.error, `启动失败 (${res.status})`));
|
||||||
setTaskId(data.taskId);
|
setTaskId(data.taskId);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError(e.message || '启动失败');
|
setError(e.message || '启动失败');
|
||||||
@@ -103,7 +116,7 @@ function AIVideoModal({ libraryId, images, onClose, onDone }) {
|
|||||||
const input = 'w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent';
|
const input = 'w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-50 bg-black bg-opacity-60 flex items-center justify-center p-4" onClick={(running || starting) ? undefined : onClose}>
|
<div className="fixed inset-0 z-50 bg-black bg-opacity-60 flex items-center justify-center p-4">
|
||||||
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-lg max-h-[92vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
|
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-lg max-h-[92vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
|
||||||
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 dark:border-gray-700">
|
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 dark:border-gray-700">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
|
|||||||
@@ -0,0 +1,461 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { X, Film, Loader2, CheckCircle2, AlertCircle, Link as LinkIcon, FileText, Image as ImageIcon, Sparkles, Search, Check, Settings } from 'lucide-react';
|
||||||
|
import { getToken } from '../api/client';
|
||||||
|
|
||||||
|
const VOICES = [
|
||||||
|
{ key: 'zh-CN-XiaoxiaoNeural', label: '晓晓(女声·自然)' },
|
||||||
|
{ key: 'zh-CN-YunxiNeural', label: '云希(男声·温暖)' },
|
||||||
|
{ key: 'zh-CN-YunjianNeural', label: '云健(男声·浑厚)' },
|
||||||
|
{ key: 'zh-CN-XiaoyiNeural', label: '晓伊(女声·活泼)' },
|
||||||
|
{ key: 'zh-CN-YunyangNeural', label: '云扬(男声·播音)' },
|
||||||
|
];
|
||||||
|
const RESOLUTIONS = [
|
||||||
|
{ key: '1920x1080', label: '横屏 1920×1080' },
|
||||||
|
{ key: '1080x1920', label: '竖屏 1080×1920' },
|
||||||
|
];
|
||||||
|
const SUBTITLE_STYLES = [
|
||||||
|
{ key: 'bottom-center', label: '底部居中', position: 'bottom-center' },
|
||||||
|
{ key: 'top-center', label: '顶部居中', position: 'top-center' },
|
||||||
|
{ key: 'center', label: '画面中央', position: 'center' },
|
||||||
|
];
|
||||||
|
const SUBTITLE_COLORS = [
|
||||||
|
{ key: 'white', label: '白色' },
|
||||||
|
{ key: '#FFD700', label: '金色' },
|
||||||
|
{ key: '#00FFCC', label: '青色' },
|
||||||
|
];
|
||||||
|
const POPULAR_PROMPTS = [
|
||||||
|
'产品功能速览:开头 3 秒抛出用户痛点,逐条演示 3 个核心卖点与真实使用场景,配合界面录屏特写与前后对比,结尾出现品牌名与一句话 slogan,节奏明快,字幕醒目',
|
||||||
|
'周末探店 vlog:从推门进店的第一视角开场,依次拍环境空镜、招牌菜特写、入口咀嚼的满足表情,穿插与店主的简短对话,轻快背景音乐,暖色调,结尾给出店名地址与推荐指数',
|
||||||
|
'知识科普:先用一个反常识的问题抓住注意力,再分三步由浅入深讲解概念,每步配一个生活化类比和简单动画示意,最后用一句话总结并抛出延伸思考,语速适中,重点处放大字幕',
|
||||||
|
'旅行日记:以清晨出发的车窗镜头开场,交替呈现沿途风景大远景、地标建筑仰拍、当地市集人文细节与个人打卡瞬间,配舒缓音乐和游记式旁白,结尾定格日落剪影并标注地点',
|
||||||
|
'健身打卡:开场展示今日训练目标与身材对比,中间分组记录动作特写、重量数据和力竭瞬间,穿插教练指导与呼吸节奏提示,热血鼓点配乐,结尾打出训练总消耗与坚持天数',
|
||||||
|
'美食制作:从食材摆盘的俯拍开场,按备料、烹饪、装盘三阶段推进,关键步骤给慢镜头特写(下锅滋响、拉丝、淋酱),配清晰步骤字幕,结尾成品 360 度展示与口感描述'
|
||||||
|
];
|
||||||
|
|
||||||
|
function errText(e, fb) { if (!e) return fb; if (typeof e === 'string') return e; return e.message || JSON.stringify(e); }
|
||||||
|
|
||||||
|
function thumbUrl(libraryId, img) {
|
||||||
|
const tp = img.thumbnailPath || '';
|
||||||
|
const fn = tp ? tp.replace(/\\/g, '/').split('/').pop() : '';
|
||||||
|
if (fn) return `/api/image/thumbnail/${libraryId}/${encodeURIComponent(fn)}${img.modifiedAt ? `?v=${img.modifiedAt}` : ''}`;
|
||||||
|
return `/api/image/original/${libraryId}/${String(img.path || '').split('/').map(encodeURIComponent).join('/')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AIVideoStudioModal({ libraryId, onClose, onDone }) {
|
||||||
|
const [tab, setTab] = useState('prompt');
|
||||||
|
const [title, setTitle] = useState('');
|
||||||
|
const [content, setContent] = useState('');
|
||||||
|
const [url, setUrl] = useState('');
|
||||||
|
const [extracted, setExtracted] = useState(null);
|
||||||
|
const [extracting, setExtracting] = useState(false);
|
||||||
|
const [file, setFile] = useState(null);
|
||||||
|
const [voice, setVoice] = useState(VOICES[0].key);
|
||||||
|
const [resolution, setResolution] = useState('1920x1080');
|
||||||
|
const [subtitlePos, setSubtitlePos] = useState('bottom-center');
|
||||||
|
const [subtitleColor, setSubtitleColor] = useState('white');
|
||||||
|
const [subtitleSize, setSubtitleSize] = useState(5);
|
||||||
|
// 素材库图片选择(弹窗内直接挑选)
|
||||||
|
const [libImgs, setLibImgs] = useState([]);
|
||||||
|
const [libLoading, setLibLoading] = useState(false);
|
||||||
|
const [keyword, setKeyword] = useState('');
|
||||||
|
const [picked, setPicked] = useState([]);
|
||||||
|
const [taskId, setTaskId] = useState('');
|
||||||
|
const [folders, setFolders] = useState([]);
|
||||||
|
const [saveDir, setSaveDir] = useState('');
|
||||||
|
const [transition, setTransition] = useState('fade');
|
||||||
|
const [duration, setDuration] = useState(0); // 目标时长(秒),0=自动按配音
|
||||||
|
const [task, setTask] = useState(null);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
const [starting, setStarting] = useState(false);
|
||||||
|
const timerRef = { current: null };
|
||||||
|
|
||||||
|
const auth = { Authorization: `Bearer ${getToken()}` };
|
||||||
|
|
||||||
|
const loadImages = async (kw) => {
|
||||||
|
setLibLoading(true);
|
||||||
|
try {
|
||||||
|
const q = new URLSearchParams({ libraryId: String(libraryId), offset: '0', limit: '120' });
|
||||||
|
if (kw && kw.trim()) q.set('keywords', kw.trim());
|
||||||
|
const r = await fetch(`/api/image?${q}`, { headers: auth });
|
||||||
|
const d = await r.json();
|
||||||
|
// 只允许图片做视频画面:视频文件当图传给 ffmpeg 会直接报 Option loop not found
|
||||||
|
const VIDEO_EXT = ['mp4', 'mov', 'mkv', 'webm', 'avi', 'm4v', 'flv', 'wmv', 'ts'];
|
||||||
|
setLibImgs(((d && d.data && d.data.images) || []).filter((i) => {
|
||||||
|
if (!i || !i.path) return false;
|
||||||
|
const t = String(i.fileType || i.type || '').toLowerCase();
|
||||||
|
if (t === 'video') return false;
|
||||||
|
const ext = String(i.filename || i.path).split('.').pop().toLowerCase();
|
||||||
|
return !VIDEO_EXT.includes(ext);
|
||||||
|
}));
|
||||||
|
} catch (_) {
|
||||||
|
setLibImgs([]);
|
||||||
|
} finally {
|
||||||
|
setLibLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => { if (libraryId) loadImages(''); }, [libraryId]);
|
||||||
|
|
||||||
|
const flattenFolders = (nodes, acc = []) => {
|
||||||
|
for (const n of (nodes || [])) {
|
||||||
|
if (n && n.path) acc.push(n.path);
|
||||||
|
if (n && n.children) flattenFolders(n.children, acc);
|
||||||
|
}
|
||||||
|
return acc;
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!libraryId) return;
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const r = await fetch(`/api/image/folders?libraryId=${libraryId}`, { headers: auth });
|
||||||
|
const d = await r.json();
|
||||||
|
const tree = (d && d.data && d.data.folders) || [];
|
||||||
|
setFolders(flattenFolders(tree));
|
||||||
|
} catch (_) { setFolders([]); }
|
||||||
|
})();
|
||||||
|
}, [libraryId]);
|
||||||
|
|
||||||
|
const togglePick = (img) => {
|
||||||
|
setPicked((list) => {
|
||||||
|
const i = list.findIndex((x) => x.path === img.path);
|
||||||
|
if (i >= 0) return list.filter((x) => x.path !== img.path);
|
||||||
|
return [...list, img];
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const poll = (id) => {
|
||||||
|
const iv = setInterval(async () => {
|
||||||
|
try {
|
||||||
|
const r = await fetch(`/api/video/task/${id}`, { headers: { Authorization: `Bearer ${getToken()}` } });
|
||||||
|
if (!r.ok) return;
|
||||||
|
const d = await r.json();
|
||||||
|
setTask(d);
|
||||||
|
if (d.status === 'done' || d.status === 'error') {
|
||||||
|
clearInterval(iv);
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
}, 1500);
|
||||||
|
timerRef.current = iv;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleExtractUrl = async () => {
|
||||||
|
setExtracting(true); setError('');
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/video/extract-url', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }, body: JSON.stringify({ url }) });
|
||||||
|
const d = await r.json();
|
||||||
|
if (!r.ok || d.error) throw new Error(errText(d.error, `失败 (${r.status})`));
|
||||||
|
setExtracted(d);
|
||||||
|
if (!title) setTitle(d.title || '');
|
||||||
|
setContent(d.text || '');
|
||||||
|
} catch (e) { setError(e.message); }
|
||||||
|
finally { setExtracting(false); }
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleExtractDoc = async () => {
|
||||||
|
if (!file) return;
|
||||||
|
setExtracting(true); setError('');
|
||||||
|
try {
|
||||||
|
const fd = new FormData(); fd.append('file', file);
|
||||||
|
const r = await fetch('/api/video/extract-doc', { method: 'POST', headers: { Authorization: `Bearer ${getToken()}` }, body: fd });
|
||||||
|
const d = await r.json();
|
||||||
|
if (!r.ok || d.error) throw new Error(errText(d.error, `失败 (${r.status})`));
|
||||||
|
setExtracted(d);
|
||||||
|
if (!title) setTitle(d.title || '');
|
||||||
|
setContent(d.text || '');
|
||||||
|
} catch (e) { setError(e.message); }
|
||||||
|
finally { setExtracting(false); }
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleStart = async () => {
|
||||||
|
setError('');
|
||||||
|
if (!title.trim()) { setError('请填写视频标题'); return; }
|
||||||
|
if (tab === 'images' && picked.length === 0) { setError('请先在「素材库图片」里选择至少 1 张'); return; }
|
||||||
|
setStarting(true);
|
||||||
|
try {
|
||||||
|
const imgs = picked.length
|
||||||
|
? picked.map((i) => ({ path: i.path, filename: i.filename, width: i.width, height: i.height }))
|
||||||
|
: ((extracted && extracted.images) || []);
|
||||||
|
const body = {
|
||||||
|
libraryId, title: title.trim(),
|
||||||
|
content: content.trim(),
|
||||||
|
images: imgs,
|
||||||
|
voice, resolution, extraPrompt: '', saveDir, transition, duration: Number(duration) || 0,
|
||||||
|
subtitleStyle: { position: subtitlePos, color: subtitleColor, fontSizePct: subtitleSize }
|
||||||
|
};
|
||||||
|
const r = await fetch('/api/video/aigenerate-text', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }, body: JSON.stringify(body) });
|
||||||
|
const d = await r.json().catch(() => ({}));
|
||||||
|
if (!r.ok || d.error) throw new Error(errText(d.error, `启动失败 (${r.status})`));
|
||||||
|
setTaskId(d.taskId); poll(d.taskId);
|
||||||
|
} catch (e) { setError(e.message || '启动失败'); }
|
||||||
|
finally { setStarting(false); }
|
||||||
|
};
|
||||||
|
|
||||||
|
const running = !!taskId && task && task.status === 'running';
|
||||||
|
const failed = task && task.status === 'error';
|
||||||
|
const done = task && task.status === 'done';
|
||||||
|
|
||||||
|
const input = 'w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-50 bg-black bg-opacity-60 flex items-center justify-center p-4">
|
||||||
|
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-[98vw] h-[98vh] max-w-none max-h-none overflow-y-auto" onClick={(e)=>e.stopPropagation()}>
|
||||||
|
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 dark:border-gray-700">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Film className="w-5 h-5 text-purple-500" />
|
||||||
|
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">AI 一键生成视频</h2>
|
||||||
|
</div>
|
||||||
|
<button onClick={onClose} disabled={running||starting} className="p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded"><X className="w-5 h-5 text-gray-500" /></button>
|
||||||
|
</div>
|
||||||
|
<div className="p-5 space-y-4">
|
||||||
|
{/* tabs */}
|
||||||
|
<div className="flex gap-2 border-b border-gray-200 dark:border-gray-700 pb-2">
|
||||||
|
{[
|
||||||
|
{ k: 'prompt', l: '提示词', icon: Sparkles },
|
||||||
|
{ k: 'url', l: '链接抓取', icon: LinkIcon },
|
||||||
|
{ k: 'doc', l: '文档/PDF', icon: FileText },
|
||||||
|
{ k: 'images', l: '素材库图片', icon: ImageIcon },
|
||||||
|
].map(({ k, l, icon: Icon }) => (
|
||||||
|
<button key={k} onClick={() => setTab(k)} className={`flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm ${tab===k ? 'bg-purple-600 text-white' : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'}`}>
|
||||||
|
<Icon className="w-4 h-4" /> {l}
|
||||||
|
{k === 'images' && picked.length > 0 && <span className="ml-0.5 text-[10px] px-1 rounded bg-white/25">{picked.length}</span>}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{tab === 'prompt' && (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">常用热门提示词</label>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{POPULAR_PROMPTS.map((p) => (
|
||||||
|
<button key={p} onClick={() => { setContent(p); if (!title) setTitle(p.slice(0, 20)); }} className="px-3 py-1 text-xs rounded-full bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-purple-100 dark:hover:bg-purple-900/40">
|
||||||
|
{p}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">提示词 / 内容</label>
|
||||||
|
<textarea className={input} rows={4} value={content} onChange={(e) => setContent(e.target.value)} placeholder="描述你想要的视频内容…" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{tab === 'url' && (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">网页链接</label>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<input className={input} value={url} onChange={(e) => setUrl(e.target.value)} placeholder="https://..." />
|
||||||
|
<button onClick={handleExtractUrl} disabled={extracting || !url} className="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm disabled:opacity-50">
|
||||||
|
{extracting ? '抓取中…' : '抓取'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{extracted && <p className="text-xs text-green-600">已抓取:{extracted.title}({extracted.images?.length || 0} 张图)</p>}
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">内容预览</label>
|
||||||
|
<textarea className={input} rows={4} value={content} onChange={(e) => setContent(e.target.value)} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{tab === 'doc' && (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">上传 PDF / 文档</label>
|
||||||
|
<input type="file" accept=".pdf,.txt,.md,.doc,.docx" onChange={(e) => setFile(e.target.files?.[0] || null)} />
|
||||||
|
<button onClick={handleExtractDoc} disabled={extracting || !file} className="mt-2 px-4 py-2 bg-blue-600 text-white rounded-lg text-sm disabled:opacity-50">
|
||||||
|
{extracting ? '识别中…' : 'AI 识别'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{extracted && <p className="text-xs text-green-600">已识别:{extracted.title}</p>}
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">内容预览</label>
|
||||||
|
<textarea className={input} rows={4} value={content} onChange={(e) => setContent(e.target.value)} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{tab === 'images' && (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<div className="relative flex-1">
|
||||||
|
<Search className="w-4 h-4 text-gray-400 absolute left-2.5 top-1/2 -translate-y-1/2" />
|
||||||
|
<input
|
||||||
|
className={`${input} pl-8`}
|
||||||
|
value={keyword}
|
||||||
|
onChange={(e) => setKeyword(e.target.value)}
|
||||||
|
onKeyDown={(e) => { if (e.key === 'Enter') loadImages(keyword); }}
|
||||||
|
placeholder="搜索素材库图片(回车)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<button onClick={() => loadImages(keyword)} className="px-3 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">搜索</button>
|
||||||
|
{picked.length > 0 && (
|
||||||
|
<button onClick={() => setPicked([])} className="px-3 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-600 text-gray-500 hover:bg-gray-50 dark:hover:bg-gray-700">清空</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="max-h-64 overflow-y-auto rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/40 p-2">
|
||||||
|
{libLoading && <div className="py-8 text-center text-sm text-gray-500"><Loader2 className="w-4 h-4 animate-spin inline mr-1" />加载图片…</div>}
|
||||||
|
{!libLoading && libImgs.length === 0 && <div className="py-8 text-center text-sm text-gray-500">这个素材库还没有图片</div>}
|
||||||
|
{!libLoading && libImgs.length > 0 && (
|
||||||
|
<div className="grid grid-cols-4 sm:grid-cols-5 gap-2">
|
||||||
|
{libImgs.map((img) => {
|
||||||
|
const on = picked.some((x) => x.path === img.path);
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={img.path}
|
||||||
|
onClick={() => togglePick(img)}
|
||||||
|
title={img.filename || img.path}
|
||||||
|
className={`relative aspect-square rounded-lg overflow-hidden border-2 ${on ? 'border-purple-500 ring-2 ring-purple-300' : 'border-transparent hover:border-gray-300'}`}
|
||||||
|
>
|
||||||
|
<img src={thumbUrl(libraryId, img)} alt={img.filename || ''} className="w-full h-full object-cover" />
|
||||||
|
{on && (
|
||||||
|
<span className="absolute top-1 right-1 w-5 h-5 rounded-full bg-purple-600 text-white flex items-center justify-center">
|
||||||
|
<Check className="w-3.5 h-3.5" />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{on && (
|
||||||
|
<span className="absolute bottom-0 left-0 right-0 bg-purple-600/85 text-white text-[10px] py-0.5 truncate px-1">
|
||||||
|
#{picked.findIndex((x) => x.path === img.path) + 1}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-gray-500 dark:text-gray-400">
|
||||||
|
已选 {picked.length} 张(按点击顺序作为画面顺序);不选则按内容自动配图。
|
||||||
|
</p>
|
||||||
|
<textarea className={input} rows={2} value={content} onChange={(e) => setContent(e.target.value)} placeholder="补充说明(可选):想表达的主题、语气…" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">视频标题</label>
|
||||||
|
<input className={input} value={title} onChange={(e) => setTitle(e.target.value)} placeholder="例如:产品速览 / 探店 vlog" maxLength={60} disabled={running||done} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">朗读音色</label>
|
||||||
|
<select className={input} value={voice} onChange={(e) => setVoice(e.target.value)} disabled={running||done}>
|
||||||
|
{VOICES.map((v) => <option key={v.key} value={v.key}>{v.label}</option>)}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">画幅</label>
|
||||||
|
<select className={input} value={resolution} onChange={(e) => setResolution(e.target.value)} disabled={running||done}>
|
||||||
|
{RESOLUTIONS.map((r) => <option key={r.key} value={r.key}>{r.label}</option>)}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-3 gap-3">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">字幕位置</label>
|
||||||
|
<select className={input} value={subtitlePos} onChange={(e) => setSubtitlePos(e.target.value)} disabled={running||done}>
|
||||||
|
{SUBTITLE_STYLES.map((s) => <option key={s.key} value={s.key}>{s.label}</option>)}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">字幕颜色</label>
|
||||||
|
<select className={input} value={subtitleColor} onChange={(e) => setSubtitleColor(e.target.value)} disabled={running||done}>
|
||||||
|
{SUBTITLE_COLORS.map((c) => <option key={c.key} value={c.key}>{c.label}</option>)}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">字幕字号</label>
|
||||||
|
<input type="range" min={3} max={8} value={subtitleSize} onChange={(e) => setSubtitleSize(parseInt(e.target.value))} disabled={running||done} className="w-full" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">保存到目录</label>
|
||||||
|
<select className={input} value={saveDir} onChange={(e) => setSaveDir(e.target.value)} disabled={running||done}>
|
||||||
|
<option value="">素材库根目录</option>
|
||||||
|
{folders.map((p) => <option key={p} value={p}>{p}</option>)}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">视频时长</label>
|
||||||
|
<div className="flex flex-wrap gap-1.5 mb-1.5">
|
||||||
|
{[0, 15, 30, 45, 60, 90, 120, 180, 300].map((s) => (
|
||||||
|
<button key={s} type="button" disabled={running||done}
|
||||||
|
onClick={() => setDuration(s)}
|
||||||
|
className={`px-2 py-1 rounded text-xs border transition ${Number(duration)===s ? 'bg-blue-500 border-blue-500 text-white' : 'bg-white dark:bg-gray-700 border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:border-blue-400'}`}>
|
||||||
|
{s === 0 ? '自动' : s < 60 ? `${s}秒` : `${s/60}分钟`}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<input type="number" min="0" max="600" step="5" disabled={running||done}
|
||||||
|
className={input} value={duration || ''} placeholder="自动(按配音)"
|
||||||
|
onChange={(e) => setDuration(Math.min(600, Math.max(0, Number(e.target.value) || 0)))} />
|
||||||
|
<span className="text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap">秒 · 0=自动</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">转场效果</label>
|
||||||
|
<select className={input} value={transition} onChange={(e) => setTransition(e.target.value)} disabled={running||done}>
|
||||||
|
<option value="cut">无转场(直接切换)</option>
|
||||||
|
<option value="fade">淡入淡出</option>
|
||||||
|
<option value="fadeblack">黑场淡入</option>
|
||||||
|
<option value="fadewhite">白场淡入</option>
|
||||||
|
<option value="slideleft">左滑</option>
|
||||||
|
<option value="slideright">右滑</option>
|
||||||
|
<option value="slideup">上滑</option>
|
||||||
|
<option value="slidedown">下滑</option>
|
||||||
|
<option value="dissolve">溶解</option>
|
||||||
|
<option value="wipeleft">左擦除</option>
|
||||||
|
<option value="wiperight">右擦除</option>
|
||||||
|
<option value="pixelize">像素化</option>
|
||||||
|
<option value="circleopen">圆圈打开</option>
|
||||||
|
<option value="hblur">模糊过渡</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-start gap-2 rounded-lg bg-gray-50 dark:bg-gray-900/50 border border-gray-200 dark:border-gray-700 px-3 py-2 text-xs text-gray-600 dark:text-gray-400">
|
||||||
|
<Settings className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />
|
||||||
|
<span>提供商 / 模型 / KEY 在右上角「设置 → AI 视频」里配置,普通文本模型即可;配音与字幕由本地合成。</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{(running || done || failed) && (
|
||||||
|
<div className={`rounded-lg border px-4 py-3 ${failed ? 'border-red-200 bg-red-50 dark:bg-red-900/20' : done ? 'border-green-200 bg-green-50 dark:bg-green-900/20' : 'border-blue-200 bg-blue-50 dark:bg-blue-900/20'}`}>
|
||||||
|
<div className="flex items-center gap-2 text-sm">
|
||||||
|
{failed ? <AlertCircle className="w-4 h-4 text-red-500" /> : done ? <CheckCircle2 className="w-4 h-4 text-green-500" /> : <Loader2 className="w-4 h-4 animate-spin text-blue-500" />}
|
||||||
|
<span className={`font-medium ${failed ? 'text-red-700 dark:text-red-300' : done ? 'text-green-700 dark:text-green-300' : 'text-blue-700 dark:text-blue-300'}`}>
|
||||||
|
{failed ? '生成失败' : done ? '生成完成' : (task?.stepLabel || '处理中')}
|
||||||
|
</span>
|
||||||
|
{running && <span className="ml-auto text-xs text-blue-600 dark:text-blue-300">{task?.progress || 0}%</span>}
|
||||||
|
</div>
|
||||||
|
{running && <div className="mt-2 h-1.5 bg-blue-100 dark:bg-blue-900/50 rounded-full overflow-hidden"><div className="h-full bg-blue-500 rounded-full transition-all" style={{ width: `${task?.progress || 0}%` }} /></div>}
|
||||||
|
{failed && <p className="mt-1 text-xs text-red-600 dark:text-red-400">{task?.error}</p>}
|
||||||
|
{done && task?.resultPath && <p className="mt-1 text-xs text-green-600 dark:text-green-400">已保存:{task.resultPath}</p>}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && <div className="text-sm text-red-600 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-lg px-3 py-2">{error}</div>}
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-3 pt-1">
|
||||||
|
<button onClick={() => (done ? (onDone && onDone(task?.resultPath)) : onClose())} disabled={running||starting} className="px-4 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50">
|
||||||
|
{done ? '关闭并刷新' : '取消'}
|
||||||
|
</button>
|
||||||
|
{!running && !done && (
|
||||||
|
<button onClick={handleStart} disabled={starting} className="px-5 py-2 text-sm rounded-lg bg-purple-600 hover:bg-purple-700 text-white font-medium disabled:opacity-50 flex items-center gap-2">
|
||||||
|
{starting && <Loader2 className="w-4 h-4 animate-spin" />}
|
||||||
|
{starting ? '启动中…' : '一键生成'}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,430 @@
|
|||||||
|
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||||
|
import { Replace, Loader2, X, Play, Square, CheckCircle2, AlertTriangle, ArrowRight } from 'lucide-react';
|
||||||
|
import { batchAPI } from '../api';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量重命名弹窗(文件夹级)
|
||||||
|
* 模式:
|
||||||
|
* prefix 前缀添加 —— 在原文件名前加文本
|
||||||
|
* suffix 后缀添加 —— 在原文件名后加文本
|
||||||
|
* replace 全部改名 —— 原文件名整体替换为文本(同目录多个文件自动加序号 -001)
|
||||||
|
*
|
||||||
|
* 流程:配置(实时预览)→ 启动任务(立即返回 taskId)→ 1s 轮询进度 → 完成/取消
|
||||||
|
*/
|
||||||
|
|
||||||
|
const MODES = [
|
||||||
|
{ key: 'prefix', label: '前面加', desc: '在原文件名前加文本', hint: '文本 + 原文件名 + 扩展名' },
|
||||||
|
{ key: 'suffix', label: '后面加', desc: '在原文件名后加文本', hint: '原文件名 + 文本 + 扩展名' },
|
||||||
|
{ key: 'replace', label: '全部改名', desc: '原文件名替换为文本', hint: '同目录多个文件自动编号:文本-001、文本-002…' },
|
||||||
|
{ key: 'keyword', label: '关键词替换', desc: '替换文件名中的关键词', hint: '把文件名中的「找什么」全部换成「替换成」,替换成留空 = 删除该关键词' }
|
||||||
|
];
|
||||||
|
|
||||||
|
const ILLEGAL_RE = /[\\/:*?"<>|]/;
|
||||||
|
|
||||||
|
function BatchRenameModal({ isOpen, folder, libraryId, scope, keywords, onClose, onFinished }) {
|
||||||
|
const [phase, setPhase] = useState('config'); // config | running | done
|
||||||
|
const [mode, setMode] = useState('prefix');
|
||||||
|
const [text, setText] = useState('');
|
||||||
|
const [find, setFind] = useState('');
|
||||||
|
const [includeSubdirs, setIncludeSubdirs] = useState(true);
|
||||||
|
const [preview, setPreview] = useState(null); // { count, total, samples, skipped }
|
||||||
|
const [previewErr, setPreviewErr] = useState('');
|
||||||
|
const [starting, setStarting] = useState(false);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
|
||||||
|
const [taskId, setTaskId] = useState(null);
|
||||||
|
const [progress, setProgress] = useState(null);
|
||||||
|
const pollRef = useRef(null);
|
||||||
|
const previewTimerRef = useRef(null);
|
||||||
|
|
||||||
|
const stopPolling = useCallback(() => {
|
||||||
|
if (pollRef.current) {
|
||||||
|
clearInterval(pollRef.current);
|
||||||
|
pollRef.current = null;
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// 打开时重置
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isOpen) return;
|
||||||
|
setPhase('config');
|
||||||
|
setMode('prefix');
|
||||||
|
setText('');
|
||||||
|
setFind('');
|
||||||
|
setIncludeSubdirs(true);
|
||||||
|
setPreview(null);
|
||||||
|
setPreviewErr('');
|
||||||
|
setError('');
|
||||||
|
setTaskId(null);
|
||||||
|
setProgress(null);
|
||||||
|
setStarting(false);
|
||||||
|
return () => stopPolling();
|
||||||
|
}, [isOpen, stopPolling]);
|
||||||
|
|
||||||
|
// 实时预览(防抖 300ms)
|
||||||
|
const needInput = mode === 'keyword' ? find.trim() : text.trim();
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isOpen || phase !== 'config') return;
|
||||||
|
if (previewTimerRef.current) clearTimeout(previewTimerRef.current);
|
||||||
|
if (!needInput) {
|
||||||
|
setPreview(null);
|
||||||
|
setPreviewErr('');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
previewTimerRef.current = setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
const resp = await batchAPI.renamePreview({
|
||||||
|
libraryId, folder, scope, keywords,
|
||||||
|
options: { mode, text: text.trim(), find: find.trim(), keywords: keywords || undefined, includeSubdirs }
|
||||||
|
});
|
||||||
|
setPreview(resp);
|
||||||
|
setPreviewErr('');
|
||||||
|
} catch (err) {
|
||||||
|
setPreview(null);
|
||||||
|
setPreviewErr(err?.message || '预览失败');
|
||||||
|
}
|
||||||
|
}, 300);
|
||||||
|
return () => { if (previewTimerRef.current) clearTimeout(previewTimerRef.current); };
|
||||||
|
}, [isOpen, phase, mode, text, find, includeSubdirs, libraryId, folder, scope, keywords, needInput]);
|
||||||
|
|
||||||
|
const startPolling = useCallback((id) => {
|
||||||
|
stopPolling();
|
||||||
|
pollRef.current = setInterval(async () => {
|
||||||
|
try {
|
||||||
|
const s = await batchAPI.status(id);
|
||||||
|
setProgress(s);
|
||||||
|
if (s.status !== 'running') {
|
||||||
|
stopPolling();
|
||||||
|
setPhase('done');
|
||||||
|
onFinished?.(s);
|
||||||
|
}
|
||||||
|
} catch (_) { /* 网络抖动,继续轮询 */ }
|
||||||
|
}, 1000);
|
||||||
|
}, [stopPolling, onFinished]);
|
||||||
|
|
||||||
|
const handleStart = async () => {
|
||||||
|
setError('');
|
||||||
|
const t = text.trim();
|
||||||
|
const f = find.trim();
|
||||||
|
if (mode === 'keyword') {
|
||||||
|
if (!f) {
|
||||||
|
setError('请填写要查找的关键词');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (ILLEGAL_RE.test(f)) {
|
||||||
|
setError('关键词包含文件名非法字符 \\ / : * ? " < > |');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (ILLEGAL_RE.test(t)) {
|
||||||
|
setError('替换文本包含文件名非法字符 \\ / : * ? " < > |');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (!t) {
|
||||||
|
setError('请输入重命名文本');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (ILLEGAL_RE.test(t)) {
|
||||||
|
setError('文本包含文件名非法字符 \\ / : * ? " < > |');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setStarting(true);
|
||||||
|
try {
|
||||||
|
const resp = await batchAPI.start({
|
||||||
|
libraryId, folder, scope, keywords, type: 'rename',
|
||||||
|
options: { mode, text: t, find: f, keywords: keywords || undefined, includeSubdirs }
|
||||||
|
});
|
||||||
|
setTaskId(resp.taskId);
|
||||||
|
setPhase('running');
|
||||||
|
setProgress({
|
||||||
|
status: 'running', total: resp.total, done: 0, failed: 0,
|
||||||
|
skipped: 0, current: '', errors: []
|
||||||
|
});
|
||||||
|
startPolling(resp.taskId);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err?.message || '启动失败');
|
||||||
|
} finally {
|
||||||
|
setStarting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCancel = async () => {
|
||||||
|
if (!taskId) return;
|
||||||
|
try { await batchAPI.cancel(taskId); } catch (_) { /* 已结束 */ }
|
||||||
|
stopPolling();
|
||||||
|
setPhase('done');
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleClose = () => {
|
||||||
|
stopPolling();
|
||||||
|
onClose();
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!isOpen) return null;
|
||||||
|
|
||||||
|
const pct = progress && progress.total > 0
|
||||||
|
? Math.round(((progress.done + progress.failed + progress.skipped) / progress.total) * 100)
|
||||||
|
: 0;
|
||||||
|
const modeInfo = MODES.find((m) => m.key === mode);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
|
||||||
|
<div
|
||||||
|
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-xl max-h-[90vh] overflow-hidden flex flex-col"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
{/* 头部 */}
|
||||||
|
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 dark:border-gray-700">
|
||||||
|
<div className="flex items-center gap-2.5">
|
||||||
|
<Replace className="w-5 h-5 text-violet-500" />
|
||||||
|
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">批量重命名文件</h2>
|
||||||
|
<span className="text-xs px-2 py-0.5 rounded-full bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 truncate max-w-[240px]">
|
||||||
|
{scope === 'search' ? `搜索:${keywords}` : folder}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<button onClick={handleClose} className="p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-700">
|
||||||
|
<X className="w-5 h-5 text-gray-500" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 内容 */}
|
||||||
|
<div className="flex-1 overflow-y-auto p-5">
|
||||||
|
{phase === 'config' && (
|
||||||
|
<>
|
||||||
|
{/* 重命名模式 */}
|
||||||
|
<div className="mb-4">
|
||||||
|
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">重命名方式</div>
|
||||||
|
<div className="grid grid-cols-2 gap-2">
|
||||||
|
{MODES.map((m) => (
|
||||||
|
<button
|
||||||
|
key={m.key}
|
||||||
|
onClick={() => setMode(m.key)}
|
||||||
|
className={`px-3 py-2.5 rounded-lg text-sm border transition-colors ${mode === m.key
|
||||||
|
? 'border-violet-500 bg-violet-50 dark:bg-violet-900/40 text-violet-600 dark:text-violet-300 font-medium'
|
||||||
|
: 'border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:border-gray-400'}`}
|
||||||
|
>
|
||||||
|
<div>{m.label}</div>
|
||||||
|
<div className="text-[10px] font-normal opacity-70 mt-0.5">{m.desc}</div>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="text-[11px] text-gray-400 dark:text-gray-500 mt-1.5">
|
||||||
|
规则:{modeInfo.hint}(扩展名始终保留)
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 文本输入 */}
|
||||||
|
{mode === 'keyword' ? (
|
||||||
|
<div className="mb-4">
|
||||||
|
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">关键词</div>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={find}
|
||||||
|
onChange={(e) => setFind(e.target.value)}
|
||||||
|
placeholder="找什么:要被替换的文件名关键词,例如:素材"
|
||||||
|
maxLength={100}
|
||||||
|
autoFocus
|
||||||
|
className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm focus:outline-none focus:ring-2 focus:ring-violet-500"
|
||||||
|
/>
|
||||||
|
{ILLEGAL_RE.test(find) && (
|
||||||
|
<div className="text-[11px] text-red-500 mt-1">关键词包含文件名非法字符 \ / : * ? " < > |</div>
|
||||||
|
)}
|
||||||
|
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5 mt-3">替换成</div>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={text}
|
||||||
|
onChange={(e) => setText(e.target.value)}
|
||||||
|
placeholder="替换成:留空 = 直接删除该关键词,例如:视频"
|
||||||
|
maxLength={100}
|
||||||
|
className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm focus:outline-none focus:ring-2 focus:ring-violet-500"
|
||||||
|
/>
|
||||||
|
{ILLEGAL_RE.test(text) && (
|
||||||
|
<div className="text-[11px] text-red-500 mt-1">替换文本包含文件名非法字符 \ / : * ? " < > |</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="mb-4">
|
||||||
|
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">文本内容</div>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={text}
|
||||||
|
onChange={(e) => setText(e.target.value)}
|
||||||
|
placeholder={mode === 'replace' ? '例如:风景素材(全部文件改为 风景素材-001.jpg …)' : '例如:2026_'}
|
||||||
|
maxLength={100}
|
||||||
|
autoFocus
|
||||||
|
className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm focus:outline-none focus:ring-2 focus:ring-violet-500"
|
||||||
|
/>
|
||||||
|
{ILLEGAL_RE.test(text) && (
|
||||||
|
<div className="text-[11px] text-red-500 mt-1">包含文件名非法字符 \ / : * ? " < > |</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 包含子目录(搜索范围时全库命中,无需此开关) */}
|
||||||
|
{scope !== 'search' && (
|
||||||
|
<label className="flex items-center gap-2 mb-4 cursor-pointer select-none">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={includeSubdirs}
|
||||||
|
onChange={(e) => setIncludeSubdirs(e.target.checked)}
|
||||||
|
className="w-4 h-4 rounded accent-violet-500"
|
||||||
|
/>
|
||||||
|
<span className="text-sm text-gray-700 dark:text-gray-300">包含子目录(递归处理所有层级文件)</span>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* 实时预览 */}
|
||||||
|
<div className="rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50 p-3">
|
||||||
|
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-2">预览</div>
|
||||||
|
{!needInput && (
|
||||||
|
<div className="text-[11px] text-gray-400">{mode === 'keyword' ? '输入关键词后显示改名效果' : '输入文本后显示改名效果'}</div>
|
||||||
|
)}
|
||||||
|
{needInput && previewErr && (
|
||||||
|
<div className="text-[11px] text-red-500">{previewErr}</div>
|
||||||
|
)}
|
||||||
|
{needInput && !previewErr && !preview && (
|
||||||
|
<div className="text-[11px] text-gray-400 flex items-center gap-1.5">
|
||||||
|
<Loader2 className="w-3 h-3 animate-spin" /> 计算中…
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{preview && (
|
||||||
|
<>
|
||||||
|
<div className="text-[11px] text-gray-600 dark:text-gray-300 mb-2">
|
||||||
|
将重命名 <b className="text-violet-500">{preview.count}</b> 个文件
|
||||||
|
{preview.skipped > 0 && <span className="text-gray-400">({preview.skipped} 个跳过)</span>}
|
||||||
|
{!includeSubdirs && <span className="text-gray-400">,仅当前文件夹</span>}
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1">
|
||||||
|
{preview.samples.map((s, i) => (
|
||||||
|
<div key={i} className="flex items-center gap-2 text-[11px] font-mono">
|
||||||
|
<span className="text-gray-500 dark:text-gray-400 truncate max-w-[45%]">{s.from}</span>
|
||||||
|
<ArrowRight className="w-3 h-3 text-violet-400 flex-shrink-0" />
|
||||||
|
<span className="text-violet-500 truncate">{s.to}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{preview.total > preview.samples.length && (
|
||||||
|
<div className="text-[10px] text-gray-400 pt-0.5">
|
||||||
|
…共 {preview.total} 条
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="mt-3 flex items-center gap-2 text-sm text-red-500">
|
||||||
|
<AlertTriangle className="w-4 h-4" /> {error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{phase === 'running' && (
|
||||||
|
<div className="py-4">
|
||||||
|
<div className="flex items-center justify-between text-sm text-gray-600 dark:text-gray-300 mb-2">
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<Loader2 className="w-4 h-4 animate-spin text-violet-500" />
|
||||||
|
重命名中 {progress ? `${progress.done + progress.failed + progress.skipped}/${progress.total}` : ''}
|
||||||
|
</span>
|
||||||
|
<span className="tabular-nums">{pct}%</span>
|
||||||
|
</div>
|
||||||
|
<div className="h-2 rounded-full bg-gray-200 dark:bg-gray-700 overflow-hidden">
|
||||||
|
<div className="h-full bg-violet-500 transition-all" style={{ width: `${pct}%` }} />
|
||||||
|
</div>
|
||||||
|
{progress?.current && (
|
||||||
|
<div className="mt-2 text-[11px] text-gray-400 truncate">{progress.current}</div>
|
||||||
|
)}
|
||||||
|
<div className="flex justify-center mt-5">
|
||||||
|
<button
|
||||||
|
onClick={handleCancel}
|
||||||
|
className="px-4 py-2 rounded-lg text-sm border border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-2"
|
||||||
|
>
|
||||||
|
<Square className="w-3.5 h-3.5" /> 停止(已完成的保留)
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{phase === 'done' && (
|
||||||
|
<div className="py-4">
|
||||||
|
<div className="flex items-center gap-2 mb-4">
|
||||||
|
<CheckCircle2 className="w-5 h-5 text-emerald-500" />
|
||||||
|
<span className="text-sm font-medium text-gray-900 dark:text-white">
|
||||||
|
{progress?.status === 'cancelled' ? '已停止' : '重命名完成'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-3 gap-3 text-center">
|
||||||
|
<div className="rounded-lg bg-emerald-50 dark:bg-emerald-900/30 p-3">
|
||||||
|
<div className="text-xl font-semibold text-emerald-600 dark:text-emerald-300 tabular-nums">{progress?.done ?? 0}</div>
|
||||||
|
<div className="text-[11px] text-gray-500 dark:text-gray-400">已重命名</div>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-lg bg-gray-100 dark:bg-gray-700/60 p-3">
|
||||||
|
<div className="text-xl font-semibold text-gray-600 dark:text-gray-300 tabular-nums">{progress?.skipped ?? 0}</div>
|
||||||
|
<div className="text-[11px] text-gray-500 dark:text-gray-400">已跳过</div>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-lg bg-red-50 dark:bg-red-900/30 p-3">
|
||||||
|
<div className="text-xl font-semibold text-red-600 dark:text-red-300 tabular-nums">{progress?.failed ?? 0}</div>
|
||||||
|
<div className="text-[11px] text-gray-500 dark:text-gray-400">失败</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{progress?.errors?.length > 0 && (
|
||||||
|
<div className="mt-4 rounded-lg border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/20 p-3">
|
||||||
|
<div className="text-xs font-medium text-red-600 dark:text-red-300 mb-1.5">失败明细</div>
|
||||||
|
<div className="space-y-1">
|
||||||
|
{progress.errors.slice(0, 8).map((e, i) => (
|
||||||
|
<div key={i} className="text-[11px] text-red-500 dark:text-red-400 font-mono truncate">
|
||||||
|
{e.path}: {e.error}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 底部按钮 */}
|
||||||
|
<div className="px-5 py-4 border-t border-gray-200 dark:border-gray-700 flex justify-end gap-2.5">
|
||||||
|
{phase === 'config' && (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
onClick={handleClose}
|
||||||
|
className="px-4 py-2 rounded-lg text-sm border border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
|
||||||
|
>
|
||||||
|
取消
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={handleStart}
|
||||||
|
disabled={starting || !text.trim() || ILLEGAL_RE.test(text)}
|
||||||
|
className="px-4 py-2 rounded-lg text-sm bg-violet-500 hover:bg-violet-600 text-white flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
|
>
|
||||||
|
{starting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Play className="w-4 h-4" />}
|
||||||
|
开始重命名{preview ? `(${preview.count} 个)` : ''}
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{phase === 'running' && (
|
||||||
|
<button
|
||||||
|
onClick={handleCancel}
|
||||||
|
className="px-4 py-2 rounded-lg text-sm border border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
|
||||||
|
>
|
||||||
|
停止
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{phase === 'done' && (
|
||||||
|
<button
|
||||||
|
onClick={handleClose}
|
||||||
|
className="px-4 py-2 rounded-lg text-sm bg-violet-500 hover:bg-violet-600 text-white"
|
||||||
|
>
|
||||||
|
完成
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default BatchRenameModal;
|
||||||
@@ -203,7 +203,7 @@ function BatchWatermarkModal({ isOpen, mode, folder, libraryId, onClose, onFinis
|
|||||||
: 0;
|
: 0;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={handleClose}>
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
|
||||||
<div
|
<div
|
||||||
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col"
|
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col"
|
||||||
onClick={(e) => e.stopPropagation()}
|
onClick={(e) => e.stopPropagation()}
|
||||||
@@ -216,7 +216,7 @@ function BatchWatermarkModal({ isOpen, mode, folder, libraryId, onClose, onFinis
|
|||||||
<span className="text-xs px-2 py-0.5 rounded-full bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 truncate max-w-[240px]">
|
<span className="text-xs px-2 py-0.5 rounded-full bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 truncate max-w-[240px]">
|
||||||
{folder}
|
{folder}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-xs text-gray-400">{imageCount} 张图片</span>
|
<span className="text-xs text-gray-400">{imageCount} 个文件</span>
|
||||||
</div>
|
</div>
|
||||||
<button onClick={handleClose} className="p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-700">
|
<button onClick={handleClose} className="p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-700">
|
||||||
<X className="w-5 h-5 text-gray-500" />
|
<X className="w-5 h-5 text-gray-500" />
|
||||||
@@ -517,7 +517,7 @@ function BatchWatermarkModal({ isOpen, mode, folder, libraryId, onClose, onFinis
|
|||||||
className={`flex items-center gap-2 px-5 py-2.5 rounded-lg text-white text-sm disabled:opacity-50 disabled:cursor-not-allowed transition-colors ${accentBtn}`}
|
className={`flex items-center gap-2 px-5 py-2.5 rounded-lg text-white text-sm disabled:opacity-50 disabled:cursor-not-allowed transition-colors ${accentBtn}`}
|
||||||
>
|
>
|
||||||
{starting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Play className="w-4 h-4" />}
|
{starting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Play className="w-4 h-4" />}
|
||||||
{imageCount === 0 ? '该文件夹没有图片' : `开始处理 ${imageCount} 张`}
|
{imageCount === 0 ? '该文件夹没有可处理的文件' : `开始处理 ${imageCount} 个文件`}
|
||||||
</button>
|
</button>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { useEffect, useRef } from 'react';
|
import { useEffect, useRef } from 'react';
|
||||||
import { Trash2, Edit3, Move, Copy, FolderPlus, Star, Droplets, Eraser, Scissors, Film } from 'lucide-react';
|
import { Trash2, Edit3, Move, Copy, FolderPlus, Star, Droplets, Eraser, Scissors, Film, Replace } from 'lucide-react';
|
||||||
|
|
||||||
function ContextMenu({ isOpen, position, onClose, options }) {
|
function ContextMenu({ isOpen, position, onClose, options }) {
|
||||||
const menuRef = useRef(null);
|
const menuRef = useRef(null);
|
||||||
@@ -173,6 +173,11 @@ export const menuItems = {
|
|||||||
label: '批量加水印…',
|
label: '批量加水印…',
|
||||||
action
|
action
|
||||||
}),
|
}),
|
||||||
|
batchRename: (action) => ({
|
||||||
|
icon: <Replace size={16} />,
|
||||||
|
label: '批量重命名文件…',
|
||||||
|
action
|
||||||
|
}),
|
||||||
batchRemoveWatermark: (action) => ({
|
batchRemoveWatermark: (action) => ({
|
||||||
icon: <Eraser size={16} />,
|
icon: <Eraser size={16} />,
|
||||||
label: '批量去水印…',
|
label: '批量去水印…',
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { useLibraryStore } from '../stores/useLibraryStore';
|
import { useLibraryStore } from '../stores/useLibraryStore';
|
||||||
import { useImageStore } from '../stores/useImageStore';
|
import { useImageStore } from '../stores/useImageStore';
|
||||||
import { Folder, Image as ImageIcon, HardDrive } from 'lucide-react';
|
import { Folder, Image as ImageIcon, HardDrive, File as FileIcon } from 'lucide-react';
|
||||||
|
import { countLabel, typeMeta, typeLabelOf, orderedTypeEntries } from '../utils/fileTypes';
|
||||||
|
|
||||||
function Dashboard() {
|
function Dashboard() {
|
||||||
const { currentLibraryId, getCurrentLibrary } = useLibraryStore();
|
const { currentLibraryId, getCurrentLibrary } = useLibraryStore();
|
||||||
const { totalImageCount, totalSize, folders } = useImageStore();
|
const { totalImageCount, totalSize, folders, typeCounts } = useImageStore();
|
||||||
|
|
||||||
const currentLibrary = getCurrentLibrary();
|
const currentLibrary = getCurrentLibrary();
|
||||||
const folderCount = folders.length;
|
const folderCount = folders.length;
|
||||||
@@ -35,11 +36,22 @@ function Dashboard() {
|
|||||||
<div className="bg-secondary rounded-xl p-6 shadow-sm border">
|
<div className="bg-secondary rounded-xl p-6 shadow-sm border">
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
<div className="p-3 bg-blue-100 rounded-lg text-accent">
|
<div className="p-3 bg-blue-100 rounded-lg text-accent">
|
||||||
<ImageIcon className="w-6 h-6" />
|
{(() => {
|
||||||
|
const types = orderedTypeEntries(typeCounts);
|
||||||
|
const StatIcon = types.length === 1 ? typeMeta(types[0][0]).icon : FileIcon;
|
||||||
|
return <StatIcon className="w-6 h-6" />;
|
||||||
|
})()}
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<div className="text-2xl font-bold text-primary">{totalImageCount.toLocaleString()}</div>
|
<div className="text-2xl font-bold text-primary">{totalImageCount.toLocaleString()}</div>
|
||||||
<div className="text-sm text-tertiary">图片总数</div>
|
<div className="text-sm text-tertiary">{typeLabelOf(typeCounts)}总数</div>
|
||||||
|
{/* 分类型图例:由类型注册表自动渲染,新类型无需改代码 */}
|
||||||
|
<div className="text-xs text-tertiary mt-0.5 flex gap-2 flex-wrap">
|
||||||
|
{orderedTypeEntries(typeCounts)
|
||||||
|
.map(([t, n]) => (
|
||||||
|
<span key={t}>{typeMeta(t).label} {n.toLocaleString()}</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -87,7 +99,7 @@ function Dashboard() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-xs text-tertiary">{folder.imageCount || 0} 张图片</div>
|
<div className="text-xs text-tertiary">{countLabel(folder.imageCount || 0, folder.typeCounts)}</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -100,7 +112,7 @@ function Dashboard() {
|
|||||||
<h3 className="text-lg font-medium text-primary mb-2">暂无文件夹</h3>
|
<h3 className="text-lg font-medium text-primary mb-2">暂无文件夹</h3>
|
||||||
<p className="text-tertiary max-w-sm mx-auto">
|
<p className="text-tertiary max-w-sm mx-auto">
|
||||||
{totalImageCount > 0
|
{totalImageCount > 0
|
||||||
? `此素材库的 ${totalImageCount} 张图片没有子文件夹,已在下方瀑布视图中直接显示。`
|
? `此素材库的 ${countLabel(totalImageCount, typeCounts)} 没有子文件夹,已在下方瀑布视图中直接显示。`
|
||||||
: '您的素材库似乎是空的。请将图片添加到素材库目录中,系统会自动扫描。'}
|
: '您的素材库似乎是空的。请将图片添加到素材库目录中,系统会自动扫描。'}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useState, useEffect, useMemo, useRef } from 'react';
|
import { useState, useEffect, useMemo, useRef } from 'react';
|
||||||
import { Sun, Moon, Search, Filter, Sliders, RefreshCw, ScanLine, Star, Bell, Github, Settings, ExternalLink, Wand2 } from 'lucide-react';
|
import { Sun, Moon, Search, Filter, Sliders, RefreshCw, ScanLine, Star, Bell, Github, Settings, ExternalLink, Wand2, Film } from 'lucide-react';
|
||||||
import { useLibraryStore } from '../stores/useLibraryStore';
|
import { useLibraryStore } from '../stores/useLibraryStore';
|
||||||
import { useImageStore } from '../stores/useImageStore';
|
import { useImageStore } from '../stores/useImageStore';
|
||||||
import { useUIStore } from '../stores/useUIStore';
|
import { useUIStore } from '../stores/useUIStore';
|
||||||
@@ -9,6 +9,7 @@ import { useHub } from '../hooks/useHub';
|
|||||||
import { libraryAPI, scanAPI, watchAPI } from '../api';
|
import { libraryAPI, scanAPI, watchAPI } from '../api';
|
||||||
import SettingsModal from './SettingsModal';
|
import SettingsModal from './SettingsModal';
|
||||||
import AIGenModal from './AIGenModal';
|
import AIGenModal from './AIGenModal';
|
||||||
|
import AIVideoStudioModal from './AIVideoStudioModal';
|
||||||
import { createLogger } from '../utils/logger';
|
import { createLogger } from '../utils/logger';
|
||||||
|
|
||||||
const logger = createLogger('Header');
|
const logger = createLogger('Header');
|
||||||
@@ -33,12 +34,13 @@ function Header() {
|
|||||||
const [showSettings, setShowSettings] = useState(false);
|
const [showSettings, setShowSettings] = useState(false);
|
||||||
const [settingsTab, setSettingsTab] = useState('ocr');
|
const [settingsTab, setSettingsTab] = useState('ocr');
|
||||||
const [showAIGen, setShowAIGen] = useState(false);
|
const [showAIGen, setShowAIGen] = useState(false);
|
||||||
|
const [showAIVideo, setShowAIVideo] = useState(false);
|
||||||
const searchDebounceRef = useRef(null);
|
const searchDebounceRef = useRef(null);
|
||||||
|
|
||||||
// 授权系统 hub:版本 / 公告 / 在线人数
|
// 授权系统 hub:版本 / 公告 / 在线人数
|
||||||
const hub = useHub();
|
const hub = useHub();
|
||||||
const announcements = hub.announcements || [];
|
const announcements = hub.announcements || [];
|
||||||
const appVersion = hub.version ? `v${String(hub.version).replace(/^v/, '')}` : 'v1.4.2';
|
const appVersion = hub.version ? `v${String(hub.version).replace(/^v/, '')}` : 'v1.4.15';
|
||||||
|
|
||||||
// 从全局 store 获取筛选状态
|
// 从全局 store 获取筛选状态
|
||||||
const selectedFormats = filters.formats || [];
|
const selectedFormats = filters.formats || [];
|
||||||
@@ -410,6 +412,14 @@ function Header() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={() => setShowAIVideo(true)}
|
||||||
|
title="AI 生成视频"
|
||||||
|
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
|
||||||
|
>
|
||||||
|
<Film className="w-5 h-5 text-purple-600 dark:text-purple-400" />
|
||||||
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={() => setShowAIGen(true)}
|
onClick={() => setShowAIGen(true)}
|
||||||
title="AI 生图"
|
title="AI 生图"
|
||||||
@@ -432,6 +442,7 @@ function Header() {
|
|||||||
|
|
||||||
<SettingsModal open={showSettings} onClose={() => setShowSettings(false)} versionLabel={appVersion} initialTab={settingsTab} />
|
<SettingsModal open={showSettings} onClose={() => setShowSettings(false)} versionLabel={appVersion} initialTab={settingsTab} />
|
||||||
<AIGenModal open={showAIGen} onClose={() => setShowAIGen(false)} />
|
<AIGenModal open={showAIGen} onClose={() => setShowAIGen(false)} />
|
||||||
|
{showAIVideo && <AIVideoStudioModal libraryId={currentLibraryId} onClose={() => setShowAIVideo(false)} onDone={() => { setShowAIVideo(false); window.location.reload(); }} />}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -494,7 +505,7 @@ function Header() {
|
|||||||
<Search className="absolute left-3 top-2.5 w-5 h-5 text-gray-400" />
|
<Search className="absolute left-3 top-2.5 w-5 h-5 text-gray-400" />
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="搜索图片...(支持 OCR 图内文字)"
|
placeholder="搜索文件...(支持 OCR 图内文字)"
|
||||||
value={searchKeywords}
|
value={searchKeywords}
|
||||||
onChange={(e) => handleSearchChange(e.target.value)}
|
onChange={(e) => handleSearchChange(e.target.value)}
|
||||||
className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm"
|
className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm"
|
||||||
@@ -671,7 +682,7 @@ function Header() {
|
|||||||
<div className="h-14 flex items-center justify-between px-6">
|
<div className="h-14 flex items-center justify-between px-6">
|
||||||
<div className="flex-shrink-0">
|
<div className="flex-shrink-0">
|
||||||
<h1 className="text-xl font-bold text-gray-900 dark:text-white">牛仔库</h1>
|
<h1 className="text-xl font-bold text-gray-900 dark:text-white">牛仔库</h1>
|
||||||
<p className="text-xs text-gray-500 dark:text-gray-400">轻量快速的图片素材库管理</p>
|
<p className="text-xs text-gray-500 dark:text-gray-400">轻量快速的素材库管理</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 搜索栏 */}
|
{/* 搜索栏 */}
|
||||||
@@ -680,7 +691,7 @@ function Header() {
|
|||||||
<Search className="absolute left-3 top-2.5 w-5 h-5 text-gray-400" />
|
<Search className="absolute left-3 top-2.5 w-5 h-5 text-gray-400" />
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="搜索图片...(支持 OCR 图内文字,多个关键词用空格分隔)"
|
placeholder="搜索文件...(支持 OCR 图内文字,多个关键词用空格分隔)"
|
||||||
value={localSearchValue}
|
value={localSearchValue}
|
||||||
onChange={(e) => handleSearchChange(e.target.value)}
|
onChange={(e) => handleSearchChange(e.target.value)}
|
||||||
className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ const ImageCell = ({
|
|||||||
height: `${image.calculatedHeight}px`
|
height: `${image.calculatedHeight}px`
|
||||||
}}
|
}}
|
||||||
onClick={(e) => onImageClick(image, e, flatIndex)}
|
onClick={(e) => onImageClick(image, e, flatIndex)}
|
||||||
onDoubleClick={() => onImageDoubleClick(image, flatIndex)}
|
onDoubleClick={(e) => { e.preventDefault(); onImageDoubleClick(image, flatIndex); }}
|
||||||
onContextMenu={(e) => onContextMenu(e, image)}
|
onContextMenu={(e) => onContextMenu(e, image)}
|
||||||
draggable={true}
|
draggable={true}
|
||||||
onDragStart={(e) => onDragStart(e, image)}
|
onDragStart={(e) => onDragStart(e, image)}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
|
|
||||||
import { useState, useMemo, useCallback, useRef } from 'react';
|
import { useState, useMemo, useCallback, useRef } from 'react';
|
||||||
import { PhotoProvider } from 'react-photo-view';
|
import { PhotoProvider } from 'react-photo-view';
|
||||||
|
import PhotoStrip from './PhotoStrip';
|
||||||
import 'react-photo-view/dist/react-photo-view.css';
|
import 'react-photo-view/dist/react-photo-view.css';
|
||||||
import { VariableSizeList as List } from 'react-window';
|
import { VariableSizeList as List } from 'react-window';
|
||||||
|
|
||||||
@@ -27,6 +28,7 @@ import { useInfiniteScroll } from '../hooks/useInfiniteScroll';
|
|||||||
|
|
||||||
// Utils
|
// Utils
|
||||||
import { filterImages } from '../utils/imageFilters';
|
import { filterImages } from '../utils/imageFilters';
|
||||||
|
import { typeCountsOf, countLabel } from '../utils/fileTypes';
|
||||||
import { imageAPI, fileAPI } from '../api';
|
import { imageAPI, fileAPI } from '../api';
|
||||||
|
|
||||||
// Components
|
// Components
|
||||||
@@ -40,7 +42,6 @@ import UndoToast from './UndoToast';
|
|||||||
import RatingToast from './RatingToast';
|
import RatingToast from './RatingToast';
|
||||||
import FolderSelector from './FolderSelector';
|
import FolderSelector from './FolderSelector';
|
||||||
import ConflictDialog from './ConflictDialog';
|
import ConflictDialog from './ConflictDialog';
|
||||||
import VideoEditModal from './VideoEditModal';
|
|
||||||
import AIVideoModal from './AIVideoModal';
|
import AIVideoModal from './AIVideoModal';
|
||||||
|
|
||||||
// 虚拟滚动阈值
|
// 虚拟滚动阈值
|
||||||
@@ -58,13 +59,12 @@ function ImageWaterfall() {
|
|||||||
toggleImageSelection, clearSelection, imageLoadingState, selectedFolder,
|
toggleImageSelection, clearSelection, imageLoadingState, selectedFolder,
|
||||||
searchKeywords, filters, folders, setSelectedFolderItem, updateImage
|
searchKeywords, filters, folders, setSelectedFolderItem, updateImage
|
||||||
} = useImageStore();
|
} = useImageStore();
|
||||||
const { setEditingImage, setMergeImages } = useUIStore();
|
const { setEditingImage, setMergeImages, setVideoEditFile } = useUIStore();
|
||||||
|
|
||||||
// 状态
|
// 状态
|
||||||
const [photoIndex, setPhotoIndex] = useState(-1);
|
const [photoIndex, setPhotoIndex] = useState(-1);
|
||||||
const [lastSelectedIndex, setLastSelectedIndex] = useState(null);
|
const [lastSelectedIndex, setLastSelectedIndex] = useState(null);
|
||||||
const [viewerFile, setViewerFile] = useState(null);
|
const [viewerFile, setViewerFile] = useState(null);
|
||||||
const [videoEditFile, setVideoEditFile] = useState(null); // 视频编辑弹窗
|
|
||||||
const [aiVideoOpen, setAiVideoOpen] = useState(false); // AI 生成视频弹窗
|
const [aiVideoOpen, setAiVideoOpen] = useState(false); // AI 生成视频弹窗
|
||||||
const [contextMenu, setContextMenu] = useState({ isOpen: false, position: null, image: null });
|
const [contextMenu, setContextMenu] = useState({ isOpen: false, position: null, image: null });
|
||||||
// 统一图片移动/删除撤销顺序的栈:按操作时间顺序记录 'move' | 'delete'
|
// 统一图片移动/删除撤销顺序的栈:按操作时间顺序记录 'move' | 'delete'
|
||||||
@@ -198,10 +198,15 @@ function ImageWaterfall() {
|
|||||||
return imageAPI.getOriginalUrl(currentLibraryId, image.path);
|
return imageAPI.getOriginalUrl(currentLibraryId, image.path);
|
||||||
}, [currentLibraryId]);
|
}, [currentLibraryId]);
|
||||||
|
|
||||||
|
// 灯箱只收图片:视频/文档双击走 FileViewer,不进灯箱列表(底部缩略图条同源,打不开的文件不显示)
|
||||||
|
const lightboxImages = useMemo(() => {
|
||||||
|
return filteredImages.filter(img => (img.fileType || 'image') === 'image');
|
||||||
|
}, [filteredImages]);
|
||||||
|
|
||||||
// PhotoProvider 图片列表
|
// PhotoProvider 图片列表
|
||||||
const providerImages = useMemo(() => {
|
const providerImages = useMemo(() => {
|
||||||
return filteredImages.map(img => ({ src: getOriginalUrl(img), key: img.id }));
|
return lightboxImages.map(img => ({ src: getOriginalUrl(img), key: img.id }));
|
||||||
}, [filteredImages, getOriginalUrl]);
|
}, [lightboxImages, getOriginalUrl]);
|
||||||
|
|
||||||
// 图片点击处理 —— 单击选中,双击放大
|
// 图片点击处理 —— 单击选中,双击放大
|
||||||
const handleImageClick = useCallback((image, event, imageIndex) => {
|
const handleImageClick = useCallback((image, event, imageIndex) => {
|
||||||
@@ -237,11 +242,13 @@ function ImageWaterfall() {
|
|||||||
const handleImageDoubleClick = useCallback((image, flatIndex) => {
|
const handleImageDoubleClick = useCallback((image, flatIndex) => {
|
||||||
const fileType = image.fileType || 'image';
|
const fileType = image.fileType || 'image';
|
||||||
if (fileType === 'image') {
|
if (fileType === 'image') {
|
||||||
setPhotoIndex(flatIndex);
|
// flatIndex 是全量列表索引,灯箱列表只含图片 → 映射为图片子集索引
|
||||||
|
const idx = lightboxImages.findIndex(im => im.id === image.id);
|
||||||
|
setPhotoIndex(idx >= 0 ? idx : 0);
|
||||||
} else {
|
} else {
|
||||||
setViewerFile(image);
|
setViewerFile(image);
|
||||||
}
|
}
|
||||||
}, []);
|
}, [lightboxImages]);
|
||||||
|
|
||||||
// 文件名双击处理(重命名)
|
// 文件名双击处理(重命名)
|
||||||
const handleFilenameDoubleClick = useCallback((e, image) => {
|
const handleFilenameDoubleClick = useCallback((e, image) => {
|
||||||
@@ -538,13 +545,16 @@ onToggleFavorite={handleToggleFavorite}
|
|||||||
}
|
}
|
||||||
const unionCount = union.length;
|
const unionCount = union.length;
|
||||||
if (unionCount <= 1) return null;
|
if (unionCount <= 1) return null;
|
||||||
|
const unionTypeCounts = typeCountsOf(union);
|
||||||
return (
|
return (
|
||||||
<div className="absolute bottom-4 left-1/2 -translate-x-1/2 z-30 flex items-center gap-3 bg-gray-900/90 dark:bg-gray-800/90 backdrop-blur text-white rounded-full pl-5 pr-2 py-2 shadow-2xl">
|
<div className="absolute bottom-4 left-1/2 -translate-x-1/2 z-30 flex items-center gap-3 bg-gray-900/90 dark:bg-gray-800/90 backdrop-blur text-white rounded-full pl-5 pr-2 py-2 shadow-2xl">
|
||||||
<span className="text-sm whitespace-nowrap">已选 {unionCount} 张图片</span>
|
<span className="text-sm whitespace-nowrap">已选 {countLabel(unionCount, unionTypeCounts)}</span>
|
||||||
<button
|
<button
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setMergeImages(union);
|
// 合拼是图片功能:过滤出图片(与 AI 生成视频入口一致),视频/文档不进画布
|
||||||
setEditingImage(union[0]);
|
const imgOnly = union.filter((img) => (img.fileType || 'image') === 'image');
|
||||||
|
setMergeImages(imgOnly);
|
||||||
|
setEditingImage(imgOnly[0] || union[0]);
|
||||||
clearSelection();
|
clearSelection();
|
||||||
}}
|
}}
|
||||||
className="flex items-center gap-1.5 px-4 py-1.5 rounded-full bg-blue-600 hover:bg-blue-700 text-sm font-medium transition-colors"
|
className="flex items-center gap-1.5 px-4 py-1.5 rounded-full bg-blue-600 hover:bg-blue-700 text-sm font-medium transition-colors"
|
||||||
@@ -658,6 +668,14 @@ onToggleFavorite={handleToggleFavorite}
|
|||||||
)}
|
)}
|
||||||
</PhotoProvider>
|
</PhotoProvider>
|
||||||
|
|
||||||
|
{/* 灯箱底部缩略图条:只列图片(与 providerImages 同源对齐),点击跳转查看 */}
|
||||||
|
<PhotoStrip
|
||||||
|
images={lightboxImages}
|
||||||
|
index={photoIndex}
|
||||||
|
onIndexChange={setPhotoIndex}
|
||||||
|
getThumbnailUrl={getThumbnailUrl}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* 文件查看器 */}
|
{/* 文件查看器 */}
|
||||||
{viewerFile && (
|
{viewerFile && (
|
||||||
<FileViewer
|
<FileViewer
|
||||||
@@ -667,16 +685,6 @@ onToggleFavorite={handleToggleFavorite}
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* 视频编辑弹窗 */}
|
|
||||||
{videoEditFile && (
|
|
||||||
<VideoEditModal
|
|
||||||
file={videoEditFile}
|
|
||||||
libraryId={currentLibraryId}
|
|
||||||
onClose={() => setVideoEditFile(null)}
|
|
||||||
onDone={() => { setVideoEditFile(null); window.location.reload(); }}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* AI 生成视频弹窗 */}
|
{/* AI 生成视频弹窗 */}
|
||||||
{aiVideoOpen && (
|
{aiVideoOpen && (
|
||||||
<AIVideoModal
|
<AIVideoModal
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import requestManager, { RequestType } from '../services/requestManager';
|
|||||||
import domCleanup from '../utils/domCleanup';
|
import domCleanup from '../utils/domCleanup';
|
||||||
import ImageWaterfall from './ImageWaterfall';
|
import ImageWaterfall from './ImageWaterfall';
|
||||||
import Dashboard from './Dashboard';
|
import Dashboard from './Dashboard';
|
||||||
|
import BatchRenameModal from './BatchRenameModal';
|
||||||
|
import { PencilLine } from 'lucide-react';
|
||||||
import { createLogger } from '../utils/logger';
|
import { createLogger } from '../utils/logger';
|
||||||
|
|
||||||
const logger = createLogger('MainContent');
|
const logger = createLogger('MainContent');
|
||||||
@@ -18,6 +20,9 @@ function MainContent() {
|
|||||||
const { searchKeywords, filters, selectedFolder, favoritesView, setImages, setOriginalImages, imageLoadingState, images, refreshTick, folders, foldersLoaded } = useImageStore();
|
const { searchKeywords, filters, selectedFolder, favoritesView, setImages, setOriginalImages, imageLoadingState, images, refreshTick, folders, foldersLoaded } = useImageStore();
|
||||||
const { scanProgress } = useScanStore();
|
const { scanProgress } = useScanStore();
|
||||||
|
|
||||||
|
// 搜索结果批量重命名弹窗
|
||||||
|
const [searchRenameOpen, setSearchRenameOpen] = useState(false);
|
||||||
|
|
||||||
// 使用 ref 跟踪最新的请求上下文
|
// 使用 ref 跟踪最新的请求上下文
|
||||||
const currentRequestContextRef = useRef(null);
|
const currentRequestContextRef = useRef(null);
|
||||||
// 文件夹切换防抖
|
// 文件夹切换防抖
|
||||||
@@ -208,7 +213,7 @@ function MainContent() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-xs text-blue-600 dark:text-blue-400">
|
<div className="text-xs text-blue-600 dark:text-blue-400">
|
||||||
已处理 {scanProgress?.current || 0} / {scanProgress?.total || 0} 张图片
|
已处理 {scanProgress.processed} / {scanProgress.total} 个文件
|
||||||
{getEstimatedTime() && ` · ${getEstimatedTime()}`}
|
{getEstimatedTime() && ` · ${getEstimatedTime()}`}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -219,7 +224,7 @@ function MainContent() {
|
|||||||
<div className="px-4 py-2 bg-gray-100 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
|
<div className="px-4 py-2 bg-gray-100 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
|
||||||
<div className="flex items-center justify-between text-sm">
|
<div className="flex items-center justify-between text-sm">
|
||||||
<span className="text-gray-600 dark:text-gray-400">
|
<span className="text-gray-600 dark:text-gray-400">
|
||||||
已加载 {images.length} / {imageLoadingState.totalCount} 张
|
已加载 {images.length} / {imageLoadingState.totalCount} 个文件
|
||||||
</span>
|
</span>
|
||||||
<div className="w-32 h-1.5 bg-gray-200 rounded-full overflow-hidden">
|
<div className="w-32 h-1.5 bg-gray-200 rounded-full overflow-hidden">
|
||||||
<div
|
<div
|
||||||
@@ -236,7 +241,39 @@ function MainContent() {
|
|||||||
{(!selectedFolder && !searchKeywords && filters.formats.length === 0 && !favoritesView && (!foldersLoaded || folders.length > 0)) ? (
|
{(!selectedFolder && !searchKeywords && filters.formats.length === 0 && !favoritesView && (!foldersLoaded || folders.length > 0)) ? (
|
||||||
<Dashboard />
|
<Dashboard />
|
||||||
) : (
|
) : (
|
||||||
<ImageWaterfall />
|
<>
|
||||||
|
{/* 搜索结果工具条:对模糊命中的全部文件批量重命名 */}
|
||||||
|
{searchKeywords && (
|
||||||
|
<div className="px-3 sm:px-5 pt-3 flex items-center gap-2 flex-wrap">
|
||||||
|
<span className="text-xs text-gray-500 dark:text-gray-400">
|
||||||
|
搜索「{searchKeywords}」的模糊匹配结果
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={() => setSearchRenameOpen(true)}
|
||||||
|
className="inline-flex items-center gap-1.5 text-xs px-2.5 py-1 rounded-lg bg-violet-500 text-white hover:bg-violet-600 transition-colors"
|
||||||
|
>
|
||||||
|
<PencilLine className="w-3.5 h-3.5" />
|
||||||
|
批量重命名搜索结果…
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<ImageWaterfall />
|
||||||
|
{/* 搜索结果批量重命名 */}
|
||||||
|
{searchRenameOpen && (
|
||||||
|
<BatchRenameModal
|
||||||
|
isOpen={searchRenameOpen}
|
||||||
|
folder={selectedFolder}
|
||||||
|
libraryId={currentLibraryId}
|
||||||
|
scope="search"
|
||||||
|
keywords={searchKeywords}
|
||||||
|
onClose={() => setSearchRenameOpen(false)}
|
||||||
|
onFinished={() => {
|
||||||
|
setSearchRenameOpen(false);
|
||||||
|
useImageStore.getState().bumpRefresh();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -221,7 +221,7 @@ export default function MergeCollage({ image, libraryId, onMerge, setStatus, set
|
|||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
Authorization: `*** ${getToken()}`
|
Authorization: `Bearer ${getToken()}`
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
libraryId,
|
libraryId,
|
||||||
|
|||||||
@@ -0,0 +1,152 @@
|
|||||||
|
/**
|
||||||
|
* 灯箱底部缩略图条 + 幻灯片播放
|
||||||
|
* 双击图片放大后,在底部列出当前文件夹(含筛选)下的全部图片,
|
||||||
|
* 点击任意缩略图直接跳转查看,与 react-photo-view 的 index 一一对应。
|
||||||
|
* 左侧提供幻灯片播放:▶ 播放 / ⏸ 暂停,间隔可选(1/2/3/5/10 秒,localStorage 记忆)。
|
||||||
|
*
|
||||||
|
* 通过 portal 挂到 body:react-photo-view 也是 portal 到 body(z-index 2000),
|
||||||
|
* 这里用 2100 保证压在其上方,且不被祖先的 transform/filter 形成的层叠上下文困住。
|
||||||
|
*/
|
||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
|
|
||||||
|
const INTERVAL_KEY = 'flypic_slideshow_interval';
|
||||||
|
const INTERVAL_OPTIONS = [1, 2, 3, 5, 10];
|
||||||
|
|
||||||
|
export default function PhotoStrip({ images, index, onIndexChange, getThumbnailUrl }) {
|
||||||
|
const stripRef = useRef(null);
|
||||||
|
const [playing, setPlaying] = useState(false);
|
||||||
|
const [intervalSec, setIntervalSec] = useState(() => {
|
||||||
|
const v = parseFloat(localStorage.getItem(INTERVAL_KEY));
|
||||||
|
return INTERVAL_OPTIONS.includes(v) ? v : 3;
|
||||||
|
});
|
||||||
|
// 缩略图加载失败(后端可能返回 0 字节 webp)→ 退化为格式角标
|
||||||
|
const [failed, setFailed] = useState({});
|
||||||
|
|
||||||
|
const total = images ? images.length : 0;
|
||||||
|
|
||||||
|
const changeInterval = (v) => {
|
||||||
|
setIntervalSec(v);
|
||||||
|
localStorage.setItem(INTERVAL_KEY, String(v));
|
||||||
|
};
|
||||||
|
|
||||||
|
// 灯箱关闭即停播(组件在 index<0 时仍挂载,只是返回 null)
|
||||||
|
useEffect(() => {
|
||||||
|
if (index < 0 && playing) setPlaying(false);
|
||||||
|
}, [index, playing]);
|
||||||
|
|
||||||
|
// 幻灯片:每张停留 intervalSec,到末尾循环回首张;
|
||||||
|
// 手动跳转(index 变化)会重排计时器,让新图也停留满一个间隔。
|
||||||
|
useEffect(() => {
|
||||||
|
if (!playing || index < 0 || total < 2) return undefined;
|
||||||
|
const t = setTimeout(() => onIndexChange((index + 1) % total), intervalSec * 1000);
|
||||||
|
return () => clearTimeout(t);
|
||||||
|
}, [playing, index, intervalSec, total, onIndexChange]);
|
||||||
|
|
||||||
|
// 切换图片时把当前缩略图滚到条中间(只滚条自身,不动页面)
|
||||||
|
useEffect(() => {
|
||||||
|
if (index < 0 || !stripRef.current) return;
|
||||||
|
const el = stripRef.current.querySelector('[data-active="true"]');
|
||||||
|
if (!el) return;
|
||||||
|
const c = stripRef.current;
|
||||||
|
c.scrollTo({
|
||||||
|
left: el.offsetLeft - c.clientWidth / 2 + el.clientWidth / 2,
|
||||||
|
behavior: 'smooth',
|
||||||
|
});
|
||||||
|
}, [index]);
|
||||||
|
|
||||||
|
if (index < 0 || !images || !images.length) return null;
|
||||||
|
|
||||||
|
return createPortal(
|
||||||
|
<div className="fixed bottom-0 left-0 right-0 z-[2100] bg-black/85 backdrop-blur-sm border-t border-white/10">
|
||||||
|
<div className="flex items-center gap-2 px-3 py-2">
|
||||||
|
{/* 当前进度 */}
|
||||||
|
<span className="shrink-0 text-[11px] text-gray-300 tabular-nums select-none pr-1 border-r border-white/15 mr-1">
|
||||||
|
{index + 1} / {total}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
{/* 幻灯片播放:▶/⏸ + 间隔选择 */}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
title={playing ? '暂停幻灯片播放' : '幻灯片播放'}
|
||||||
|
aria-label={playing ? '暂停幻灯片' : '播放幻灯片'}
|
||||||
|
onClick={() => total >= 2 && setPlaying((p) => !p)}
|
||||||
|
className={`shrink-0 w-7 h-7 rounded-full flex items-center justify-center transition-colors ${
|
||||||
|
playing
|
||||||
|
? 'bg-purple-500 text-white hover:bg-purple-400'
|
||||||
|
: 'bg-white/10 text-gray-200 hover:bg-white/20'
|
||||||
|
} ${total < 2 ? 'opacity-40 cursor-not-allowed' : ''}`}
|
||||||
|
>
|
||||||
|
{playing ? (
|
||||||
|
<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
|
||||||
|
<rect x="6" y="4" width="4" height="16" rx="1" />
|
||||||
|
<rect x="14" y="4" width="4" height="16" rx="1" />
|
||||||
|
</svg>
|
||||||
|
) : (
|
||||||
|
<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
|
||||||
|
<path d="M7 4.5v15l13-7.5z" />
|
||||||
|
</svg>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
<select
|
||||||
|
title="幻灯片切换间隔"
|
||||||
|
aria-label="幻灯片切换间隔"
|
||||||
|
value={intervalSec}
|
||||||
|
onChange={(e) => changeInterval(parseFloat(e.target.value))}
|
||||||
|
className={`shrink-0 h-7 rounded bg-white/10 text-[11px] text-gray-200 px-1 pr-4 outline-none cursor-pointer hover:bg-white/20 border border-transparent focus:border-purple-400/60 ${
|
||||||
|
playing ? 'border-purple-400/60' : ''
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{INTERVAL_OPTIONS.map((s) => (
|
||||||
|
<option key={s} value={s} className="bg-gray-900 text-gray-100">
|
||||||
|
{s} 秒
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
|
||||||
|
{/* 缩略图横向滚动条 */}
|
||||||
|
<div
|
||||||
|
ref={stripRef}
|
||||||
|
className="flex-1 flex items-center gap-1.5 overflow-x-auto overflow-y-hidden scrollbar-thin"
|
||||||
|
style={{ scrollbarWidth: 'thin' }}
|
||||||
|
>
|
||||||
|
{images.map((img, i) => {
|
||||||
|
const src = getThumbnailUrl ? getThumbnailUrl(img) : '';
|
||||||
|
const active = i === index;
|
||||||
|
const bad = failed[img.id ?? i];
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={img.id ?? i}
|
||||||
|
type="button"
|
||||||
|
data-active={active ? 'true' : 'false'}
|
||||||
|
title={img.filename || ''}
|
||||||
|
onClick={() => onIndexChange(i)}
|
||||||
|
className={`relative shrink-0 w-12 h-12 rounded overflow-hidden border-2 transition-all duration-150 ${
|
||||||
|
active
|
||||||
|
? 'border-purple-500 ring-2 ring-purple-400/60 scale-105 z-10'
|
||||||
|
: 'border-transparent opacity-55 hover:opacity-100 hover:border-white/40'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{src && !bad ? (
|
||||||
|
<img
|
||||||
|
src={src}
|
||||||
|
alt={img.filename || ''}
|
||||||
|
decoding="async"
|
||||||
|
draggable={false}
|
||||||
|
onError={() => setFailed((f) => ({ ...f, [img.id ?? i]: true }))}
|
||||||
|
className="w-full h-full object-cover pointer-events-none"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<span className="w-full h-full flex items-center justify-center bg-gray-800 text-[9px] text-gray-400">
|
||||||
|
{(img.format || (img.filename || '').split('.').pop() || '').slice(0, 5)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>,
|
||||||
|
document.body
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -40,7 +40,7 @@ function RatingToast({ isVisible, rating, count, onClose, duration = 2000 }) {
|
|||||||
</div>
|
</div>
|
||||||
<span className="text-sm font-medium">
|
<span className="text-sm font-medium">
|
||||||
{rating === 0 ? '已取消评分' : `已评 ${rating} 星`}
|
{rating === 0 ? '已取消评分' : `已评 ${rating} 星`}
|
||||||
{count > 1 ? ` (${count} 张)` : ''}
|
{count > 1 ? ` (${count} 个)` : ''}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -9,13 +9,14 @@ import { imageAPI, fileAPI } from '../api';
|
|||||||
import JSZip from 'jszip';
|
import JSZip from 'jszip';
|
||||||
import RatingStars from './RatingStars';
|
import RatingStars from './RatingStars';
|
||||||
import { createLogger } from '../utils/logger';
|
import { createLogger } from '../utils/logger';
|
||||||
|
import { typeMeta, typeCountsOf, countLabel, typeLabelOf } from '../utils/fileTypes';
|
||||||
|
|
||||||
const logger = createLogger('RightPanel');
|
const logger = createLogger('RightPanel');
|
||||||
|
|
||||||
function RightPanel() {
|
function RightPanel() {
|
||||||
const { currentLibraryId } = useLibraryStore();
|
const { currentLibraryId } = useLibraryStore();
|
||||||
const { selectedImage, selectedImages, selectedFolder, selectedFolderItem, images, setSelectedImage, setSelectedImages, updateImage } = useImageStore();
|
const { selectedImage, selectedImages, selectedFolder, selectedFolderItem, images, setSelectedImage, setSelectedImages, updateImage } = useImageStore();
|
||||||
const { setMobileView, isResizingPanels, resizingSide, setEditingImage } = useUIStore();
|
const { setMobileView, isResizingPanels, resizingSide, setEditingImage, setVideoEditFile } = useUIStore();
|
||||||
const { copyToClipboard } = useClipboardStore();
|
const { copyToClipboard } = useClipboardStore();
|
||||||
const [isMobile, setIsMobile] = useState(false);
|
const [isMobile, setIsMobile] = useState(false);
|
||||||
const [imageUrl, setImageUrl] = useState(''); // 当前显示的图片URL
|
const [imageUrl, setImageUrl] = useState(''); // 当前显示的图片URL
|
||||||
@@ -50,6 +51,8 @@ function RightPanel() {
|
|||||||
// 判断是单选还是多选
|
// 判断是单选还是多选
|
||||||
const isMultiSelect = actualSelectedCount > 1;
|
const isMultiSelect = actualSelectedCount > 1;
|
||||||
const displayImage = selectedImages.length > 0 ? selectedImages[0] : selectedImage;
|
const displayImage = selectedImages.length > 0 ? selectedImages[0] : selectedImage;
|
||||||
|
// 视频文件判定:右侧面板按文件类型展示,视频不再套用图片文案/操作
|
||||||
|
const singleIsVideo = !isMultiSelect && (displayImage?.fileType === 'video');
|
||||||
const { getCurrentLibrary } = useLibraryStore();
|
const { getCurrentLibrary } = useLibraryStore();
|
||||||
const currentLibrary = getCurrentLibrary();
|
const currentLibrary = getCurrentLibrary();
|
||||||
|
|
||||||
@@ -319,7 +322,7 @@ function RightPanel() {
|
|||||||
setSelectedImages(updatedSelectedImages);
|
setSelectedImages(updatedSelectedImages);
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.file(`已更新 ${paths.length} 张图片的评分为 ${newRating} 星`);
|
logger.file(`已更新 ${paths.length} 个文件的评分为 ${newRating} 星`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('更新评分失败:', error);
|
logger.error('更新评分失败:', error);
|
||||||
alert('更新评分失败: ' + (error.message || '未知错误'));
|
alert('更新评分失败: ' + (error.message || '未知错误'));
|
||||||
@@ -597,7 +600,14 @@ function RightPanel() {
|
|||||||
|
|
||||||
// 2. 获取原图URL,写入系统剪贴板
|
// 2. 获取原图URL,写入系统剪贴板
|
||||||
const imageUrl = imageAPI.getOriginalUrl(currentLibraryId, selectedImage.path);
|
const imageUrl = imageAPI.getOriginalUrl(currentLibraryId, selectedImage.path);
|
||||||
|
|
||||||
|
// 视频无法转换为图片写入系统剪贴板,仅保留应用内复制(供粘贴移动)
|
||||||
|
if (selectedImage?.fileType === 'video') {
|
||||||
|
setImageCopied(true);
|
||||||
|
setTimeout(() => setImageCopied(false), 2000);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// 方案1:尝试现代 Clipboard API(需要 HTTPS)
|
// 方案1:尝试现代 Clipboard API(需要 HTTPS)
|
||||||
if (isClipboardApiSupported()) {
|
if (isClipboardApiSupported()) {
|
||||||
try {
|
try {
|
||||||
@@ -770,6 +780,10 @@ function RightPanel() {
|
|||||||
return selectedImage ? [selectedImage] : [];
|
return selectedImage ? [selectedImage] : [];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 选中集合类型计数(由类型注册表驱动文案:图片/视频/文档…混合自动按"文件")
|
||||||
|
const selectionTypeCounts = typeCountsOf(getImagesToProcess());
|
||||||
|
const selectionTypeLabel = typeLabelOf(selectionTypeCounts);
|
||||||
|
|
||||||
// 批量复制图片
|
// 批量复制图片
|
||||||
const copyMultipleImages = async () => {
|
const copyMultipleImages = async () => {
|
||||||
try {
|
try {
|
||||||
@@ -1083,15 +1097,16 @@ function RightPanel() {
|
|||||||
|
|
||||||
const totalCount = folderImages.length;
|
const totalCount = folderImages.length;
|
||||||
const totalSize = folderImages.reduce((sum, img) => sum + (img.size || 0), 0);
|
const totalSize = folderImages.reduce((sum, img) => sum + (img.size || 0), 0);
|
||||||
|
const folderTypeCounts = typeCountsOf(folderImages);
|
||||||
return { totalCount, totalSize };
|
|
||||||
|
return { totalCount, totalSize, folderTypeCounts };
|
||||||
};
|
};
|
||||||
|
|
||||||
// ========== 文件夹详情渲染 ==========
|
// ========== 文件夹详情渲染 ==========
|
||||||
if (isShowingFolder) {
|
if (isShowingFolder) {
|
||||||
const folderPath = selectedFolderItem.path;
|
const folderPath = selectedFolderItem.path;
|
||||||
const folderName = selectedFolderItem.name;
|
const folderName = selectedFolderItem.name;
|
||||||
const { totalCount, totalSize } = getFolderStats(folderPath);
|
const { totalCount, totalSize, folderTypeCounts } = getFolderStats(folderPath);
|
||||||
const fullPath = currentLibrary?.path
|
const fullPath = currentLibrary?.path
|
||||||
? normalizePath(`${currentLibrary.path}${getPathSeparator()}${folderPath}`)
|
? normalizePath(`${currentLibrary.path}${getPathSeparator()}${folderPath}`)
|
||||||
: folderPath;
|
: folderPath;
|
||||||
@@ -1148,8 +1163,8 @@ function RightPanel() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<span className="text-gray-500 dark:text-gray-400">包含图片:</span>
|
<span className="text-gray-500 dark:text-gray-400">包含:</span>
|
||||||
<p className="text-gray-900 dark:text-gray-100">{totalCount} 张(含子文件夹)</p>
|
<p className="text-gray-900 dark:text-gray-100">{countLabel(totalCount, folderTypeCounts)}(含子文件夹)</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<span className="text-gray-500 dark:text-gray-400">总大小:</span>
|
<span className="text-gray-500 dark:text-gray-400">总大小:</span>
|
||||||
@@ -1200,7 +1215,7 @@ function RightPanel() {
|
|||||||
<span>
|
<span>
|
||||||
{isExportingFolder
|
{isExportingFolder
|
||||||
? `打包中... ${folderExportProgress}%`
|
? `打包中... ${folderExportProgress}%`
|
||||||
: `导出文件夹 (${totalCount} 张)`
|
: `导出文件夹 (${countLabel(totalCount, folderTypeCounts)})`
|
||||||
}
|
}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -1251,7 +1266,7 @@ function RightPanel() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
title="双击查看第一张图片"
|
title="双击查看原文件"
|
||||||
>
|
>
|
||||||
{(() => {
|
{(() => {
|
||||||
const imagesToShow = getImagesToProcess().slice(0, 5);
|
const imagesToShow = getImagesToProcess().slice(0, 5);
|
||||||
@@ -1312,7 +1327,16 @@ function RightPanel() {
|
|||||||
}}
|
}}
|
||||||
title="双击查看原文件"
|
title="双击查看原文件"
|
||||||
>
|
>
|
||||||
{imageUrl ? (
|
{singleIsVideo ? (
|
||||||
|
// 视频:直接播放原文件(不再以图片缩略图形式展示)
|
||||||
|
<video
|
||||||
|
src={getOriginalUrl()}
|
||||||
|
poster={imageUrl || undefined}
|
||||||
|
controls
|
||||||
|
preload="metadata"
|
||||||
|
className="w-full h-full object-contain bg-black"
|
||||||
|
/>
|
||||||
|
) : imageUrl ? (
|
||||||
<img
|
<img
|
||||||
src={imageUrl}
|
src={imageUrl}
|
||||||
alt={displayImage.filename}
|
alt={displayImage.filename}
|
||||||
@@ -1346,7 +1370,7 @@ function RightPanel() {
|
|||||||
<div className="flex-1 overflow-y-auto p-4 space-y-4 min-h-0">
|
<div className="flex-1 overflow-y-auto p-4 space-y-4 min-h-0">
|
||||||
<div>
|
<div>
|
||||||
<h3 className="text-xs font-semibold text-gray-700 dark:text-gray-300 mb-2">
|
<h3 className="text-xs font-semibold text-gray-700 dark:text-gray-300 mb-2">
|
||||||
{isMultiSelect ? `已选择 ${actualSelectedCount} 张图片` : '基本信息'}
|
{isMultiSelect ? `已选择 ${countLabel(actualSelectedCount, selectionTypeCounts)}` : '基本信息'}
|
||||||
</h3>
|
</h3>
|
||||||
<div className="space-y-2 text-xs">
|
<div className="space-y-2 text-xs">
|
||||||
{isMultiSelect ? (
|
{isMultiSelect ? (
|
||||||
@@ -1359,7 +1383,7 @@ function RightPanel() {
|
|||||||
<>
|
<>
|
||||||
<div>
|
<div>
|
||||||
<span className="text-gray-500 dark:text-gray-400">数量:</span>
|
<span className="text-gray-500 dark:text-gray-400">数量:</span>
|
||||||
<p className="text-gray-900 dark:text-gray-100 text-xs">{stats.count} 张图片</p>
|
<p className="text-gray-900 dark:text-gray-100 text-xs">{countLabel(stats.count, selectionTypeCounts)}</p>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<span className="text-gray-500 dark:text-gray-400">评分:</span>
|
<span className="text-gray-500 dark:text-gray-400">评分:</span>
|
||||||
@@ -1492,6 +1516,14 @@ function RightPanel() {
|
|||||||
<span className="text-gray-500 dark:text-gray-400">尺寸:</span>
|
<span className="text-gray-500 dark:text-gray-400">尺寸:</span>
|
||||||
<p className="text-gray-900 dark:text-gray-100 text-xs">{selectedImage.width} × {selectedImage.height}</p>
|
<p className="text-gray-900 dark:text-gray-100 text-xs">{selectedImage.width} × {selectedImage.height}</p>
|
||||||
</div>
|
</div>
|
||||||
|
{singleIsVideo && selectedImage.duration > 0 && (
|
||||||
|
<div>
|
||||||
|
<span className="text-gray-500 dark:text-gray-400">时长:</span>
|
||||||
|
<p className="text-gray-900 dark:text-gray-100 text-xs font-mono tabular-nums">
|
||||||
|
{Math.floor(selectedImage.duration / 60)}:{String(Math.floor(selectedImage.duration % 60)).padStart(2, '0')}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<div>
|
<div>
|
||||||
<span className="text-gray-500 dark:text-gray-400">文件大小:</span>
|
<span className="text-gray-500 dark:text-gray-400">文件大小:</span>
|
||||||
<p className="text-gray-900 dark:text-gray-100 text-xs">{formatFileSize(selectedImage.size)}</p>
|
<p className="text-gray-900 dark:text-gray-100 text-xs">{formatFileSize(selectedImage.size)}</p>
|
||||||
@@ -1552,7 +1584,7 @@ function RightPanel() {
|
|||||||
</div>
|
</div>
|
||||||
{isMultiSelect && (
|
{isMultiSelect && (
|
||||||
<p className="text-xs text-gray-400 dark:text-gray-500 mt-1">
|
<p className="text-xs text-gray-400 dark:text-gray-500 mt-1">
|
||||||
已选择 {actualSelectedCount} 张图片的共同父路径
|
已选择 {countLabel(actualSelectedCount, selectionTypeCounts)}的共同父路径
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -1563,16 +1595,23 @@ function RightPanel() {
|
|||||||
{/* Actions - 仅桌面端显示 */}
|
{/* Actions - 仅桌面端显示 */}
|
||||||
{!isMobile && (
|
{!isMobile && (
|
||||||
<div className="p-4 border-t border-gray-200 dark:border-gray-700 space-y-2 flex-shrink-0">
|
<div className="p-4 border-t border-gray-200 dark:border-gray-700 space-y-2 flex-shrink-0">
|
||||||
{/* 编辑图片(单选时) */}
|
{/* 编辑图片/视频(单选时) */}
|
||||||
{!isMultiSelect && selectedImage && (
|
{!isMultiSelect && selectedImage && (
|
||||||
<button
|
<button
|
||||||
onClick={() => setEditingImage(selectedImage)}
|
onClick={() => {
|
||||||
|
if (singleIsVideo) {
|
||||||
|
// 视频 → 视频编辑弹窗(水印/字幕声音)
|
||||||
|
setVideoEditFile(selectedImage);
|
||||||
|
} else {
|
||||||
|
setEditingImage(selectedImage);
|
||||||
|
}
|
||||||
|
}}
|
||||||
className="w-full flex items-center justify-center gap-2 px-4 py-2 rounded-lg bg-blue-600 text-white hover:bg-blue-700 transition-colors"
|
className="w-full flex items-center justify-center gap-2 px-4 py-2 rounded-lg bg-blue-600 text-white hover:bg-blue-700 transition-colors"
|
||||||
>
|
>
|
||||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
|
||||||
</svg>
|
</svg>
|
||||||
编辑图片
|
{singleIsVideo ? '编辑视频' : '编辑图片'}
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
{/* 复制按钮 */}
|
{/* 复制按钮 */}
|
||||||
@@ -1587,12 +1626,14 @@ function RightPanel() {
|
|||||||
{imageCopied ? (
|
{imageCopied ? (
|
||||||
<>
|
<>
|
||||||
<Check className="w-4 h-4" />
|
<Check className="w-4 h-4" />
|
||||||
<span>已复制{isMultiSelect ? ` ${actualSelectedCount} 张` : ''}</span>
|
<span>已复制{isMultiSelect ? ` ${countLabel(actualSelectedCount, selectionTypeCounts)}` : ''}</span>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<Copy className="w-4 h-4" />
|
<Copy className="w-4 h-4" />
|
||||||
<span>复制图片{isMultiSelect ? ` (${actualSelectedCount})` : ''}</span>
|
<span>
|
||||||
|
{`复制${singleIsVideo ? '视频' : selectionTypeLabel}${isMultiSelect ? ` (${actualSelectedCount})` : ''}`}
|
||||||
|
</span>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
@@ -1608,7 +1649,7 @@ function RightPanel() {
|
|||||||
<span>
|
<span>
|
||||||
{isExporting
|
{isExporting
|
||||||
? `打包中... ${exportProgress}%`
|
? `打包中... ${exportProgress}%`
|
||||||
: `导出图片${isMultiSelect ? ` (${actualSelectedCount})` : ''}`
|
: `导出${singleIsVideo ? '视频' : selectionTypeLabel}${isMultiSelect ? ` (${actualSelectedCount})` : ''}`
|
||||||
}
|
}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { X, ScanText, Info, Save, FlaskConical, Github, ExternalLink, Wand2 } from 'lucide-react';
|
import { X, ScanText, Info, Save, FlaskConical, Github, ExternalLink, Wand2, Film } from 'lucide-react';
|
||||||
import { settingsAPI } from '../api';
|
import { settingsAPI, aigenAPI } from '../api';
|
||||||
|
|
||||||
const APP_VERSION = 'v1.4.2';
|
const APP_VERSION = 'v1.4.15';
|
||||||
const REPO_URL = 'https://gitea.88531.cn/jinghui/flypic';
|
const REPO_URL = 'https://gitea.88531.cn/jinghui/flypic';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -17,6 +17,9 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
|
|||||||
const [ig, setIg] = useState(null); // imagegen 配置
|
const [ig, setIg] = useState(null); // imagegen 配置
|
||||||
const [igNewKey, setIgNewKey] = useState(''); // NewAPI 新密钥
|
const [igNewKey, setIgNewKey] = useState(''); // NewAPI 新密钥
|
||||||
const [igCustomKey, setIgCustomKey] = useState(''); // 自定义提供商新密钥
|
const [igCustomKey, setIgCustomKey] = useState(''); // 自定义提供商新密钥
|
||||||
|
const [igGroups, setIgGroups] = useState([]); // 内置模型分组(默认模型下拉用)
|
||||||
|
const [va, setVa] = useState(null); // AI 视频文本模型配置
|
||||||
|
const [vaKey, setVaKey] = useState(''); // AI 视频新密钥
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [testing, setTesting] = useState(false);
|
const [testing, setTesting] = useState(false);
|
||||||
const [msg, setMsg] = useState(null); // { type, text }
|
const [msg, setMsg] = useState(null); // { type, text }
|
||||||
@@ -28,6 +31,7 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
|
|||||||
setApiKeyInput('');
|
setApiKeyInput('');
|
||||||
setIgNewKey('');
|
setIgNewKey('');
|
||||||
setIgCustomKey('');
|
setIgCustomKey('');
|
||||||
|
setVaKey('');
|
||||||
settingsAPI.getSettings()
|
settingsAPI.getSettings()
|
||||||
.then((d) => { setCfg({
|
.then((d) => { setCfg({
|
||||||
provider: d?.provider || 'local',
|
provider: d?.provider || 'local',
|
||||||
@@ -42,6 +46,7 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
|
|||||||
provider: d?.imagegen?.provider || 'newapi',
|
provider: d?.imagegen?.provider || 'newapi',
|
||||||
newapi: {
|
newapi: {
|
||||||
url: d?.imagegen?.newapi?.url || 'http://192.168.68.19:3099/v1',
|
url: d?.imagegen?.newapi?.url || 'http://192.168.68.19:3099/v1',
|
||||||
|
model: d?.imagegen?.newapi?.model || 'flux-schnell',
|
||||||
apiKeyMasked: d?.imagegen?.newapi?.apiKeyMasked || '',
|
apiKeyMasked: d?.imagegen?.newapi?.apiKeyMasked || '',
|
||||||
hasKey: !!d?.imagegen?.newapi?.hasKey
|
hasKey: !!d?.imagegen?.newapi?.hasKey
|
||||||
},
|
},
|
||||||
@@ -51,8 +56,20 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
|
|||||||
apiKeyMasked: d?.imagegen?.custom?.apiKeyMasked || ''
|
apiKeyMasked: d?.imagegen?.custom?.apiKeyMasked || ''
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
setVa({
|
||||||
|
provider: d?.videoai?.provider === 'custom' ? 'custom' : 'inherit',
|
||||||
|
custom: {
|
||||||
|
url: d?.videoai?.custom?.url || '',
|
||||||
|
model: d?.videoai?.custom?.model || '',
|
||||||
|
apiKeyMasked: d?.videoai?.custom?.apiKeyMasked || '',
|
||||||
|
configured: !!d?.videoai?.custom?.configured
|
||||||
|
}
|
||||||
|
});
|
||||||
})
|
})
|
||||||
.catch((e) => setMsg({ type: 'error', text: '读取设置失败: ' + (e.data?.message || e.message) }));
|
.catch((e) => setMsg({ type: 'error', text: '读取设置失败: ' + (e.data?.message || e.message) }));
|
||||||
|
aigenAPI.getModels()
|
||||||
|
.then((d) => setIgGroups(d.groups || []))
|
||||||
|
.catch(() => setIgGroups([]));
|
||||||
}, [open]);
|
}, [open]);
|
||||||
|
|
||||||
if (!open) return null;
|
if (!open) return null;
|
||||||
@@ -77,6 +94,7 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
|
|||||||
provider: ig.provider,
|
provider: ig.provider,
|
||||||
newapi: {
|
newapi: {
|
||||||
url: ig.newapi.url,
|
url: ig.newapi.url,
|
||||||
|
model: ig.newapi.model || 'flux-schnell',
|
||||||
apiKey: igNewKey || '' // 空 = 保持原密钥
|
apiKey: igNewKey || '' // 空 = 保持原密钥
|
||||||
},
|
},
|
||||||
custom: {
|
custom: {
|
||||||
@@ -85,6 +103,16 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
|
|||||||
apiKey: igCustomKey || ''
|
apiKey: igCustomKey || ''
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} : {}),
|
||||||
|
...(va ? {
|
||||||
|
videoai: {
|
||||||
|
provider: va.provider,
|
||||||
|
custom: {
|
||||||
|
url: va.custom.url,
|
||||||
|
model: va.custom.model,
|
||||||
|
apiKey: vaKey || ''
|
||||||
|
}
|
||||||
|
}
|
||||||
} : {})
|
} : {})
|
||||||
};
|
};
|
||||||
const data = await settingsAPI.updateSettings(payload);
|
const data = await settingsAPI.updateSettings(payload);
|
||||||
@@ -105,8 +133,20 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
setApiKeyInput('');
|
setApiKeyInput('');
|
||||||
|
if (data?.videoai) {
|
||||||
|
setVa({
|
||||||
|
provider: data.videoai.provider === 'custom' ? 'custom' : 'inherit',
|
||||||
|
custom: {
|
||||||
|
url: data.videoai.custom?.url || '',
|
||||||
|
model: data.videoai.custom?.model || '',
|
||||||
|
apiKeyMasked: data.videoai.custom?.apiKeyMasked || '',
|
||||||
|
configured: !!data.videoai.custom?.configured
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
setIgNewKey('');
|
setIgNewKey('');
|
||||||
setIgCustomKey('');
|
setIgCustomKey('');
|
||||||
|
setVaKey('');
|
||||||
setMsg({ type: 'ok', text: '已保存,新配置立即生效' });
|
setMsg({ type: 'ok', text: '已保存,新配置立即生效' });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setMsg({ type: 'error', text: '保存失败: ' + (e.data?.message || e.message) });
|
setMsg({ type: 'error', text: '保存失败: ' + (e.data?.message || e.message) });
|
||||||
@@ -142,11 +182,12 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
|
|||||||
const menus = [
|
const menus = [
|
||||||
{ key: 'ocr', label: 'OCR 识别', icon: ScanText },
|
{ key: 'ocr', label: 'OCR 识别', icon: ScanText },
|
||||||
{ key: 'aigen', label: 'AI 生图', icon: Wand2 },
|
{ key: 'aigen', label: 'AI 生图', icon: Wand2 },
|
||||||
|
{ key: 'videoai', label: 'AI 视频', icon: Film },
|
||||||
{ key: 'about', label: '关于', icon: Info }
|
{ key: 'about', label: '关于', icon: Info }
|
||||||
];
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
|
||||||
<div
|
<div
|
||||||
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-3xl max-h-[85vh] overflow-hidden flex"
|
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-3xl max-h-[85vh] overflow-hidden flex"
|
||||||
onClick={(e) => e.stopPropagation()}
|
onClick={(e) => e.stopPropagation()}
|
||||||
@@ -174,7 +215,7 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
|
|||||||
<div className="flex-1 p-6 overflow-y-auto">
|
<div className="flex-1 p-6 overflow-y-auto">
|
||||||
<div className="flex items-center justify-between mb-4">
|
<div className="flex items-center justify-between mb-4">
|
||||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">
|
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">
|
||||||
{active === 'ocr' ? 'OCR 识别设置' : active === 'aigen' ? 'AI 生图设置' : '关于'}
|
{active === 'ocr' ? 'OCR 识别设置' : active === 'aigen' ? 'AI 生图设置' : active === 'videoai' ? 'AI 视频设置' : '关于'}
|
||||||
</h2>
|
</h2>
|
||||||
<button onClick={onClose} className="p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">
|
<button onClick={onClose} className="p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">
|
||||||
<X className="w-5 h-5 text-gray-500" />
|
<X className="w-5 h-5 text-gray-500" />
|
||||||
@@ -285,7 +326,7 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
|
|||||||
{active === 'aigen' && cfg && ig && (
|
{active === 'aigen' && cfg && ig && (
|
||||||
<div className="space-y-5">
|
<div className="space-y-5">
|
||||||
<p className="text-xs text-gray-500 dark:text-gray-400">
|
<p className="text-xs text-gray-500 dark:text-gray-400">
|
||||||
AI 生图默认走内置 NewAPI(Pollinations + CF Workers AI 两个生图渠道);也可以切换到自己的 OpenAI 兼容提供商。密钥只保存在本机,不出服务器。
|
AI 生图默认走内置 NewAPI(Pollinations + CF Workers AI 两个生图渠道,CF Workers AI 提供商可免费申请、每日有免费额度,见下方说明);也可以切换到自己的 OpenAI 兼容提供商。密钥只保存在本机,不出服务器。
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
@@ -323,6 +364,37 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
|
|||||||
|
|
||||||
{ig.provider === 'newapi' && (
|
{ig.provider === 'newapi' && (
|
||||||
<div className="space-y-3 p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg border border-gray-200 dark:border-gray-700">
|
<div className="space-y-3 p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg border border-gray-200 dark:border-gray-700">
|
||||||
|
{/* CF Workers AI 免费额度 + 申请地址 */}
|
||||||
|
<div className="p-3 rounded-lg bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800">
|
||||||
|
<div className="flex items-center gap-1.5 mb-1">
|
||||||
|
<span className="text-xs font-semibold text-blue-700 dark:text-blue-300">免费生图:Cloudflare Workers AI 提供商</span>
|
||||||
|
<span className="px-1.5 py-0.5 text-[10px] font-medium rounded bg-blue-600 text-white">每日免费额度</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-[11px] leading-relaxed text-blue-600/90 dark:text-blue-300/85">
|
||||||
|
内置通道里的 CF Workers AI 提供商可自行免费申请:Workers 免费计划<strong className="font-medium">无需绑定信用卡</strong>,每天 10000 neurons 免费额度(北京时间每天 08:00 重置),FLUX.1 schnell 约 10 neurons/张,<strong className="font-medium">约合每天 1000 张免费文生图</strong>;DALL·E 3、FLUX 高质量等模型也走该额度。
|
||||||
|
</p>
|
||||||
|
<div className="mt-1.5 flex flex-wrap gap-x-4 gap-y-1 text-[11px]">
|
||||||
|
<a
|
||||||
|
href="https://dash.cloudflare.com/sign-up"
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
className="text-blue-600 dark:text-blue-400 hover:underline font-medium"
|
||||||
|
>
|
||||||
|
① 注册 Cloudflare 账号(免费)→
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
href="https://dash.cloudflare.com/profile/api-tokens"
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
className="text-blue-600 dark:text-blue-400 hover:underline font-medium"
|
||||||
|
>
|
||||||
|
② 创建 API Token(Workers AI Run 权限)→
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
<p className="mt-1 text-[10px] text-blue-500/80 dark:text-blue-400/70">
|
||||||
|
Token 创建时直接选「Workers AI」预设模板即可,过期时间选 No expiration;申请到的 Token 填到下方 API Key 即可免费生图。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">接口地址</label>
|
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">接口地址</label>
|
||||||
<input
|
<input
|
||||||
@@ -343,6 +415,26 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
|
|||||||
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
|
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">默认模型</label>
|
||||||
|
<select
|
||||||
|
value={ig.newapi.model || 'flux-schnell'}
|
||||||
|
onChange={(e) => setIg((v) => ({ ...v, newapi: { ...v.newapi, model: e.target.value } }))}
|
||||||
|
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
|
||||||
|
>
|
||||||
|
{igGroups.map((g) => (
|
||||||
|
<optgroup key={g.key} label={g.label}>
|
||||||
|
{g.models.map((m) => (
|
||||||
|
<option key={m.id} value={m.id}>{m.name}</option>
|
||||||
|
))}
|
||||||
|
</optgroup>
|
||||||
|
))}
|
||||||
|
{!igGroups.length && <option value="flux-schnell">FLUX.1 schnell(快速)</option>}
|
||||||
|
</select>
|
||||||
|
<p className="mt-1 text-[11px] text-gray-400 dark:text-gray-500">
|
||||||
|
AI 生图弹窗使用此模型;选了参考图时后端自动切到 FLUX.2 图生图模型。
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -395,6 +487,92 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{active === 'videoai' && cfg && va && (
|
||||||
|
<div className="space-y-5">
|
||||||
|
<p className="text-xs text-gray-500 dark:text-gray-400">
|
||||||
|
AI 视频用这个模型来写分镜脚本、把提示词/网页/文档内容组织成讲解稿(普通文本模型即可,无需多模态)。
|
||||||
|
配音、字幕与成片合成由服务器本地完成。密钥只保存在本机,不出服务器。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<div className="text-xs font-medium text-gray-600 dark:text-gray-400 mb-2">文本模型来源</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="flex items-start gap-2.5 p-3 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
className="mt-0.5"
|
||||||
|
checked={va.provider === 'inherit'}
|
||||||
|
onChange={() => setVa((v) => ({ ...v, provider: 'inherit' }))}
|
||||||
|
/>
|
||||||
|
<span>
|
||||||
|
<span className="block text-sm font-medium text-gray-900 dark:text-white">复用「AI 生图」配置(推荐)</span>
|
||||||
|
<span className="block text-xs text-gray-500 dark:text-gray-400 mt-0.5">用上面 AI 生图里的地址与 Key,无需重复填写</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
<label className="flex items-start gap-2.5 p-3 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50">
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
className="mt-0.5"
|
||||||
|
checked={va.provider === 'custom'}
|
||||||
|
onChange={() => setVa((v) => ({ ...v, provider: 'custom' }))}
|
||||||
|
/>
|
||||||
|
<span>
|
||||||
|
<span className="block text-sm font-medium text-gray-900 dark:text-white">单独配置提供商 / 模型 / Key</span>
|
||||||
|
<span className="block text-xs text-gray-500 dark:text-gray-400 mt-0.5">任意 OpenAI 兼容 /v1/chat/completions 的文本模型</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{va.provider === 'custom' && (
|
||||||
|
<div className="space-y-3 p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg border border-gray-200 dark:border-gray-700">
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">接口地址(BASE URL)</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={va.custom.url}
|
||||||
|
onChange={(e) => setVa((v) => ({ ...v, custom: { ...v.custom, url: e.target.value } }))}
|
||||||
|
placeholder="https://api.openai.com/v1 或 http://192.168.68.19:3099/v1"
|
||||||
|
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">模型名称</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={va.custom.model}
|
||||||
|
onChange={(e) => setVa((v) => ({ ...v, custom: { ...v.custom, model: e.target.value } }))}
|
||||||
|
placeholder="mimo-v2.6-flash / gpt-4o-mini / qwen-plus ..."
|
||||||
|
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">API Key</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={vaKey}
|
||||||
|
onChange={(e) => setVaKey(e.target.value)}
|
||||||
|
placeholder={va.custom.apiKeyMasked ? `已配置(${va.custom.apiKeyMasked}),留空保持不变` : 'sk-... 或中转站 48 位令牌'}
|
||||||
|
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<button
|
||||||
|
onClick={handleSave}
|
||||||
|
disabled={saving}
|
||||||
|
className="flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg disabled:opacity-50"
|
||||||
|
>
|
||||||
|
<Save className="w-4 h-4" />
|
||||||
|
{saving ? '保存中...' : '保存'}
|
||||||
|
</button>
|
||||||
|
<span className="text-xs text-gray-400 dark:text-gray-500">保存后立即生效,无需重启</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{active === 'about' && (
|
{active === 'about' && (
|
||||||
<div className="space-y-4 text-sm">
|
<div className="space-y-4 text-sm">
|
||||||
<div className="flex items-center justify-between py-2 border-b border-gray-100 dark:border-gray-700">
|
<div className="flex items-center justify-between py-2 border-b border-gray-100 dark:border-gray-700">
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import UndoToast from './UndoToast';
|
|||||||
import FolderSelector from './FolderSelector';
|
import FolderSelector from './FolderSelector';
|
||||||
import ConflictDialog from './ConflictDialog';
|
import ConflictDialog from './ConflictDialog';
|
||||||
import BatchWatermarkModal from './BatchWatermarkModal';
|
import BatchWatermarkModal from './BatchWatermarkModal';
|
||||||
|
import BatchRenameModal from './BatchRenameModal';
|
||||||
import { createLogger } from '../utils/logger';
|
import { createLogger } from '../utils/logger';
|
||||||
|
|
||||||
const logger = createLogger('Sidebar');
|
const logger = createLogger('Sidebar');
|
||||||
@@ -54,6 +55,7 @@ function Sidebar() {
|
|||||||
const [contextMenu, setContextMenu] = useState({ isOpen: false, position: null, folder: null });
|
const [contextMenu, setContextMenu] = useState({ isOpen: false, position: null, folder: null });
|
||||||
// 批量水印弹窗 { mode: 'add'|'remove', folder }
|
// 批量水印弹窗 { mode: 'add'|'remove', folder }
|
||||||
const [batchWatermark, setBatchWatermark] = useState(null);
|
const [batchWatermark, setBatchWatermark] = useState(null);
|
||||||
|
const [batchRename, setBatchRename] = useState(null);
|
||||||
const [undoToast, setUndoToast] = useState({ isVisible: false, message: '', count: 0 });
|
const [undoToast, setUndoToast] = useState({ isVisible: false, message: '', count: 0 });
|
||||||
const [undoHistory, setUndoHistory] = useState([]); // 撤销历史栈,支持多次撤销
|
const [undoHistory, setUndoHistory] = useState([]); // 撤销历史栈,支持多次撤销
|
||||||
const [dragOverFolder, setDragOverFolder] = useState(null); // 拖拽悬停的文件夹
|
const [dragOverFolder, setDragOverFolder] = useState(null); // 拖拽悬停的文件夹
|
||||||
@@ -1513,6 +1515,18 @@ function Sidebar() {
|
|||||||
bumpRefresh(); // 让图片区重新加载(覆盖模式下缩略图已更新)
|
bumpRefresh(); // 让图片区重新加载(覆盖模式下缩略图已更新)
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* 批量重命名弹窗 */}
|
||||||
|
<BatchRenameModal
|
||||||
|
isOpen={!!batchRename}
|
||||||
|
folder={batchRename?.folder}
|
||||||
|
libraryId={currentLibraryId}
|
||||||
|
onClose={() => setBatchRename(null)}
|
||||||
|
onFinished={(result) => {
|
||||||
|
logger.file(`批量重命名完成: ${batchRename?.folder}`, result);
|
||||||
|
bumpRefresh(); // 让图片区重新加载(文件名/路径已更新)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Library Management */}
|
{/* Library Management */}
|
||||||
<div className="p-4 border-b border-gray-200 dark:border-gray-700">
|
<div className="p-4 border-b border-gray-200 dark:border-gray-700">
|
||||||
@@ -1718,7 +1732,7 @@ function Sidebar() {
|
|||||||
<div className="w-5 mr-1" />
|
<div className="w-5 mr-1" />
|
||||||
<Folder className="w-4 h-4 mr-2 text-blue-500 flex-shrink-0" />
|
<Folder className="w-4 h-4 mr-2 text-blue-500 flex-shrink-0" />
|
||||||
<span className="text-sm text-gray-700 dark:text-gray-200 font-medium flex-1">
|
<span className="text-sm text-gray-700 dark:text-gray-200 font-medium flex-1">
|
||||||
全部图片
|
全部
|
||||||
</span>
|
</span>
|
||||||
<span className="text-xs text-gray-500 dark:text-gray-300 ml-2">
|
<span className="text-xs text-gray-500 dark:text-gray-300 ml-2">
|
||||||
{totalImageCount}
|
{totalImageCount}
|
||||||
@@ -1779,6 +1793,10 @@ function Sidebar() {
|
|||||||
menuItems.rename(() => handleStartRenameFolder(contextMenu.folder)),
|
menuItems.rename(() => handleStartRenameFolder(contextMenu.folder)),
|
||||||
menuItems.move(() => handleMoveFolderClick(contextMenu.folder.path)),
|
menuItems.move(() => handleMoveFolderClick(contextMenu.folder.path)),
|
||||||
menuItems.divider(),
|
menuItems.divider(),
|
||||||
|
menuItems.batchRename(() => {
|
||||||
|
setContextMenu({ isOpen: false, position: null, folder: null });
|
||||||
|
setBatchRename({ folder: contextMenu.folder.path });
|
||||||
|
}),
|
||||||
menuItems.batchAddWatermark(() => {
|
menuItems.batchAddWatermark(() => {
|
||||||
setContextMenu({ isOpen: false, position: null, folder: null });
|
setContextMenu({ isOpen: false, position: null, folder: null });
|
||||||
setBatchWatermark({ mode: 'add', folder: contextMenu.folder.path });
|
setBatchWatermark({ mode: 'add', folder: contextMenu.folder.path });
|
||||||
|
|||||||
@@ -6,6 +6,14 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { X, Droplets, Eraser, Type, Scissors, Loader2 } from 'lucide-react';
|
import { X, Droplets, Eraser, Type, Scissors, Loader2 } from 'lucide-react';
|
||||||
import { imageAPI } from '../api';
|
import { imageAPI } from '../api';
|
||||||
|
import { getToken } from '../api/client';
|
||||||
|
|
||||||
|
// 后端错误可能为字符串或 {code,message} 对象,统一取可读文本
|
||||||
|
const errText = (e, fallback) => {
|
||||||
|
if (!e) return fallback;
|
||||||
|
if (typeof e === 'string') return e;
|
||||||
|
return e.message || JSON.stringify(e);
|
||||||
|
};
|
||||||
|
|
||||||
const ACTIONS = [
|
const ACTIONS = [
|
||||||
{ key: 'watermark-add', label: '加水印', icon: Droplets },
|
{ key: 'watermark-add', label: '加水印', icon: Droplets },
|
||||||
@@ -109,11 +117,14 @@ function VideoEditModal({ file, libraryId, onClose, onDone }) {
|
|||||||
try {
|
try {
|
||||||
const res = await fetch('/api/video/edit', {
|
const res = await fetch('/api/video/edit', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Authorization: `Bearer ${getToken()}`
|
||||||
|
},
|
||||||
body: JSON.stringify({ libraryId, path: file.path, action, options, output: outputMode })
|
body: JSON.stringify({ libraryId, path: file.path, action, options, output: outputMode })
|
||||||
});
|
});
|
||||||
const data = await res.json().catch(() => ({}));
|
const data = await res.json().catch(() => ({}));
|
||||||
if (!res.ok || data.error) throw new Error(data.error || `处理失败 (${res.status})`);
|
if (!res.ok || data.error) throw new Error(errText(data.error, `处理失败 (${res.status})`));
|
||||||
onDone && onDone(data.path);
|
onDone && onDone(data.path);
|
||||||
onClose();
|
onClose();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -127,7 +138,7 @@ function VideoEditModal({ file, libraryId, onClose, onDone }) {
|
|||||||
const input = 'w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent';
|
const input = 'w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-50 bg-black bg-opacity-60 flex items-center justify-center p-4" onClick={busy ? undefined : onClose}>
|
<div className="fixed inset-0 z-50 bg-black bg-opacity-60 flex items-center justify-center p-4">
|
||||||
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-3xl max-h-[92vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
|
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-3xl max-h-[92vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
|
||||||
{/* 头部 */}
|
{/* 头部 */}
|
||||||
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 dark:border-gray-700 sticky top-0 bg-white dark:bg-gray-800 z-10">
|
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 dark:border-gray-700 sticky top-0 bg-white dark:bg-gray-800 z-10">
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
/**
|
/**
|
||||||
* AI 生图 · 常用热门提示词库
|
* AI 生图 · 常用热门提示词库
|
||||||
* 分类 + 预设提示词(中英混合,flux 系模型对英文提示词效果更稳)
|
* 分类 + 预设提示词(中英双语)
|
||||||
* 点击条目 = 追加/替换输入框内容
|
* 展示与点击填入均使用中文详细提示词 promptCn(用户要求显示中文);
|
||||||
|
* 发送时后台自动把含中文的提示词翻译成英文(aigen.js translatePromptToEnglish,失败回落原文)
|
||||||
|
* 英文 prompt 字段保留:供对照上游效果,也作为翻译失败时的兜底
|
||||||
|
* 每条均为「主体 + 场景 + 光线 + 构图 + 风格 + 质量」的完整详细描述
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export const PROMPT_CATEGORIES = [
|
export const PROMPT_CATEGORIES = [
|
||||||
@@ -9,88 +12,88 @@ export const PROMPT_CATEGORIES = [
|
|||||||
key: 'hot',
|
key: 'hot',
|
||||||
label: '🔥 热门',
|
label: '🔥 热门',
|
||||||
prompts: [
|
prompts: [
|
||||||
{ name: '赛博朋克城市夜景', prompt: 'cyberpunk city at night, neon lights, rain reflections, flying cars, ultra detailed, cinematic lighting' },
|
{ name: '赛博朋克城市夜景', promptCn: '雨后的赛博朋克城市夜景街道,两侧高楼挂满中文与日文霓虹招牌,湿漉漉的柏油路面倒映五彩灯光,天空中飞行汽车拖出光轨,人群撑着透明雨伞穿行,体积雾弥漫,电影感打光,银翼杀手氛围,超精细,8K,广角镜头', prompt: 'cyberpunk city street at night after rain, towering neon signs in chinese and japanese, colorful reflections on wet asphalt, flying cars leaving light trails in the sky, dense crowd with transparent umbrellas, volumetric fog, cinematic lighting, blade runner mood, ultra detailed, 8k, wide angle' },
|
||||||
{ name: '治愈系猫咪', prompt: 'a fluffy cat sitting on windowsill, warm afternoon sunlight, soft focus, cozy atmosphere, photorealistic' },
|
{ name: '治愈系猫咪', promptCn: '一只毛茸茸的橘猫蜷缩在洒满阳光的窗台上,午后温暖的黄金时刻光线,空气中漂浮着细微尘埃,薄纱窗帘被微风轻轻吹起,旁边有几盆绿植,背景虚化,暖色调,写实摄影,85毫米镜头,浅景深,毛发细节丰富', prompt: 'a fluffy orange cat curled up on a sunlit windowsill, warm golden hour afternoon light, dust particles floating in the air, sheer curtains gently blowing, potted plants nearby, soft focus background, cozy warm tones, photorealistic, 85mm lens, shallow depth of field, highly detailed fur' },
|
||||||
{ name: '水晶球微缩世界', prompt: 'miniature world inside a glass snow globe on wooden table, macro photography, dreamy bokeh, studio lighting' },
|
{ name: '水晶球微缩世界', promptCn: '玻璃雪水晶球里装着一座微缩雪夜村庄,摆在质朴的木桌上,微距摄影,小屋里透出暖黄灯光,梦幻光斑背景,柔和影棚柔光箱打光,飘浮的雪尘闪烁,浅景深,童话温馨氛围,超精细,8K', prompt: 'miniature snowy village inside a glass snow globe on a rustic wooden table, macro photography, tiny warm window lights glowing, dreamy bokeh, soft studio softbox lighting, sparkling snow dust, shallow depth of field, whimsical cozy atmosphere, ultra detailed, 8k' },
|
||||||
{ name: '复古胶片人像', prompt: 'vintage film portrait, kodak portra 400, soft natural light, nostalgic mood, grain texture' },
|
{ name: '复古胶片人像', promptCn: '一位年轻女性的复古胶片人像,柯达 Portra 400 胶片质感,柔和的窗边光线,怀旧暖色调,细腻胶片颗粒,色彩微微褪色,1970 年代穿搭风格,浅浅微笑,浅景深,50 毫米镜头,模拟摄影美学', prompt: 'vintage film portrait of a young woman, kodak portra 400 film look, soft window light, nostalgic warm tones, subtle film grain, slightly faded colors, 1970s styling, gentle smile, shallow depth of field, 50mm lens, analog photography aesthetic' },
|
||||||
{ name: '极简几何壁纸', prompt: 'minimalist geometric wallpaper, pastel gradient colors, clean shapes, flat design, 4k' }
|
{ name: '极简几何壁纸', promptCn: '极简几何壁纸,圆形、三角形与拱形相互交叠,薰衣草紫、蜜桃粉与薄荷绿的柔和渐变,干净的扁平化设计,细腻噪点纹理,均衡的重复构图,现代抽象背景,无文字,4K', prompt: 'minimalist geometric wallpaper with overlapping circles triangles and arches, pastel gradient of lavender peach and mint, clean flat design, subtle noise texture, balanced repeating composition, modern abstract background, no text, 4k' }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'portrait',
|
key: 'portrait',
|
||||||
label: '👤 头像人像',
|
label: '👤 头像人像',
|
||||||
prompts: [
|
prompts: [
|
||||||
{ name: '动漫男头', prompt: 'anime boy avatar, short black hair, hoodie, city background at dusk, detailed illustration, vibrant colors' },
|
{ name: '动漫男头', promptCn: '动漫男生头像,黑色短发微乱,宽松连帽卫衣,背景是黄昏时分的城市天际线,精细插画,鲜艳的夕阳配色,干净的线条,眼神有神,半身构图,日系动漫风格,高质量', prompt: 'anime boy avatar, short messy black hair, oversized hoodie, city skyline at dusk in the background, detailed illustration, vibrant sunset colors, clean lineart, expressive eyes, upper body shot, japanese anime style, high quality' },
|
||||||
{ name: '动漫女头', prompt: 'anime girl avatar, long silver hair, flower crown, soft pastel colors, clean lineart, studio ghibli style' },
|
{ name: '动漫女头', promptCn: '动漫女生头像,银色长发,精致的花环发饰,柔和的马卡龙色调,干净的线条,吉卜力工作室风格,浅浅微笑,梦幻花卉背景,精细插画,肖像构图,佳作级质量', prompt: 'anime girl avatar, long silver hair, delicate flower crown, soft pastel colors, clean lineart, studio ghibli inspired style, gentle smile, dreamy floral background, detailed illustration, portrait framing, masterpiece quality' },
|
||||||
{ name: '3D 卡通头像', prompt: '3D cartoon avatar of a young man, Pixar style, round face, big eyes, soft studio lighting, plain background' },
|
{ name: '3D 卡通头像', promptCn: '年轻男性的 3D 卡通头像,皮克斯风格,圆润友善的脸庞,明亮有神的大眼睛,柔和的影棚打光,纯色渐变背景,光滑的黏土渲染质感,可爱亲切,Octane 渲染,高质量', prompt: '3D cartoon avatar of a young man, pixar style, round friendly face, big sparkling eyes, soft studio lighting, plain gradient background, smooth clay render, cute and approachable, octane render, high quality' },
|
||||||
{ name: '写真级人像', prompt: 'professional headshot portrait, shallow depth of field, natural window light, high detail skin texture, 85mm lens' },
|
{ name: '写真级人像', promptCn: '专业级写真人像特写,浅景深,柔和的自然窗光,皮肤纹理清晰真实,85 毫米 f/1.8 镜头,中性干净的背景,焦点锐利落在眼睛上,商业摄影,轻微调色', prompt: 'professional headshot portrait, shallow depth of field, soft natural window light, high detail skin texture, 85mm f/1.8 lens, neutral clean background, sharp focus on eyes, commercial photography, subtle color grading' },
|
||||||
{ name: '像素风头像', prompt: 'pixel art avatar, 64x64, retro game style, bold outlines, limited palette, cute expression' }
|
{ name: '像素风头像', promptCn: '像素风头像,64x64 网格,复古游戏风格,粗犷干净的描边,限定 16 色调色板,可爱自信的表情,对称构图,怀旧 8-bit 氛围,像素清晰锐利,无抗锯齿', prompt: 'pixel art avatar, 64x64 grid, retro game style, bold clean outlines, limited 16 color palette, cute confident expression, symmetrical composition, nostalgic 8-bit vibe, crisp pixels, no anti-aliasing' }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'wallpaper',
|
key: 'wallpaper',
|
||||||
label: '🖼 壁纸风景',
|
label: '🖼 壁纸风景',
|
||||||
prompts: [
|
prompts: [
|
||||||
{ name: '雪山日出', prompt: 'snow mountain range at sunrise, golden alpenglow, crystal clear lake reflection, ultra wide angle, 8k landscape' },
|
{ name: '雪山日出', promptCn: '日出时分的雪山山脉,金色晨光染亮山峰,清澈见底的高山湖完美倒映雪山,几缕薄雾缭绕,超广角构图,8K 风景摄影,冷蓝阴影渐变为暖金色,天空壮丽', prompt: 'snow mountain range at sunrise, golden alpenglow on the peaks, crystal clear alpine lake perfectly mirroring the mountains, wisps of mist, ultra wide angle, 8k landscape photography, cold blue shadows turning warm gold, dramatic sky' },
|
||||||
{ name: '海上星河', prompt: 'milky way over calm ocean, starry night, long exposure photography, deep blue tones, tranquil scene' },
|
{ name: '海上星河', promptCn: '夜晚银河横跨平静的海面,长曝光摄影,漫天繁星,轻柔的海浪泛着微光,深蓝色调,宁静辽阔的场景,高细节天文摄影,地平线泛着微光', prompt: 'milky way arching over a calm ocean at night, long exposure photography, thousands of stars, gentle glowing waves, deep blue tones, tranquil and vast scene, high detail astrophotography, horizon glow' },
|
||||||
{ name: '梯田晨雾', prompt: 'terraced rice fields with morning mist, layered mountains, traditional chinese landscape painting mood, aerial view' },
|
{ name: '梯田晨雾', promptCn: '清晨被晨雾笼罩的梯田稻田,层层远山在雾中渐隐,无人机航拍视角,中国传统山水画意境,柔和光线,宁静氛围,青绿与灰调,超精细', prompt: 'terraced rice fields at dawn covered in morning mist, layered mountains fading into the distance, aerial drone view, traditional chinese landscape painting mood, soft light, serene atmosphere, green and grey tones, ultra detailed' },
|
||||||
{ name: '梦幻森林', prompt: 'enchanted forest with glowing mushrooms and fireflies, volumetric light rays, fantasy atmosphere, highly detailed' },
|
{ name: '梦幻森林', promptCn: '充满魔力的梦幻森林,发光的蘑菇与飞舞的萤火虫,体积光束穿过树冠洒落,布满苔藓的古树,奇幻氛围,幽蓝与翠绿的魔法光晕,高细节数字艺术', prompt: 'enchanted forest with glowing mushrooms and floating fireflies, volumetric light rays breaking through the canopy, moss covered ancient trees, fantasy atmosphere, magical blue and green glow, highly detailed digital art' },
|
||||||
{ name: '沙漠驼队', prompt: 'camel caravan crossing golden sand dunes at sunset, long shadows, warm tones, national geographic style' }
|
{ name: '沙漠驼队', promptCn: '日落时分穿越金色沙丘的骆驼商队,长长的戏剧性投影,暖橙色调,国家地理风格,辽阔的沙漠地平线,沙丘波纹质感,广角电影感镜头,空气中扬着沙尘', prompt: 'camel caravan crossing golden sand dunes at sunset, long dramatic shadows, warm orange tones, national geographic style, vast desert horizon, rippled sand texture, wide cinematic shot, dusty air' }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'anime',
|
key: 'anime',
|
||||||
label: '✨ 动漫插画',
|
label: '✨ 动漫插画',
|
||||||
prompts: [
|
prompts: [
|
||||||
{ name: '樱花下的少女', prompt: 'anime girl under cherry blossom tree, petals falling, spring breeze, pastel colors, detailed anime illustration' },
|
{ name: '樱花下的少女', promptCn: '樱花树下的动漫少女,粉色花瓣随春风飘散,柔和的马卡龙色调,逆光的花朵,浅浅微笑,温暖的午后光线,精细的日系插画,佳作级质量', prompt: 'anime girl standing under a cherry blossom tree, pink petals drifting in the spring breeze, soft pastel colors, backlit flowers, gentle smile, warm afternoon light, detailed anime illustration, masterpiece quality' },
|
||||||
{ name: '机甲战士', prompt: 'giant mecha robot standing in ruined city, dramatic angle, sci-fi anime style, detailed mechanical parts, dynamic lighting' },
|
{ name: '机甲战士', promptCn: '矗立在废墟城市中的巨型机甲战士,戏剧性的低角度仰拍,科幻动漫风格,精密的机械细节,蒸汽与火花四溅,动态光影,空气中漂浮尘埃,史诗般的体量感,高细节', prompt: 'giant mecha robot standing in a ruined city, dramatic low angle, sci-fi anime style, intricate mechanical parts, steam and sparks, dynamic lighting, floating dust, epic sense of scale, highly detailed' },
|
||||||
{ name: '魔法使', prompt: 'young wizard casting spell, glowing runes, dark library background, fantasy anime illustration, vibrant magic effects' },
|
{ name: '魔法使', promptCn: '年轻魔法师施展发光的咒语,符文悬浮飞舞,背景是幽暗的古老图书馆,奇幻动漫插画,绚丽的魔法特效,轮廓光,闪烁的光粒,动态的施法姿态', prompt: 'young wizard casting a glowing spell, floating arcane runes, dark ancient library background, fantasy anime illustration, vibrant magic effects, rim lighting, sparkling light particles, dynamic pose' },
|
||||||
{ name: '校园日常', prompt: 'anime scene of students walking home at sunset, warm orange sky, slice of life, clean lineart, makoto shinkai style' },
|
{ name: '校园日常', promptCn: '夕阳下放学回家的校园动漫场景,暖橙色天空与高耸的积云,长长的影子铺在路面上,日常系治愈氛围,干净的线条,新海诚风格,精细背景,怀旧感', prompt: 'anime scene of students walking home at sunset, warm orange sky with towering cumulus clouds, long shadows on the road, slice of life mood, clean lineart, makoto shinkai style, detailed background, nostalgic feeling' },
|
||||||
{ name: '和风少女', prompt: 'girl in kimono holding wagashi, traditional japanese room, tatami, soft light, detailed anime art' }
|
{ name: '和风少女', promptCn: '身穿色彩斑斓和服的少女,手捧日式和果子,传统榻榻米房间与障子拉门,柔和的漫射光,精致的布料花纹,优雅恬静,精细的日系插画', prompt: 'girl in a colorful kimono holding japanese wagashi sweet, traditional tatami room with sliding shoji doors, soft diffused light, delicate fabric patterns, elegant and calm, detailed anime art' }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'commerce',
|
key: 'commerce',
|
||||||
label: '🛍 电商海报',
|
label: '🛍 电商海报',
|
||||||
prompts: [
|
prompts: [
|
||||||
{ name: '产品主图', prompt: 'product photography of a perfume bottle on marble pedestal, soft gradient background, studio lighting, luxury feel, high-end commercial shot' },
|
{ name: '产品主图', promptCn: '奢侈品香水瓶置于白色大理石台座上的产品摄影,柔和渐变背景,影棚漫射打光,细腻倒影,优雅高级的商业大片,锐利细节,8K,留出文字排版空间', prompt: 'product photography of a luxury perfume bottle on a white marble pedestal, soft gradient background, diffused studio lighting, subtle reflections, elegant high-end commercial shot, sharp detail, 8k, negative space for text' },
|
||||||
{ name: '美食海报', prompt: 'gourmet burger with melted cheese, steam rising, dark moody background, commercial food photography, appetizing, sharp detail' },
|
{ name: '美食海报', promptCn: '芝士融化的豪华汉堡,芝麻面包,热气升腾,深色氛围背景,戏剧性侧光,商业美食摄影,食材新鲜诱人,锐利细节,浅景深', prompt: 'gourmet burger with melted cheese and sesame bun, steam rising, dark moody background, dramatic side light, commercial food photography, fresh appetizing ingredients, sharp detail, shallow depth of field' },
|
||||||
{ name: '双十一促销', prompt: 'e-commerce sale banner, red and gold color scheme, floating gift boxes and confetti, modern 3d render, festive atmosphere' },
|
{ name: '双十一促销', promptCn: '电商大促海报背景,红金配色,漂浮的礼盒、丝带与五彩纸屑,现代 3D 渲染,喜庆热闹的氛围,高光材质,影棚打光,中央留出标题文案空间', prompt: 'e-commerce sale banner background, red and gold color scheme, floating gift boxes ribbons and confetti, modern 3d render, festive energetic atmosphere, glossy materials, studio lighting, empty center space for headline' },
|
||||||
{ name: '化妆品展示', prompt: 'cosmetic serum bottle surrounded by fresh flowers and water drops, clean white background, fresh and natural, commercial photo' },
|
{ name: '化妆品展示', promptCn: '精华液瓶被鲜花与水珠环绕,干净的白色背景,明亮的自然光,清新自然的氛围,商业产品摄影,细节清晰锐利,柔和阴影', prompt: 'cosmetic serum bottle surrounded by fresh flowers and water droplets, clean white background, bright natural light, fresh and natural mood, commercial product photo, crisp detail, soft shadows' },
|
||||||
{ name: '数码新品', prompt: 'smartphone floating above glowing platform, tech product render, blue and purple neon accents, futuristic commercial style' }
|
{ name: '数码新品', promptCn: '悬浮在发光平台之上的智能手机,科技产品渲染,蓝紫霓虹点缀,深色背景配流光线条,未来感商业风格,倒影锐利,高细节,8K', prompt: 'smartphone floating above a glowing platform, tech product render, blue and purple neon accents, dark background with light streaks, futuristic commercial style, sharp reflections, high detail, 8k' }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'icon3d',
|
key: 'icon3d',
|
||||||
label: '🧊 图标3D',
|
label: '🧊 图标3D',
|
||||||
prompts: [
|
prompts: [
|
||||||
{ name: '3D 立体图标', prompt: '3d icon of a treasure chest, glossy material, soft shadows, pastel gradient background, clay render style, cute and round' },
|
{ name: '3D 立方图标', promptCn: '宝箱造型的 3D 图标,光泽材质,柔和阴影,马卡龙渐变背景,黏土渲染风格,圆润可爱的造型,影棚打光,居中构图,App 图标设计,高质量', prompt: '3d icon of a treasure chest, glossy material, soft shadows, pastel gradient background, clay render style, cute rounded shapes, studio lighting, centered composition, app icon design, high quality' },
|
||||||
{ name: '玻璃质感', prompt: 'glassmorphism 3d icon of cloud storage, translucent frosted glass, floating, soft studio light, clean background' },
|
{ name: '玻璃质感', promptCn: '云存储主题的玻璃拟态 3D 图标,半透明磨砂玻璃质感,悬浮在柔和渐变背景之上,柔和影棚光,细腻的折射与高光,干净极简背景,现代 UI 图标', prompt: 'glassmorphism 3d icon of cloud storage, translucent frosted glass, floating above a soft gradient, soft studio light, subtle refractions and highlights, clean minimal background, modern ui icon' },
|
||||||
{ name: '卡通食物', prompt: 'cute 3d icon of a ramen bowl, kawaii style, thick outlines, vibrant colors, glossy plastic material' },
|
{ name: '卡通食物', promptCn: '拉面碗造型的可爱 3D 图标,卡哇伊风格,粗描边,鲜艳配色,光滑的塑料材质,顶部袅袅升起的蒸汽,柔和的环境光遮蔽,居中 App 图标', prompt: 'cute 3d icon of a ramen bowl, kawaii style, thick outlines, vibrant colors, glossy plastic material, swirling steam on top, soft ambient occlusion, centered app icon' },
|
||||||
{ name: '徽章印章', prompt: '3d golden badge icon with star, metallic material, embossed, dark blue background, premium look' },
|
{ name: '徽章印章', promptCn: '五角星金色徽章 3D 图标,金属材质,浮雕细节,深蓝色背景,高级质感,柔和的轮廓光,居中构图,高质量渲染', prompt: '3d golden badge icon with a star, metallic material, embossed details, dark blue background, premium look, soft rim light, centered composition, high quality render' },
|
||||||
{ emoji: '🎮', name: '游戏手柄', prompt: '3d gamepad icon, retro controller, matte plastic material, playful colors, soft ambient occlusion, icon design' }
|
{ name: '游戏手柄', promptCn: '复古手柄造型的 3D 游戏图标,哑光塑料材质,活泼的配色,柔和的环境光遮蔽,居中放在马卡龙背景上,圆润可爱风格,图标设计', prompt: '3d gamepad icon, retro controller, matte plastic material, playful colors, soft ambient occlusion, centered on pastel background, rounded cute style, icon design' }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'art',
|
key: 'art',
|
||||||
label: '🎨 艺术风格',
|
label: '🎨 艺术风格',
|
||||||
prompts: [
|
prompts: [
|
||||||
{ name: '浮世绘海浪', prompt: 'great wave in ukiyo-e style, hokusai inspired, woodblock print texture, indigo blue palette, traditional japanese art' },
|
{ name: '浮世绘海浪', promptCn: '浮世绘风格的巨浪,葛饰北斋《神奈川冲浪里》意境,木版画质感,靛蓝色调,浪花如爪般飞溅,远处可见富士山,传统日式艺术,纸张纹理可见', prompt: 'great wave cresting in ukiyo-e style, hokusai inspired, woodblock print texture, indigo blue palette, foamy claw-like spray, mount fuji in the distance, traditional japanese art, visible paper grain' },
|
||||||
{ name: '梵高星空', prompt: 'starry night style painting, swirling sky, thick brushstrokes, post-impressionism, oil painting texture' },
|
{ name: '梵高星空', promptCn: '《星月夜》风格的油画,漩涡般翻涌的夜空,明亮的黄色星辰,深色柏树剪影,厚重的颜料笔触,后印象派,油画肌理,浓郁的蓝黄对比', prompt: 'starry night style painting, swirling turbulent sky, glowing yellow stars, dark cypress silhouette, thick impasto brushstrokes, post-impressionism, oil painting texture, vibrant blues and yellows' },
|
||||||
{ name: '水彩花卉', prompt: 'delicate watercolor flowers, loose brushstrokes, soft edges, white background, botanical illustration style' },
|
{ name: '水彩花卉', promptCn: '精致的水彩花卉,笔触松动随意,边缘自然晕染,白色背景,植物图鉴风格,粉绿柔和色调,构图留白通透,手绘纸张纹理', prompt: 'delicate watercolor flowers, loose brushstrokes, soft bleeding edges, white background, botanical illustration style, pastel pink and green palette, airy composition, hand painted paper texture' },
|
||||||
{ name: '低多边形', prompt: 'low poly landscape with pine forest and mountains, faceted geometry, vibrant sunset colors, digital art' },
|
{ name: '低多边形', promptCn: '低多边形风格的风景,松林与雪山,棱面几何结构,日落的橙紫鲜艳配色,干净利落的三角切面,风格化数字艺术', prompt: 'low poly landscape with pine forest and snow mountains, faceted geometry, vibrant sunset colors of orange and purple sky, clean triangles, stylized digital art' },
|
||||||
{ name: '水墨仙鹤', prompt: 'chinese ink wash painting of crane flying over lotus, minimal brush strokes, elegant, rice paper texture' }
|
{ name: '水墨仙鹤', promptCn: '水墨画风格的仙鹤飞过荷塘,笔法简练自信,大量留白意境,宣纸纹理,微妙的墨色浓淡渐变,东方美学神韵', prompt: 'chinese ink wash painting of a crane flying over a lotus pond, minimal confident brush strokes, elegant negative space, rice paper texture, subtle grey ink gradients, oriental aesthetic' }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'scene',
|
key: 'scene',
|
||||||
label: '🏠 室内场景',
|
label: '🏠 室内场景',
|
||||||
prompts: [
|
prompts: [
|
||||||
{ name: '温馨书房', prompt: 'cozy home library with floor to ceiling bookshelves, leather armchair, warm lamp light, rainy window, photorealistic' },
|
{ name: '温馨书房', promptCn: '温馨的家庭书房,顶天立地的书架墙,皮质扶手椅,暖黄台灯光,窗外下着雨挂着水珠,写实摄影,琥珀暖色调,私密安逸的氛围,细节丰富,8K', prompt: 'cozy home library with floor to ceiling bookshelves, leather armchair, warm lamp light, rainy window with droplets, photorealistic, warm amber tones, intimate atmosphere, detailed interior, 8k' },
|
||||||
{ name: '北欧客厅', prompt: 'scandinavian living room, white walls, light wood furniture, large plants, natural daylight, interior design photo' },
|
{ name: '北欧客厅', promptCn: '北欧风客厅,白色墙面,浅色橡木家具,大型绿植,大落地窗透进充足自然光,极简装饰,室内设计摄影,通透明亮,清新色调', prompt: 'scandinavian living room, white walls, light oak furniture, large green plants, big windows with natural daylight, minimal decor, interior design photography, airy and clean, bright tones' },
|
||||||
{ name: '咖啡角落', prompt: 'small cafe corner with espresso machine, pastries display, morning light through glass, hygge atmosphere' },
|
{ name: '咖啡角落', promptCn: '咖啡馆小角落,意式咖啡机与玻璃甜点柜,清晨阳光透过窗户洒入,惬意温暖的氛围,暖色木质调,杯中升起袅袅热气,写实摄影', prompt: 'small cafe corner with an espresso machine and glass pastry display, morning sunlight streaming through the window, hygge atmosphere, warm wood tones, steam rising from a cup, photorealistic' },
|
||||||
{ name: '阁楼卧室', prompt: 'attic bedroom with slanted window, fairy lights, linen bedding, plants, soft morning light, aesthetic photo' },
|
{ name: '阁楼卧室', promptCn: '阁楼卧室,倾斜的天窗,星星串灯,亚麻床品,几盆绿植,柔和的清晨光线,文艺清新的氛围照,低饱和色调,织物质感细腻', prompt: 'attic bedroom with a slanted skylight window, fairy lights, linen bedding, potted plants, soft morning light, aesthetic cozy photo, muted tones, detailed textiles' },
|
||||||
{ name: '赛博房间', prompt: 'futuristic bedroom with holographic screens, neon strip lights, minimalist furniture, cyberpunk interior' }
|
{ name: '赛博房间', promptCn: '未来感卧室,悬浮的全息屏幕,青色与洋红的霓虹灯带,极简家具,赛博朋克室内风格,体积光晕,道具细节丰富,电影感打光', prompt: 'futuristic bedroom with floating holographic screens, neon strip lights in cyan and magenta, minimalist furniture, cyberpunk interior, volumetric glow, detailed props, cinematic lighting' }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ export const useImageStore = create((set, get) => ({
|
|||||||
selectedImage: null,
|
selectedImage: null,
|
||||||
selectedImages: [],
|
selectedImages: [],
|
||||||
totalImageCount: 0,
|
totalImageCount: 0,
|
||||||
|
typeCounts: {}, // 按文件类型计数 { image: 102, video: 181, document: 73 }
|
||||||
totalSize: 0, // 素材库总大小(字节)
|
totalSize: 0, // 素材库总大小(字节)
|
||||||
|
|
||||||
// 文件夹
|
// 文件夹
|
||||||
@@ -113,6 +114,7 @@ export const useImageStore = create((set, get) => ({
|
|||||||
|
|
||||||
// 统计
|
// 统计
|
||||||
setTotalImageCount: (count) => set({ totalImageCount: count }),
|
setTotalImageCount: (count) => set({ totalImageCount: count }),
|
||||||
|
setTypeCounts: (counts) => set({ typeCounts: counts || {} }),
|
||||||
setTotalSize: (size) => set({ totalSize: size }),
|
setTotalSize: (size) => set({ totalSize: size }),
|
||||||
|
|
||||||
// 加载状态
|
// 加载状态
|
||||||
|
|||||||
@@ -22,6 +22,10 @@ export const useUIStore = create((set) => ({
|
|||||||
editingImage: null,
|
editingImage: null,
|
||||||
setEditingImage: (image) => set({ editingImage: image }),
|
setEditingImage: (image) => set({ editingImage: image }),
|
||||||
|
|
||||||
|
// 视频编辑弹窗(打开的视频记录,null=关闭;右侧面板与瀑布流共用)
|
||||||
|
videoEditFile: null,
|
||||||
|
setVideoEditFile: (file) => set({ videoEditFile: file }),
|
||||||
|
|
||||||
// 合拼种子图(多选后点「合拼」带入编辑器,null=无)
|
// 合拼种子图(多选后点「合拼」带入编辑器,null=无)
|
||||||
mergeImages: null,
|
mergeImages: null,
|
||||||
setMergeImages: (images) => set({ mergeImages: images }),
|
setMergeImages: (images) => set({ mergeImages: images }),
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
/**
|
||||||
|
* 文件类型注册表(单一数据源)
|
||||||
|
*
|
||||||
|
* 所有"图片/视频/文档…张/个"文案与图标都从这里取,
|
||||||
|
* 新增文件类型只需在 TABLE 加一行,全站文案与统计卡自动识别。
|
||||||
|
*/
|
||||||
|
import { Image as ImageIcon, Video, FileText, File, Music, PenTool, HelpCircle } from 'lucide-react';
|
||||||
|
|
||||||
|
const TABLE = {
|
||||||
|
image: { label: '图片', unit: '张', icon: ImageIcon },
|
||||||
|
video: { label: '视频', unit: '个', icon: Video },
|
||||||
|
audio: { label: '音频', unit: '个', icon: Music },
|
||||||
|
document: { label: '文档', unit: '个', icon: FileText },
|
||||||
|
design: { label: '设计', unit: '个', icon: PenTool },
|
||||||
|
other: { label: '其他', unit: '个', icon: HelpCircle },
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按注册表顺序返回类型计数条目(图例等排序稳定展示用);
|
||||||
|
* 注册表之外的未知类型键附在末尾。
|
||||||
|
* @param {Object} typeCounts - { image: 102, video: 181 }
|
||||||
|
* @returns {Array<[string, number]>}
|
||||||
|
*/
|
||||||
|
export function orderedTypeEntries(typeCounts) {
|
||||||
|
const c = typeCounts || {};
|
||||||
|
const known = Object.keys(TABLE).filter((k) => (c[k] || 0) > 0).map((k) => [k, c[k]]);
|
||||||
|
const extra = Object.entries(c).filter(([k, n]) => n > 0 && !(k in TABLE));
|
||||||
|
return [...known, ...extra];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 未知类型兜底:一律按"文件" */
|
||||||
|
const FALLBACK = { label: '文件', unit: '个', icon: File };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 单个文件的类型元信息
|
||||||
|
* @param {string} fileType - image | video | document | ...
|
||||||
|
* @returns {{label, unit, icon}}
|
||||||
|
*/
|
||||||
|
export function typeMeta(fileType) {
|
||||||
|
return TABLE[fileType] || FALLBACK;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从条目列表聚合类型计数 { image: 2, video: 1 }
|
||||||
|
* @param {Array<{fileType?: string}>} items
|
||||||
|
*/
|
||||||
|
export function typeCountsOf(items) {
|
||||||
|
const counts = {};
|
||||||
|
for (const it of items || []) {
|
||||||
|
const t = it?.fileType || 'image';
|
||||||
|
counts[t] = (counts[t] || 0) + 1;
|
||||||
|
}
|
||||||
|
return counts;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 集合计数文案(按类型自动识别):
|
||||||
|
* - 单一已知类型:`102 张图片` / `181 个视频`
|
||||||
|
* - 多类型混合、未知类型、或没给计数:`356 个文件`
|
||||||
|
*
|
||||||
|
* @param {number} count - 总数
|
||||||
|
* @param {Object} [typeCounts] - { image: 102, video: 181, document: 73 }
|
||||||
|
*/
|
||||||
|
export function countLabel(count, typeCounts) {
|
||||||
|
const entries = Object.entries(typeCounts || {}).filter(([, n]) => n > 0);
|
||||||
|
if (entries.length === 1) {
|
||||||
|
const { label, unit } = typeMeta(entries[0][0]);
|
||||||
|
return `${count} ${unit}${label}`;
|
||||||
|
}
|
||||||
|
return `${count} 个文件`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 集合的类型名词(用于"复制图片/导出视频"等动词文案):
|
||||||
|
* - 单一类型:'图片' / '视频' / '文档'
|
||||||
|
* - 多类型混合或未知:'文件'
|
||||||
|
*/
|
||||||
|
export function typeLabelOf(typeCounts) {
|
||||||
|
const entries = Object.entries(typeCounts || {}).filter(([, n]) => n > 0);
|
||||||
|
if (entries.length === 1) return typeMeta(entries[0][0]).label;
|
||||||
|
return FALLBACK.label;
|
||||||
|
}
|
||||||
Reference in new issue
Block a user