diff --git a/.gitignore b/.gitignore index cfc3ab1..75ca19f 100644 --- a/.gitignore +++ b/.gitignore @@ -56,3 +56,7 @@ test-library/ # FlyPic 运行时配置(含 JWT 密钥/密码哈希,禁止提交) config/ + +# AI 模型/虚拟环境(体积过大,禁止入库) +ai-models/ +ai/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 98b579f..825a70c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,31 @@ # 更新日志 +## 2026-11-17 → v1.3.0 + +本版本为图片管理能力的大版本:图片编辑器(裁剪/旋转/调色等 PS 常用功能)、批量水印、AI 生图、收藏体系、合拼拼图、图片右上角一键新窗口打开。 + +- ✨ 新功能:**图片编辑器** —— 双击或右键「编辑图片」进入,提供 PS 常用功能: + - **裁剪**:画布拖拽选区 + 四角把手缩放 + 三分线辅助,支持 自由/1:1/4:3/3:2/16:9/9:16 比例锁定,应用时按原图分辨率烘焙并同步平移文字/贴图对象 + - **旋转翻转**:左转 90°、右转 90°、180°、水平/垂直翻转(底图与对象一起做几何变换) + - **图像大小**:按宽度等比缩放(16~12000 px,含超大图像素上限保护) + - **调色**:亮度、对比度、饱和度、色相、模糊五个滑杆实时预览,另有黑白/反色/复古/自动色阶效果与一键还原;保存、裁剪、AI 处理前自动按原分辨率烘焙 + - 文字/贴图图层、撤销重做一并接入 +- ✨ 新功能:**批量水印** —— 右键菜单「批量加水印…/批量去水印…」,弹窗批量处理当前选中图片 +- ✨ 新功能:**AI 生图** —— 设置页可配生图渠道(内置 NewAPI 两大量产模型开箱即用,或切换自己的 OpenAI 兼容 /v1/images/generations 接口:地址/模型/Key),提示词预设库辅助出图 +- ✨ 新功能:**收藏体系** —— 图片左上角星标一键收藏/取消,侧边栏「我的收藏」视图与筛选项,右键菜单同步提供收藏入口 +- ✨ 新功能:**图片右上角「在新窗口打开」** —— 悬停图片右上角出现外链按钮,点击在新标签页打开原图(不打断当前浏览;非图片类型的文件类型标识自动左移让位) +- ✨ 新功能:**合拼拼图**(MergeCollage)与**返回顶部按钮**(BackToTop) +- 🔧 优化:搜索支持 OCR 图内文字多关键词;重新扫描按钮补跑历史图片 OCR 索引 + + +## 2026-11-16 → v1.2.1 + +本版本修复「OCR 文字搜索不到」的根因,并新增「重新扫描」入口。旧版本的 OCR 只在**文件发生变化**时执行,OCR 功能上线前已入库的图片(数千张)文字索引一直为空,导致图内文字永远搜不到。 + +- 🐛 修复:**OCR 文字搜索不到** —— 新增 `ocr_done` 标记列,扫描时对「文件没变但缺少文字索引」的旧记录自动补跑 OCR(识别为空也记为已完成,避免重复识别);新入库/变化的图片在扫描时同步标记已识别 +- ✨ 新功能:**重新扫描按钮** —— 右上角刷新按钮旁新增「重新扫描」图标(移动端同样提供),确认后对当前素材库全量重新索引并补跑 OCR,进度条通过现有 Socket.IO 扫描进度显示,扫描期间按钮自动禁用防重复触发 +- 🔧 后端:`db.js` 新增 `updateOcrResult()` 与 `ocr_done` 列迁移;扫描统计新增 `ocr`(OCR 补扫张数)计数 + ## 2026-11-16 → v1.2.0 本版本在 v1.1.0 基础上补齐「设置 + 授权系统」能力:OCR 可切换线上/本地、右上角开源地址与版本号与通知公告、接入 CardAuth 授权系统做版本推送与在线统计。 diff --git a/Dockerfile b/Dockerfile index aad65d0..4e215b1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,12 +1,12 @@ # ====== Stage 1: 构建前端 ====== -FROM node:22-slim AS frontend-builder +FROM docker.1ms.run/library/node:22-slim AS frontend-builder WORKDIR /app/frontend COPY frontend/ ./ RUN npm install --legacy-peer-deps && npm run build # ====== Stage 2: 安装后端依赖 ====== -FROM node:22-slim AS backend-builder +FROM docker.1ms.run/library/node:22-slim AS backend-builder # 安装编译工具(better-sqlite3 / sharp 需要) RUN sed -i 's|deb.debian.org|mirrors.tuna.tsinghua.edu.cn|g' /etc/apt/sources.list.d/debian.sources 2>/dev/null; \ @@ -21,7 +21,7 @@ COPY backend/package.json ./ RUN npm install --legacy-peer-deps # ====== Stage 3: 运行 ====== -FROM node:22-slim AS runner +FROM docker.1ms.run/library/node:22-slim AS runner WORKDIR /app @@ -33,7 +33,10 @@ RUN sed -i 's|deb.debian.org|mirrors.tuna.tsinghua.edu.cn|g' /etc/apt/sources.li tesseract-ocr \ tesseract-ocr-chi-sim \ tesseract-ocr-eng \ - && rm -rf /var/lib/apt/lists/* + fonts-noto-cjk \ + fontconfig \ + && rm -rf /var/lib/apt/lists/* \ + && fc-cache -f # 复制后端代码和依赖 COPY --from=backend-builder /app/backend/node_modules ./backend/node_modules diff --git a/README.md b/README.md index a993daf..9d82d7c 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,21 @@ - 图片区保持原交互:**单击选中、Ctrl/Shift 多选、双击放大预览**(未改动) +### 8. 重新扫描按钮与 OCR 补扫(v1.2.1 新增) + +- 右上角刷新按钮旁新增**「重新扫描」图标**(移动端同样提供):确认后对当前素材库全量重新索引并补跑 OCR 文字识别,进度条复用现有扫描进度显示,扫描期间按钮自动禁用防重复触发 +- 修复 **OCR 文字搜索不到**:OCR 功能上线前已入库的图片文字索引一直为空,且旧扫描逻辑对"文件没变"的记录永远跳过、不补识别;现在新增 `ocr_done` 标记列,重新扫描时自动为这些旧图片补跑 OCR(识别为空也记为已完成,不会反复重试) +- 扫描统计新增 `ocr`(OCR 补扫张数)计数 + +### 9. 图片编辑器 / 批量水印 / AI 生图 / 收藏(v1.3.0 新增) + +- **图片编辑器**:右键「编辑图片」进入,提供 PS 常用功能 —— **裁剪**(拖拽选区 + 四角把手 + 三分线,自由/1:1/4:3/3:2/16:9/9:16 比例锁定,按原图分辨率烘焙)、**旋转翻转**(左右 90°/180°/水平/垂直)、**图像大小**(等比缩放 16~12000 px)、**调色**(亮度/对比度/饱和度/色相/模糊滑杆实时预览 + 黑白/反色/复古/自动色阶 + 一键还原),文字与贴图图层随裁剪/旋转同步变换,保存前自动按原分辨率烘焙 +- **批量水印**:右键菜单「批量加水印…/批量去水印…」,弹窗对选中图片批量处理 +- **AI 生图**:设置页「AI 生图设置」可配生图渠道 —— 默认走内置 NewAPI(Pollinations / Cloudflare Workers AI 两大量产模型开箱即用),也可切换到自己的 OpenAI 兼容 `/v1/images/generations` 接口(地址/模型/Key),并提供提示词预设库 +- **收藏体系**:图片**左上角星标**一键收藏/取消,侧边栏「我的收藏」视图 + Header 筛选项,右键菜单同步提供收藏入口 +- **图片右上角「在新窗口打开」**:悬停图片右上角出现外链按钮,点击在**新标签页打开原图**,不打断当前浏览(非图片类型的文件类型标识自动左移让位) +- **合拼拼图**与**返回顶部按钮** + ## 🚀 部署方式 ### 方式一:Docker Compose(推荐) @@ -120,7 +135,7 @@ docker run -d --name flypic --restart unless-stopped \ ## 📝 使用注意 -- **添加/更新素材库后需重新扫描**,图片内 OCR 文字才可被搜索到(旧索引无文字数据) +- **添加/更新素材库后需重新扫描**,图片内 OCR 文字才可被搜索到(旧索引无文字数据)——点击右上角**「重新扫描」图标**即可,扫描时会自动补齐历史图片的 OCR 文字索引 - 素材库全量 OCR 扫描逐张识别、耗时较长,建议在不用的时候执行 - 数据存储:素材目录下 `.flypic/`(缩略图 + SQLite 索引,含 `ocr_text` 列);应用配置在 `config/`(已 gitignore) - 删除素材目录下的 `.flypic` 即可清除该库索引,重新扫描重建 diff --git a/backend/database/db.js b/backend/database/db.js index 040c1aa..693cb27 100644 --- a/backend/database/db.js +++ b/backend/database/db.js @@ -97,6 +97,13 @@ class LibraryDatabase { // 列已存在,忽略错误 } + // 添加 ocr_done 列(如果不存在):1=已尝试过 OCR(含识别为空的结果),0=待补扫 + try { + this.db.exec(`ALTER TABLE images ADD COLUMN ocr_done INTEGER DEFAULT 0`); + } catch (e) { + // 列已存在,忽略错误 + } + // Folders table this.db.exec(` CREATE TABLE IF NOT EXISTS folders ( @@ -177,8 +184,8 @@ class LibraryDatabase { insertImage(imageData) { const stmt = this.db.prepare(` INSERT OR REPLACE INTO images - (path, filename, folder, size, width, height, format, file_type, created_at, modified_at, file_hash, thumbnail_path, thumbnail_size, indexed_at, ocr_text) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + (path, filename, folder, size, width, height, format, file_type, created_at, modified_at, file_hash, thumbnail_path, thumbnail_size, indexed_at, ocr_text, ocr_done) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `); const result = stmt.run( imageData.path, @@ -195,13 +202,27 @@ class LibraryDatabase { imageData.thumbnail_path, imageData.thumbnail_size, Date.now(), - imageData.ocr_text || '' + imageData.ocr_text || '', + imageData.ocr_done !== undefined ? imageData.ocr_done : 0 ); // 更新数据库修改时间 this.updateLastModified(); return result; } + /** + * 更新单张图片的 OCR 结果并标记已识别(ocr_done=1) + * 供扫描时对"文件未变化但缺少文字索引"的旧记录补扫使用 + */ + updateOcrResult(imagePath, text) { + const stmt = this.db.prepare( + 'UPDATE images SET ocr_text = ?, ocr_done = 1 WHERE path = ?' + ); + const result = stmt.run(text || '', imagePath); + this.updateLastModified(); + return result; + } + getImageByPath(imagePath) { const stmt = this.db.prepare('SELECT * FROM images WHERE path = ?'); return stmt.get(imagePath); diff --git a/backend/src/app.js b/backend/src/app.js index 5f8c0f2..a50bdec 100644 --- a/backend/src/app.js +++ b/backend/src/app.js @@ -85,6 +85,9 @@ function createApp(dependencies) { const uploadRouter = require('./routes/upload'); const settingsRouter = require('./routes/settings'); const hubRouter = require('./routes/hub'); + const editRouter = require('./routes/edit'); + const batchRouter = require('./routes/batch'); + const aigenRouter = require('./routes/aigen'); app.use('/api/auth', authRouter); app.use('/api/library', libraryRouter); @@ -94,6 +97,9 @@ function createApp(dependencies) { app.use('/api/upload', uploadRouter); app.use('/api/settings', settingsRouter); app.use('/api/hub', hubRouter); + app.use('/api/edit', editRouter); + app.use('/api/batch', batchRouter); + app.use('/api/aigen', aigenRouter); // 健康检查 app.get('/api/health', (req, res) => { diff --git a/backend/src/models/ImageModel.js b/backend/src/models/ImageModel.js index 2bdb4bb..0fcdeed 100644 --- a/backend/src/models/ImageModel.js +++ b/backend/src/models/ImageModel.js @@ -207,6 +207,12 @@ class ImageModel extends BaseModel { params.push(filters.endDate); } + // 收藏过滤(左侧「我的收藏」菜单) + if (filters.favorite !== undefined && filters.favorite !== null && filters.favorite !== '') { + query += ' AND favorite = ?'; + params.push(Number(filters.favorite) ? 1 : 0); + } + // 排序 query += ' ORDER BY created_at DESC'; diff --git a/backend/src/routes/aigen.js b/backend/src/routes/aigen.js new file mode 100644 index 0000000..7af5ffc --- /dev/null +++ b/backend/src/routes/aigen.js @@ -0,0 +1,235 @@ +/** + * AI 生图路由 + * - 内置渠道:NewAPI(Pollinations + CF Workers AI,OpenAI 兼容 /v1/images/generations) + * - 自定义渠道:用户在设置里填的提供商(url + apiKey + model,OpenAI 兼容) + * - GET /api/aigen/models 内置模型分组 + 当前配置(apiKey 掩码) + * - POST /api/aigen/generate 生成图片,返回 base64(key 不出后端) + */ + +const express = require('express'); +const router = express.Router(); +const { asyncHandler } = require('../middleware/errorHandler'); +const logger = require('../utils/logger'); +const { getSettings } = require('../../utils/settings'); + +// 内置模型分组(NewAPI 两个生图渠道) +const BUILTIN_GROUPS = [ + { + key: 'cf', + label: 'CF Workers AI', + models: [ + { id: 'flux-schnell', name: 'FLUX-schnell(快速)' }, + { id: 'flux', name: 'FLUX(高质量)' }, + { id: 'dall-e-3', name: 'DALL·E 3' } + ] + }, + { + key: 'pollinations', + label: 'Pollinations', + models: [ + { id: 'pollinations-flux', name: 'Pollinations FLUX(高清)' }, + { id: 'pollinations-turbo', name: 'Pollinations Turbo(极速)' }, + { id: 'pollinations-flux-anime', name: 'Pollinations 动漫' }, + { id: 'pollinations-sana', name: 'Pollinations Sana(轻量)' }, + { id: 'pollinations-any-dark', name: 'Pollinations 暗黑风' } + ] + } +]; + +const ALLOWED_SIZES = ['1024x1024', '1280x720', '720x1280', '1536x1024', '1024x1536']; + +/** 归一化基础地址 -> 完整 images/generations URL */ +function normalizeGenUrl(url) { + let u = String(url || '').trim().replace(/\/+$/, ''); + if (/\/images\/generations$/.test(u)) return u; + if (/\/v1$/.test(u)) return u + '/images/generations'; + if (/\/chat\/completions$/.test(u)) return u.replace(/\/chat\/completions$/, '/images/generations'); + return u + '/v1/images/generations'; +} + +function maskKey(key) { + if (!key) return ''; + if (key.length <= 8) return '****'; + return key.slice(0, 4) + '****' + key.slice(-4); +} + +/** 取当前生效的提供商配置 */ +function resolveProvider(settings) { + const ig = settings.imagegen || {}; + if (ig.provider === 'custom' && ig.custom && ig.custom.url) { + return { + provider: 'custom', + url: ig.custom.url, + apiKey: ig.custom.apiKey || '', + model: ig.custom.model || '', + label: '自定义提供商' + }; + } + return { + provider: 'newapi', + url: (ig.newapi && ig.newapi.url) || 'http://192.168.68.19:3099/v1', + // 内置 key 优先取设置里填的,其次取服务器环境变量 + apiKey: (ig.newapi && ig.newapi.apiKey) || process.env.NEWAPI_KEY || '', + model: '', + label: 'NewAPI(Pollinations + CF Workers AI)' + }; +} + +/** + * GET /api/aigen/models + * 返回内置模型分组 + 当前生效配置(掩码) + */ +router.get('/models', asyncHandler(async (req, res) => { + const settings = getSettings(); + const cur = resolveProvider(settings); + + res.json({ + success: true, + data: { + groups: BUILTIN_GROUPS, + sizes: ALLOWED_SIZES, + provider: { + type: cur.provider, + label: cur.label, + url: cur.url, + apiKeyMasked: maskKey(cur.apiKey), + hasKey: !!cur.apiKey, + customModel: (settings.imagegen && settings.imagegen.custom && settings.imagegen.custom.model) || '', + customUrl: (settings.imagegen && settings.imagegen.custom && settings.imagegen.custom.url) || '' + } + } + }); +})); + +/** + * POST /api/aigen/generate + * body: { prompt, model?, size?, provider? } + * provider: 'builtin'(按模型自动走 NewAPI)| 'custom'(用设置里的自定义提供商) + * 返回 { images: [{ b64 }], revisedPrompt?, ms } + */ +router.post('/generate', asyncHandler(async (req, res) => { + const t0 = Date.now(); + const { prompt, model, size, provider } = req.body || {}; + + if (!prompt || !String(prompt).trim()) { + return res.status(400).json({ success: false, error: '提示词不能为空' }); + } + + const settings = getSettings(); + const cur = resolveProvider(settings); + + // 自定义提供商模式:模型用设置里填的 + const useCustom = provider === 'custom' || (provider !== 'builtin' && cur.provider === 'custom'); + let effUrl = cur.url; + let effKey = cur.apiKey; + let effModel = model; + + if (useCustom) { + if (!cur.url || cur.provider !== 'custom') { + return res.status(400).json({ success: false, error: '未配置自定义提供商,请先到设置 → AI 生图填写' }); + } + if (!cur.model && !model) { + return res.status(400).json({ success: false, error: '自定义提供商未填写模型名' }); + } + effModel = model || cur.model; + } else { + if (!effKey) { + return res.status(400).json({ success: false, error: '未配置 NewAPI Key,请到设置 → AI 生图填写' }); + } + if (!effModel) effModel = 'flux-schnell'; + } + + 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)}`); + + const ctrl = new AbortController(); + const timer = setTimeout(() => ctrl.abort(), 150000); // 生图最长 150s + let result; + try { + const resp = await fetch(genUrl, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${effKey}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + model: effModel, + prompt: String(prompt), + n: 1, + size: effSize + }), + signal: ctrl.signal + }); + const text = await resp.text(); + if (!resp.ok) { + logger.error(`[aigen] upstream ${resp.status}: ${text.slice(0, 300)}`); + let msg = `生图接口返回 ${resp.status}`; + try { + const j = JSON.parse(text); + if (j.error && j.error.message) msg = j.error.message; + else if (j.message) msg = j.message; + } catch (e) { /* 保留默认信息 */ } + return res.status(502).json({ success: false, error: msg }); + } + result = JSON.parse(text); + } catch (e) { + const aborted = e.name === 'AbortError'; + logger.error(`[aigen] fetch error: ${e.message}`); + return res.status(502).json({ + success: false, + error: aborted ? '生图超时(超过 150 秒)' : `生图请求失败: ${e.message}` + }); + } finally { + clearTimeout(timer); + } + + // 按魔数探测真实格式(上游可能返回 JPEG/PNG/WEBP,扩展名不能瞎写) + function sniffExt(buf) { + if (buf[0] === 0xFF && buf[1] === 0xD8 && buf[2] === 0xFF) return 'jpg'; + if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4E && buf[3] === 0x47) return 'png'; + if (buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46) return 'webp'; + return 'png'; + } + + const list = result.data || []; + const images = []; + for (const item of list) { + if (item.b64_json) { + const buf = Buffer.from(item.b64_json, 'base64'); + images.push({ b64: item.b64_json, ext: sniffExt(buf) }); + } else if (item.url) { + // 上游返回 URL:服务端拉回来转 base64,避免浏览器 CORS + try { + const r = await fetch(item.url, { signal: AbortSignal.timeout(60000) }); + if (r.ok) { + const buf = Buffer.from(await r.arrayBuffer()); + images.push({ b64: buf.toString('base64'), ext: sniffExt(buf) }); + } else { + images.push({ url: item.url }); + } + } catch (e) { + images.push({ url: item.url }); + } + } + } + + if (images.length === 0) { + return res.status(502).json({ success: false, error: '生图成功但未返回图片数据' }); + } + + res.json({ + success: true, + data: { + images, + ext: images[0] && images[0].ext || 'png', + revisedPrompt: result.data && result.data[0] && result.data[0].revised_prompt, + model: effModel, + size: effSize, + ms: Date.now() - t0 + } + }); +})); + +module.exports = router; diff --git a/backend/src/routes/batch.js b/backend/src/routes/batch.js new file mode 100644 index 0000000..29b5ff3 --- /dev/null +++ b/backend/src/routes/batch.js @@ -0,0 +1,403 @@ +/** + * 文件夹批量水印路由 + * - POST /api/batch/start 启动批量任务(加水印 / 去水印),返回 taskId 立即返回 + * - GET /api/batch/status/:id 查询任务进度 + * - POST /api/batch/cancel/:id 取消任务 + * + * 加水印:sharp 合成 SVG 文字水印(九宫格 / 平铺、透明度、旋转、字号按图宽百分比) + * 去水印:按百分比矩形区域生成 mask → 调 flypic-ai sidecar 的 LaMa /inpaint + */ + +const express = require('express'); +const router = express.Router(); +const path = require('path'); +const fs = require('fs'); +const sharp = require('sharp'); +const { asyncHandler, ValidationError, NotFoundError } = require('../middleware/errorHandler'); +const { processImage } = require('../../utils/scanner'); +const ImageModel = require('../models/ImageModel'); +const logger = require('../utils/logger'); + +const AI_BASE = process.env.AI_BASE_URL || 'http://127.0.0.1:15003'; + +const IMAGE_EXTS = new Set(['.jpg', '.jpeg', '.png', '.webp']); +const SHARP_FMT = { '.jpg': 'jpeg', '.jpeg': 'jpeg', '.png': 'png', '.webp': 'webp' }; + +// ---------- 任务表(内存) ---------- +const tasks = new Map(); +let taskSeq = 0; + +function newTask(type, payload) { + const id = `bt_${Date.now()}_${++taskSeq}`; + const task = { + id, + type, // 'add' | 'remove' + status: 'running', // running | done | cancelled | error + total: 0, + done: 0, + failed: 0, + skipped: 0, + current: '', + errors: [], + cancelled: false, + startedAt: Date.now(), + finishedAt: null, + payload + }; + tasks.set(id, task); + return task; +} + +// 完成的任务 30 分钟后清理 +setInterval(() => { + const cutoff = Date.now() - 30 * 60 * 1000; + for (const [id, t] of tasks) { + if (t.finishedAt && t.finishedAt < cutoff) tasks.delete(id); + } +}, 60 * 1000).unref(); + +// ---------- 工具 ---------- + +/** 按百分比区域生成 mask(白色=待修复)→ 渲染为 PNG(PIL 不认 SVG) */ +async function makeMaskBuffer(width, height, region) { + const x = Math.max(0, Math.round((width * region.x) / 100)); + const y = Math.max(0, Math.round((height * region.y) / 100)); + const w = Math.max(1, Math.min(width - x, Math.round((width * region.w) / 100))); + const h = Math.max(1, Math.min(height - y, Math.round((height * region.h) / 100))); + const svg = `` + + `` + + ``; + return sharp(Buffer.from(svg)).png().toBuffer(); +} + +/** 生成文字水印 SVG(支持九宫格单个 / 平铺) */ +function makeWatermarkSvg(width, height, opts) { + const text = String(opts.text || '').trim(); + const fontSize = Math.max(8, Math.round((width * (opts.fontSizePct || 4)) / 100)); + const opacity = Math.max(0, Math.min(100, opts.opacity ?? 50)) / 100; + const color = opts.color || '#ffffff'; + const margin = Math.round((width * (opts.marginPct ?? 2)) / 100); + const stroke = opts.stroke ? ` stroke="#000000" stroke-opacity="${opacity * 0.5}" stroke-width="${Math.max(1, fontSize / 14)}"` : ''; + const fill = color.startsWith('#') + ? (color.length === 4 || color.length === 7 ? color : '#ffffff') + : color; + const escape = (s) => s.replace(/&/g, '&').replace(//g, '>') + .replace(/"/g, '"').replace(/'/g, '''); + const esc = escape(text); + + const font = "font-family=\"Noto Sans CJK SC, Noto Sans SC, WenQuanYi Zen Hei, sans-serif\""; + const items = []; + + if (opts.tile) { + // 平铺:按角度旋转整块排布 + const rotate = Number(opts.rotate ?? -30); + const gapX = fontSize * 8; + const gapY = fontSize * 5; + let row = 0; + for (let y = -height; y < height * 2; y += gapY) { + const offset = row % 2 === 0 ? 0 : gapX / 2; + for (let x = -width; x < width * 2; x += gapX) { + items.push( + `${esc}` + ); + } + row++; + } + const cx = width / 2; + const cy = height / 2; + return `` + + `${items.join('')}`; + } + + // 单个水印:九宫格定位 + const pos = opts.position || 'bottom-right'; + const [va, ha] = pos.split('-'); + const rotate = Number(opts.rotate || 0); + + let x, y, anchor; + if (ha === 'left') { x = margin; anchor = 'start'; } + else if (ha === 'right') { x = width - margin; anchor = 'end'; } + else { x = width / 2; anchor = 'middle'; } + + if (va === 'top') y = margin + fontSize; + else if (va === 'middle') y = height / 2; + else y = height - margin; + + const transform = rotate ? ` transform="rotate(${rotate} ${x} ${y})"` : ''; + items.push( + `${esc}` + ); + return `` + + items.join('') + ``; +} + +/** 结果 buffer 按原格式落盘(覆盖原图或另存) */ +async function writeResult(absPath, pngBuffer, opts = {}) { + const ext = path.extname(absPath).toLowerCase(); + const fmt = SHARP_FMT[ext]; + if (!fmt) throw new Error(`不支持的格式: ${ext}`); + + let target = absPath; + if (opts.mode === 'new') { + const base = absPath.slice(0, absPath.length - ext.length); + const suffix = opts.suffix || '_wm'; + target = `${base}${suffix}${ext}`; + let n = 1; + while (fs.existsSync(target)) { + target = `${base}${suffix}${n}${ext}`; + n++; + } + } + + const pipeline = sharp(pngBuffer); + if (fmt === 'jpeg') await pipeline.jpeg({ quality: 92 }).toFile(target); + else if (fmt === 'webp') await pipeline.webp({ quality: 92 }).toFile(target); + else await pipeline.png().toFile(target); + return target; +} + +/** 串行并发池 */ +async function runPool(items, concurrency, worker) { + let idx = 0; + const runners = Array.from({ length: Math.max(1, Math.min(concurrency, items.length)) }, async () => { + for (;;) { + const i = idx++; + if (i >= items.length) break; + await worker(items[i], i); + } + }); + await Promise.all(runners); +} + +/** 调 sidecar 去水印 */ +async function callInpaint(imageBuffer, maskBuffer) { + const form = new FormData(); + form.append('image', new Blob([imageBuffer], { type: 'image/png' }), 'image.png'); + form.append('mask', new Blob([maskBuffer], { type: 'image/png' }), 'mask.png'); + const resp = await fetch(`${AI_BASE}/inpaint`, { + method: 'POST', + body: form, + signal: AbortSignal.timeout(300 * 1000) + }); + if (!resp.ok) { + let msg = `AI 服务错误 (${resp.status})`; + try { + const j = await resp.json(); + msg = j.detail || j.error || msg; + } catch (_) { /* 非 JSON */ } + throw new Error(msg); + } + return Buffer.from(await resp.arrayBuffer()); +} + +/** 收集文件夹内图片(含子文件夹) */ +function collectImages(req, libraryId, folder) { + const configManager = req.app.get('configManager'); + const dbPool = req.app.get('dbPool'); + if (!configManager || !dbPool) throw new ValidationError('服务未初始化'); + + const config = configManager.load(); + const library = config.libraries.find((l) => String(l.id) === String(libraryId)); + if (!library) throw new NotFoundError('Library', libraryId); + + const db = dbPool.acquire(library.path); + try { + const model = new ImageModel(db.db); + const { images } = model.search({ folder }, null); + return { library, images }; + } finally { + dbPool.release(library.path); + } +} + +/** 每张图处理完后重建缩略图并更新 DB(每张独立 acquire,避免长占连接) */ +async function reindex(req, libraryPath, absPath) { + const dbPool = req.app.get('dbPool'); + const db = dbPool.acquire(libraryPath); + try { + await processImage(absPath, libraryPath, db); + } finally { + dbPool.release(libraryPath); + } +} + +// ---------- 任务执行 ---------- + +async function runAddWatermark(req, task) { + const { library, images } = collectImages(req, task.payload.libraryId, task.payload.folder); + const opts = task.payload.options; + const outMode = task.payload.output === 'new' ? 'new' : 'overwrite'; + task.total = images.length; + + const targets = []; + for (const img of images) { + const abs = path.join(library.path, img.path); + const ext = path.extname(abs).toLowerCase(); + if (!IMAGE_EXTS.has(ext) || !fs.existsSync(abs)) { + task.skipped++; + continue; + } + targets.push({ img, abs, ext }); + } + task.total = targets.length + task.skipped; + + await runPool(targets, 3, async ({ img, abs, ext }) => { + if (task.cancelled) return; + task.current = img.path; + try { + const base = sharp(abs); + const meta = await base.metadata(); + const w = meta.width || 1024; + const h = meta.height || 1024; + const svg = makeWatermarkSvg(w, h, opts); + let out = await base.rotate().composite([{ input: Buffer.from(svg), top: 0, left: 0 }]).png().toBuffer(); + + // rotate() 可能改变尺寸(EXIF),重取 + const m2 = await sharp(out).metadata(); + if (m2.width !== w || m2.height !== h) { + const svg2 = makeWatermarkSvg(m2.width, m2.height, opts); + out = await sharp(out).composite([{ input: Buffer.from(svg2), top: 0, left: 0 }]).png().toBuffer(); + } + + await writeResult(abs, out, { mode: outMode, suffix: '_wm' }); + await reindex(req, library.path, abs); + 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}`); + } + }); +} + +async function runRemoveWatermark(req, task) { + const { library, images } = collectImages(req, task.payload.libraryId, task.payload.folder); + const region = task.payload.options.region; + const outMode = task.payload.output === 'new' ? 'new' : 'overwrite'; + task.total = images.length; + + const targets = []; + for (const img of images) { + const abs = path.join(library.path, img.path); + const ext = path.extname(abs).toLowerCase(); + if (!IMAGE_EXTS.has(ext) || !fs.existsSync(abs)) { + task.skipped++; + continue; + } + targets.push({ img, abs, ext }); + } + task.total = targets.length + task.skipped; + + // LaMa CPU 推理较慢且 sidecar 为单模型,串行处理 + await runPool(targets, 1, async ({ img, abs }) => { + if (task.cancelled) return; + task.current = img.path; + try { + const srcBuf = fs.readFileSync(abs); + const meta = await sharp(srcBuf).metadata(); + const w = meta.width || 1024; + const h = meta.height || 1024; + const mask = await makeMaskBuffer(w, h, region); + const result = await callInpaint(srcBuf, mask); + await writeResult(abs, result, { mode: outMode, suffix: '_nowm' }); + await reindex(req, library.path, abs); + 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}`); + } + }); +} + +// ---------- 路由 ---------- + +/** + * POST /api/batch/start + * body: { libraryId, folder, type: 'add'|'remove', output?: 'overwrite'|'new', options } + * add options: { text, tile?, position?, fontSizePct?, opacity?, color?, marginPct?, rotate?, stroke? } + * remove options: { region: { x, y, w, h } // 图片宽高的百分比 } + */ +router.post( + '/start', + asyncHandler(async (req, res) => { + const { libraryId, folder, type, output, options } = req.body || {}; + if (!libraryId || !folder) throw new ValidationError('缺少 libraryId 或 folder'); + if (type !== 'add' && type !== 'remove') throw new ValidationError('type 必须是 add 或 remove'); + + if (type === 'add') { + if (!options || !String(options.text || '').trim()) throw new ValidationError('水印文字不能为空'); + } else { + const r = options && options.region; + if (!r || [r.x, r.y, r.w, r.h].some((v) => typeof v !== 'number' || v < 0)) { + throw new ValidationError('缺少水印区域 region {x,y,w,h}(百分比)'); + } + if (r.w <= 0 || r.h <= 0) throw new ValidationError('水印区域宽高必须大于 0'); + } + + const { images } = collectImages(req, libraryId, folder); + if (images.length === 0) throw new ValidationError('该文件夹下没有图片'); + + const task = newTask(type, { libraryId, folder, output, options }); + task.total = images.length; + logger.info(`▶️ 批量${type === 'add' ? '加水印' : '去水印'}启动: ${folder} (${images.length} 张)`); + + // 立即返回,后台执行 + const runner = type === 'add' ? runAddWatermark : runRemoveWatermark; + runner(req, task) + .then(() => { + task.status = task.cancelled ? 'cancelled' : 'done'; + }) + .catch((err) => { + task.status = 'error'; + task.errors.push({ path: '', error: err.message }); + logger.error(`❌ 批量任务异常: ${err.message}`); + }) + .finally(() => { + task.current = ''; + task.finishedAt = Date.now(); + }); + + res.json({ taskId: task.id, total: images.length }); + }) +); + +/** GET /api/batch/status/:id */ +router.get( + '/status/:id', + asyncHandler(async (req, res) => { + const task = tasks.get(req.params.id); + if (!task) throw new NotFoundError('Task', req.params.id); + res.json({ + id: task.id, + type: task.type, + status: task.status, + total: task.total, + done: task.done, + failed: task.failed, + skipped: task.skipped, + current: task.current, + errors: task.errors, + startedAt: task.startedAt, + finishedAt: task.finishedAt + }); + }) +); + +/** POST /api/batch/cancel/:id */ +router.post( + '/cancel/:id', + asyncHandler(async (req, res) => { + const task = tasks.get(req.params.id); + if (!task) throw new NotFoundError('Task', req.params.id); + if (task.status === 'running') { + task.cancelled = true; + task.status = 'cancelled'; + } + res.json({ ok: true, status: task.status }); + }) +); + +module.exports = router; diff --git a/backend/src/routes/edit.js b/backend/src/routes/edit.js new file mode 100644 index 0000000..9321795 --- /dev/null +++ b/backend/src/routes/edit.js @@ -0,0 +1,368 @@ +/** + * 图片编辑路由 + * - POST /api/edit/ai 代理 AI 请求到 flypic-ai sidecar(抠图/高清/去水印/换脸) + * - POST /api/edit/save 保存编辑结果(覆盖原图 / 另存为新图),重建缩略图并更新数据库 + */ + +const express = require('express'); +const router = express.Router(); +const path = require('path'); +const fs = require('fs'); +const multer = require('multer'); +const sharp = require('sharp'); +const { asyncHandler } = require('../middleware/errorHandler'); +const { processImage } = require('../../utils/scanner'); +const { getSettings } = require('../../utils/settings'); +const { normalizeOnlineUrl } = require('../../utils/ocr'); +const { mapImageForFrontend } = require('../utils/fieldMapper'); +const logger = require('../utils/logger'); + +const upload = multer({ + storage: multer.memoryStorage(), + limits: { fileSize: 200 * 1024 * 1024 } // 200MB(8K 编辑结果可能较大) +}); + +const AI_BASE = process.env.AI_BASE_URL || 'http://127.0.0.1:15003'; + +// sidecar 端点映射 +const AI_ENDPOINTS = { + upscale: '/upscale', + removebg: '/remove-bg', + inpaint: '/inpaint', + faceswap: '/face-swap' +}; + +/** + * POST /api/edit/ai + * FormData: action=upscale|removebg|inpaint|faceswap, image=file, [mask|source=file], [mode|scale|bg_color] + * 返回:image/png 二进制 或 { error } + */ +router.post( + '/ai', + upload.any(), + asyncHandler(async (req, res) => { + const { action } = req.body; + const endpoint = AI_ENDPOINTS[action]; + if (!endpoint) { + return res.status(400).json({ error: `未知 AI 操作: ${action}` }); + } + if (!req.files || req.files.length === 0) { + return res.status(400).json({ error: '缺少图片文件' }); + } + + // 组装转发表单 + const form = new FormData(); + for (const f of req.files) { + form.append(f.fieldname, new Blob([f.buffer], { type: f.mimetype || 'image/png' }), f.filename || 'image.png'); + } + for (const [k, v] of Object.entries(req.body)) { + if (k !== 'action' && v !== undefined && v !== null) form.append(k, String(v)); + } + + try { + const upstream = await fetch(`${AI_BASE}${endpoint}`, { + method: 'POST', + body: form, + signal: AbortSignal.timeout(300 * 1000) // AI 处理最长 5 分钟 + }); + + const contentType = upstream.headers.get('content-type') || ''; + if (!upstream.ok) { + let msg = `AI 服务错误 (${upstream.status})`; + try { + const j = await upstream.json(); + msg = j.detail || j.error || msg; + } catch (_) { + /* 非 JSON 错误体 */ + } + logger.warn(`⚠️ AI ${action} 失败: ${msg}`); + return res.status(502).json({ error: msg }); + } + + if (contentType.includes('application/json')) { + const j = await upstream.json(); + return res.status(502).json({ error: j.detail || j.error || 'AI 服务返回异常' }); + } + + const buf = Buffer.from(await upstream.arrayBuffer()); + res.set('Content-Type', 'image/png'); + res.set('X-AI-Action', action); + return res.send(buf); + } catch (err) { + const timedOut = err.name === 'TimeoutError' || err.name === 'AbortError'; + logger.error(`❌ AI ${action} 代理失败: ${err.message}`); + return res.status(502).json({ + error: timedOut ? 'AI 处理超时(超过 5 分钟),请缩小图片后重试' : `AI 服务不可达: ${err.message}` + }); + } + }) +); + +const IMAGE_EXTS = new Set(['.jpg', '.jpeg', '.png', '.webp']); +const SHARP_FORMAT = { '.jpg': 'jpeg', '.jpeg': 'jpeg', '.png': 'png', '.webp': 'webp' }; + +/** + * POST /api/edit/save + * FormData: image=file(编辑结果 PNG), libraryId, path(原相对路径), mode=overwrite|new + * 返回:{ path, filename, mode, regenerated } + */ +router.post( + '/save', + upload.single('image'), + asyncHandler(async (req, res) => { + const { libraryId, path: relPath, mode = 'overwrite' } = req.body; + if (!req.file || !libraryId || !relPath) { + return res.status(400).json({ error: '缺少图片、素材库或路径参数' }); + } + + const configManager = req.app.get('configManager'); + const dbPool = req.app.get('dbPool'); + if (!configManager || !dbPool) { + return res.status(500).json({ error: '服务未初始化' }); + } + + const config = configManager.load(); + const library = config.libraries.find((lib) => String(lib.id) === String(libraryId)); + if (!library) { + return res.status(404).json({ error: '素材库不存在' }); + } + + const libraryPath = library.path; + const srcAbs = path.join(libraryPath, relPath); + const ext = path.extname(srcAbs).toLowerCase(); + const db = dbPool.acquire(libraryPath); + + let targetAbs; + let outFormat; + let finalRel; + + if (mode === 'overwrite') { + if (!IMAGE_EXTS.has(ext)) { + // 原图格式不支持原地转码(gif/bmp/tiff 等)→ 自动降级为另存新图 PNG + const base = path.basename(relPath, path.extname(relPath)); + const dir = path.dirname(relPath); + finalRel = uniqueRel(libraryPath, dir, `${base}-编辑`, '.png'); + targetAbs = path.join(libraryPath, finalRel); + outFormat = 'png'; + } else { + targetAbs = srcAbs; + finalRel = relPath; + outFormat = SHARP_FORMAT[ext]; + } + } else { + const base = path.basename(relPath, path.extname(relPath)); + const dir = path.dirname(relPath); + const preferExt = IMAGE_EXTS.has(ext) ? ext : '.png'; + finalRel = uniqueRel(libraryPath, dir, `${base}-编辑`, preferExt); + targetAbs = path.join(libraryPath, finalRel); + outFormat = SHARP_FORMAT[preferExt] || 'png'; + } + + // 转码写盘 + let pipeline = sharp(req.file.buffer); + if (outFormat === 'jpeg') { + pipeline = pipeline.flatten({ background: '#ffffff' }).jpeg({ quality: 92 }); + } else if (outFormat === 'webp') { + pipeline = pipeline.webp({ quality: 92 }); + } else { + pipeline = pipeline.png(); + } + + fs.mkdirSync(path.dirname(targetAbs), { recursive: true }); + await pipeline.toFile(targetAbs); + + // 重建缩略图 + 更新数据库(文件 hash 变化会触发完整更新) + let regenerated = false; + try { + await processImage(targetAbs, libraryPath, db); + regenerated = true; + } catch (err) { + logger.error(`❌ 编辑保存后处理失败: ${err.message}`); + } + + const stat = fs.statSync(targetAbs); + logger.info( + `✅ 编辑保存 [${mode}] ${relPath} → ${finalRel} (${(stat.size / 1024).toFixed(0)}KB)` + ); + + return res.json({ + success: true, + path: finalRel.replace(/\\/g, '/'), + filename: path.basename(finalRel), + mode: mode === 'overwrite' && finalRel === relPath ? 'overwrite' : 'new', + originalPath: relPath, + size: stat.size, + regenerated, + modifiedAt: Math.floor(stat.mtimeMs / 1000) + }); + }) +); + +/** + * POST /api/edit/find-similar — AI 自动从图库找与种子图相似的图片(合拼功能) + * body: { libraryId, seedPath, count, excludePaths? } + * 依赖设置中的线上模型 KEY(与 OCR 线上配置共用) + * 返回: { success, images: [前端格式图片记录] } + */ +router.post( + '/find-similar', + asyncHandler(async (req, res) => { + const { libraryId, seedPath, count = 3, excludePaths = [] } = req.body || {}; + if (!libraryId || !seedPath) { + return res.status(400).json({ success: false, error: { message: '缺少 libraryId 或 seedPath' } }); + } + + const s = getSettings(); + const online = s.ocr && s.ocr.online; + if (!online || !online.url || !online.apiKey) { + return res.status(400).json({ + success: false, + error: { message: '未配置模型 KEY:请先在「设置 → OCR 识别」填写线上模型接口和 API Key' } + }); + } + + const configManager = req.app.get('configManager'); + const dbPool = req.app.get('dbPool'); + const config = configManager.load(); + const library = (config.libraries || []).find((l) => String(l.id) === String(libraryId)); + if (!library) { + return res.status(404).json({ success: false, error: { message: '图库不存在' } }); + } + + const want = Math.max(1, Math.min(9, parseInt(count, 10) || 3)); + const conn = dbPool.acquire(library.path); + try { + const raw = conn.db; // better-sqlite3 实例 + const seed = raw.prepare('SELECT * FROM images WHERE path = ?').get(seedPath); + if (!seed) { + return res.status(404).json({ success: false, error: { message: '种子图不存在' } }); + } + + // 候选采样:优先同文件夹,不足再全库随机;排除种子与已选 + const exclude = [seedPath, ...(Array.isArray(excludePaths) ? excludePaths : [])].filter(Boolean); + const ph = exclude.map(() => '?').join(','); + const SAMPLE = 20; + let cands = raw + .prepare( + `SELECT * FROM images WHERE folder = ? AND path NOT IN (${ph}) ORDER BY RANDOM() LIMIT ?` + ) + .all(seed.folder, ...exclude, SAMPLE); + if (cands.length < SAMPLE) { + const more = raw + .prepare(`SELECT * FROM images WHERE path NOT IN (${ph}) ORDER BY RANDOM() LIMIT ?`) + .all(...exclude, SAMPLE - cands.length); + cands = cands.concat(more); + } + if (!cands.length) { + return res.status(400).json({ success: false, error: { message: '图库中没有其他图片可供选择' } }); + } + + // 缩略图 → 小尺寸 JPEG base64(节省 token) + const toDataURI = async (rec) => { + const abs = rec.thumbnail_path + ? path.join(library.path, rec.thumbnail_path) + : path.join(library.path, rec.path); + const buf = await sharp(abs) + .resize(384, 384, { fit: 'inside', withoutEnlargement: true }) + .jpeg({ quality: 70 }) + .toBuffer(); + return `data:image/jpeg;base64,${buf.toString('base64')}`; + }; + + const seedURI = await toDataURI(seed); + const candURIs = []; + const validCands = []; + for (const c of cands) { + try { + candURIs.push(await toDataURI(c)); + validCands.push(c); + } catch (_) { /* 跳过损坏缩略图 */ } + } + if (!validCands.length) { + return res.status(500).json({ success: false, error: { message: '候选图缩略图读取失败' } }); + } + + const prompt = + `第一张是参考图。后面有 ${validCands.length} 张候选图,按出现顺序编号 1 到 ${validCands.length}。` + + `请选出与参考图在内容、主题、风格上最相似的 ${want} 张,按相似度从高到低排列,` + + `只返回一个 JSON 数组,元素为候选图编号,例如 [3,7,12],不要输出任何其他文字。`; + + const content = [ + { type: 'text', text: prompt }, + { type: 'image_url', image_url: { url: seedURI } }, + ...candURIs.map((u) => ({ type: 'image_url', image_url: { url: u } })) + ]; + + const ctrl = new AbortController(); + const timer = setTimeout(() => ctrl.abort(), 90000); + let text; + try { + const r = await fetch(normalizeOnlineUrl(online.url), { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `***}` + }, + body: JSON.stringify({ + model: online.model || 'gpt-4o-mini', + max_tokens: 500, + messages: [{ role: 'user', content }] + }), + signal: ctrl.signal + }); + const data = await r.json(); + if (!r.ok || data.error) { + throw new Error((data.error && data.error.message) || `HTTP ${r.status}`); + } + text = data.choices && data.choices[0] && data.choices[0].message + ? data.choices[0].message.content + : ''; + } finally { + clearTimeout(timer); + } + + const m = String(text).match(/\[[\s\d,]+\]/); + if (!m) { + logger.warn(`find-similar 模型返回无法解析: ${String(text).slice(0, 200)}`); + return res.status(502).json({ success: false, error: { message: '模型返回格式无法解析,请重试' } }); + } + let idx; + try { + idx = JSON.parse(m[0]); + } catch (_) { + return res.status(502).json({ success: false, error: { message: '模型返回格式无法解析,请重试' } }); + } + const picked = []; + const seen = new Set(); + for (const i of idx) { + const n = parseInt(i, 10); + if (n >= 1 && n <= validCands.length && !seen.has(n)) { + seen.add(n); + picked.push(validCands[n - 1]); + } + if (picked.length >= want) break; + } + if (!picked.length) { + return res.status(502).json({ success: false, error: { message: '未找到相似图片,请重试' } }); + } + + logger.info(`find-similar: 种子=${seedPath} 候选=${validCands.length} 命中=${picked.length}`); + res.json({ success: true, images: picked.map(mapImageForFrontend) }); + } finally { + dbPool.release(library.path); + } + }) +); + +/** 生成不冲突的相对路径:. / (1). ... */ +function uniqueRel(libraryPath, dir, baseName, ext) { + let candidate = path.join(dir, `${baseName}${ext}`).replace(/\\/g, '/'); + let i = 0; + while (fs.existsSync(path.join(libraryPath, candidate))) { + i += 1; + candidate = path.join(dir, `${baseName}(${i})${ext}`).replace(/\\/g, '/'); + } + return candidate; +} + +module.exports = router; diff --git a/backend/src/routes/image.js b/backend/src/routes/image.js index 4929286..b805536 100644 --- a/backend/src/routes/image.js +++ b/backend/src/routes/image.js @@ -28,12 +28,13 @@ router.use((req, res, next) => { router.get('/', validatePagination, asyncHandler(async (req, res) => { - const { libraryId, keywords, folder, formats, offset, limit } = req.query; + const { libraryId, keywords, folder, formats, favorite, offset, limit } = req.query; const filters = {}; if (keywords) filters.keywords = keywords; if (folder) filters.folder = folder; if (formats) filters.formats = formats.split(','); + if (favorite !== undefined) filters.favorite = favorite; const pagination = (offset !== undefined && limit !== undefined) ? { offset: parseInt(offset), limit: parseInt(limit) } @@ -49,8 +50,11 @@ router.get('/', * GET /api/image/count?libraryId=xxx */ router.get('/count', asyncHandler(async (req, res) => { - const { libraryId } = req.query; - const count = await imageService.getImageCount(libraryId); + const { libraryId, favorite, folder } = req.query; + const filters = {}; + if (favorite !== undefined) filters.favorite = favorite; + if (folder) filters.folder = folder; + const count = await imageService.getImageCount(libraryId, filters); res.json({ success: true, data: { count } }); })); diff --git a/backend/src/routes/settings.js b/backend/src/routes/settings.js index f2d316e..dbd1530 100644 --- a/backend/src/routes/settings.js +++ b/backend/src/routes/settings.js @@ -14,6 +14,7 @@ const router = express.Router(); router.get('/', (req, res) => { const s = getSettings(); + const ig = s.imagegen || {}; res.json({ success: true, data: { @@ -24,7 +25,22 @@ router.get('/', (req, res) => { apiKeyMasked: maskKey(s.ocr.online.apiKey), configured: !!(s.ocr.online.url && s.ocr.online.apiKey) }, - telemetry: s.telemetry + telemetry: s.telemetry, + imagegen: { + provider: ig.provider === 'custom' ? 'custom' : 'newapi', + newapi: { + url: (ig.newapi && ig.newapi.url) || '', + apiKeyMasked: maskKey((ig.newapi && ig.newapi.apiKey) || ''), + // 真正生效的 key:设置里的或环境变量兜底 + hasKey: !!((ig.newapi && ig.newapi.apiKey) || process.env.NEWAPI_KEY) + }, + custom: { + url: (ig.custom && ig.custom.url) || '', + model: (ig.custom && ig.custom.model) || '', + apiKeyMasked: maskKey((ig.custom && ig.custom.apiKey) || ''), + configured: !!(ig.custom && ig.custom.url && ig.custom.apiKey) + } + } } }); }); @@ -32,6 +48,7 @@ router.get('/', (req, res) => { router.put('/', (req, res) => { try { const saved = saveSettings(req.body || {}); + const ig = saved.imagegen || {}; res.json({ success: true, data: { @@ -42,7 +59,21 @@ router.put('/', (req, res) => { apiKeyMasked: maskKey(saved.ocr.online.apiKey), configured: !!(saved.ocr.online.url && saved.ocr.online.apiKey) }, - telemetry: saved.telemetry + telemetry: saved.telemetry, + imagegen: { + provider: ig.provider, + newapi: { + url: ig.newapi.url, + apiKeyMasked: maskKey(ig.newapi.apiKey), + hasKey: !!(ig.newapi.apiKey || process.env.NEWAPI_KEY) + }, + custom: { + url: ig.custom.url, + model: ig.custom.model, + apiKeyMasked: maskKey(ig.custom.apiKey), + configured: !!(ig.custom.url && ig.custom.apiKey) + } + } } }); } catch (e) { diff --git a/backend/utils/scanner.js b/backend/utils/scanner.js index 30d9556..b875252 100644 --- a/backend/utils/scanner.js +++ b/backend/utils/scanner.js @@ -279,6 +279,19 @@ async function processImage(imagePath, libraryPath, db, dryRun = false) { // Skip only if unchanged and thumbnails are up-to-date if (existing && existing.file_hash === currentHash && !needRegenThumbs) { + // OCR 补扫:老记录入库时还没有 OCR 功能(ocr_done=0), + // 文件没变也会在这里补跑一次文字识别,"重新扫描"的主要意义即在于此。 + // 识别为空也标记 ocr_done=1,避免每次扫描重复识别。 + const needsOcr = !existing.ocr_done && getFileType(imagePath) === 'image'; + if (needsOcr) { + try { + const backfillText = await extractText(imagePath); + db.updateOcrResult(relativePath.replace(/\\/g, '/'), backfillText || ''); + return { status: 'ocr', path: relativePath }; + } catch (ocrError) { + logger.warn(`OCR 补扫失败: ${filename} (${ocrError.message})`); + } + } const totalTime = Date.now() - processStartTime; // logger.info(`⏭️ 跳过 (未变化): ${filename} (${totalTime}ms)`); return { status: 'skipped', path: relativePath }; @@ -324,7 +337,8 @@ async function processImage(imagePath, libraryPath, db, dryRun = false) { file_hash: currentHash, thumbnail_path: thumbnails.thumbnail_path, thumbnail_size: thumbnails.thumbnail_size, - ocr_text: ocrText + ocr_text: ocrText, + ocr_done: 1 // 新/变化文件已执行过 OCR(extractText 失败返回空串,也算已尝试) }; if (dryRun) { @@ -415,6 +429,7 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume const results = { processed: 0, skipped: 0, + ocr: 0, errors: 0, stopped: false }; @@ -457,6 +472,7 @@ async function scanLibrary(libraryPath, db, onProgress, libraryId = null, resume // 更新统计 if (result.status === 'processed') results.processed++; + else if (result.status === 'ocr') results.ocr++; else if (result.status === 'skipped') results.skipped++; else if (result.status === 'error') results.errors++; diff --git a/backend/utils/settings.js b/backend/utils/settings.js index 3309d9d..5f45cc8 100644 --- a/backend/utils/settings.js +++ b/backend/utils/settings.js @@ -17,7 +17,20 @@ const DEFAULTS = { model: 'mimo-v2.6-flash' // 默认视觉模型 } }, - telemetry: true // CardAuth 心跳/版本/公告上报开关 + telemetry: true, // CardAuth 心跳/版本/公告上报开关 + // AI 生图(内置 NewAPI:Pollinations + CF Workers AI;或自定义 OpenAI 兼容提供商) + imagegen: { + provider: 'newapi', // 'newapi' | 'custom' + newapi: { + url: 'http://192.168.68.19:3099/v1', + apiKey: '' // 留空则用服务器环境变量 NEWAPI_KEY + }, + custom: { + url: '', + apiKey: '', + model: '' + } + } }; function settingsPath() { @@ -39,7 +52,19 @@ function getSettings() { model: (data.ocr && data.ocr.online && data.ocr.online.model) || DEFAULTS.ocr.online.model } }, - telemetry: data.telemetry !== false + telemetry: data.telemetry !== false, + imagegen: { + provider: (data.imagegen && data.imagegen.provider) === 'custom' ? 'custom' : 'newapi', + newapi: { + url: (data.imagegen && data.imagegen.newapi && data.imagegen.newapi.url) || DEFAULTS.imagegen.newapi.url, + apiKey: (data.imagegen && data.imagegen.newapi && data.imagegen.newapi.apiKey) || '' + }, + custom: { + url: (data.imagegen && data.imagegen.custom && data.imagegen.custom.url) || '', + apiKey: (data.imagegen && data.imagegen.custom && data.imagegen.custom.apiKey) || '', + model: (data.imagegen && data.imagegen.custom && data.imagegen.custom.model) || '' + } + } }; } catch (e) { console.error('[Settings] 读取失败,使用默认:', e.message); @@ -63,6 +88,26 @@ function saveSettings(settings) { } } if (typeof settings.telemetry === 'boolean') merged.telemetry = settings.telemetry; + if (settings.imagegen) { + const ig = settings.imagegen; + if (ig.provider === 'custom' || ig.provider === 'newapi') merged.imagegen.provider = ig.provider; + if (ig.newapi) { + if (typeof ig.newapi.url === 'string') merged.imagegen.newapi.url = ig.newapi.url.trim(); + const k = ig.newapi.apiKey; + // 空串/掩码 = 保持原值(与 OCR 行为一致) + if (typeof k === 'string' && k.trim() && !k.includes('***')) { + merged.imagegen.newapi.apiKey = k.trim(); + } + } + if (ig.custom) { + if (typeof ig.custom.url === 'string') merged.imagegen.custom.url = ig.custom.url.trim(); + if (typeof ig.custom.model === 'string') merged.imagegen.custom.model = ig.custom.model.trim(); + const ck = ig.custom.apiKey; + if (typeof ck === 'string' && ck.trim() && !ck.includes('***')) { + merged.imagegen.custom.apiKey = ck.trim(); + } + } + } fs.writeFileSync(p, JSON.stringify(merged, null, 2)); return merged; } diff --git a/docker-compose.yml b/docker-compose.yml index 4ed7e73..20ee336 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -19,10 +19,16 @@ services: - PORT=15002 - FRONTEND_DIST=/app/backend/public - NODE_ENV=production + # AI 图像处理侧车(去背景/高清/去水印/换脸)——宿主机 systemd flypic-ai 监听 127.0.0.1:15003 + - AI_BASE_URL=http://host.docker.internal:15003 # 授权系统(CardAuth):版本推送 / 公告 / 在线人数统计 —— 失败开放,不可达不影响使用 - HUB_URL=https://auth.88531.cn/api - HUB_PROJECT_ID=15 - HUB_API_KEY=${HUB_API_KEY:-} + - NEWAPI_KEY=${NEWAPI_KEY:-} + # 让容器经 host.docker.internal 访问宿主机的 AI 侧车 + extra_hosts: + - "host.docker.internal:host-gateway" # 如需挂载多个素材库,取消注释并修改路径: # volumes: # - /vol1/1000/图片库:/data/library1:ro diff --git a/frontend/index.html b/frontend/index.html index 409d28d..01a0008 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -4,7 +4,7 @@ - FlyPic 飞图 - 图片素材库管理 + 牛图 - 图片素材库管理
diff --git a/frontend/package.json b/frontend/package.json index 74ccff7..480bf06 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "flypic-frontend", - "version": "1.2.0", + "version": "1.3.0", "private": true, "type": "module", "scripts": { @@ -12,6 +12,7 @@ }, "dependencies": { "axios": "^1.6.2", + "fabric": "^6.9.1", "jszip": "^3.10.1", "lucide-react": "^0.300.0", "react": "^18.2.0", diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index ecec1dc..e3bb702 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -12,6 +12,8 @@ import MainContent from './components/MainContent'; import RightPanel from './components/RightPanel'; import Header from './components/Header'; import LibraryMissingModal from './components/LibraryMissingModal'; +import BackToTop from './components/BackToTop'; +import ImageEditor from './components/ImageEditor'; import { createLogger } from './utils/logger'; const logger = createLogger('App'); @@ -124,11 +126,16 @@ function App() { params.folder = imageState.selectedFolder; } + // 「我的收藏」视图:按收藏过滤 + if (imageState.favoritesView) { + params.favorite = 1; + } + // 并行加载文件夹、图片和统计信息 Promise.all([ imageAPI.getFolders(libraryId), // 如果没有选中文件夹且没有搜索条件,不加载图片(保持在 Dashboard) - (imageState.selectedFolder || imageState.searchKeywords || imageState.filters.formats.length > 0) + (imageState.selectedFolder || imageState.searchKeywords || imageState.filters.formats.length > 0 || imageState.favoritesView) ? imageAPI.search(libraryId, params) : Promise.resolve({ images: [] }), // 扫描完成后重新获取统计信息(包含 totalSize) @@ -493,6 +500,7 @@ function App() { if (isMobile) { return (
+
{/* 素材库路径丢失弹窗 */} +
{/* 侧边栏视图 */}
+
{/* 素材库路径丢失弹窗 */} -
+ /> + +
{/* 左侧边栏 */}
diff --git a/frontend/src/api/endpoints/aigen.js b/frontend/src/api/endpoints/aigen.js new file mode 100644 index 0000000..7bf4648 --- /dev/null +++ b/frontend/src/api/endpoints/aigen.js @@ -0,0 +1,22 @@ +/** + * AI 生图 API + * 注意:client 的 API_BASE 已含 /api,这里只写 /aigen 段 + */ +import { api } from '../client'; + +/** 模型分组 + 当前配置(apiKey 掩码) */ +export function getModels() { + return api.get('/aigen/models'); +} + +/** + * 生成图片 + * @param {Object} payload { prompt, model?, size?, provider? } + * provider: 'builtin' | 'custom' + */ +export function generate(payload) { + return api.post('/aigen/generate', payload, { timeout: 180000 }); +} + +export const aigenAPI = { getModels, generate }; +export default aigenAPI; diff --git a/frontend/src/api/endpoints/batch.js b/frontend/src/api/endpoints/batch.js new file mode 100644 index 0000000..4dd22a0 --- /dev/null +++ b/frontend/src/api/endpoints/batch.js @@ -0,0 +1,21 @@ +/** + * 批量水印 API(文件夹级) + */ + +import { api } from '../client'; + +/** 启动批量任务,返回 { taskId, total } */ +export async function start(payload) { + // payload: { libraryId, folder, type: 'add'|'remove', output?, options } + return api.post('/batch/start', payload); +} + +/** 查询任务进度 */ +export async function status(taskId) { + return api.get(`/batch/status/${taskId}`); +} + +/** 取消任务 */ +export async function cancel(taskId) { + return api.post(`/batch/cancel/${taskId}`); +} diff --git a/frontend/src/api/endpoints/image.js b/frontend/src/api/endpoints/image.js index 5fcfc9d..25a666e 100644 --- a/frontend/src/api/endpoints/image.js +++ b/frontend/src/api/endpoints/image.js @@ -19,8 +19,9 @@ export async function search(libraryId, params = {}, options = {}) { /** * 获取图片总数 */ -export async function getCount(libraryId) { - return api.get(`/image/count?libraryId=${libraryId}`); +export async function getCount(libraryId, params = {}) { + const query = new URLSearchParams({ libraryId, ...params }); + return api.get(`/image/count?${query}`); } /** @@ -48,8 +49,10 @@ export async function getCacheMeta(libraryId) { * 获取缩略图 URL * 使用分片结构,不再需要 size 参数 */ -export function getThumbnailUrl(libraryId, filename) { - return `/api/image/thumbnail/${libraryId}/${filename}`; +export function getThumbnailUrl(libraryId, filename, version) { + const base = `/api/image/thumbnail/${libraryId}/${filename}`; + // version=文件 modified_at,编辑保存后变化以穿透浏览器缓存 + return version ? `${base}?v=${version}` : base; } /** diff --git a/frontend/src/api/index.js b/frontend/src/api/index.js index 015676e..463dc0c 100644 --- a/frontend/src/api/index.js +++ b/frontend/src/api/index.js @@ -8,12 +8,15 @@ import * as scan from './endpoints/scan'; import { fileAPI } from './file'; import { settingsAPI } from './endpoints/settings'; import { hubAPI } from './endpoints/hub'; +import * as batch from './endpoints/batch'; +import { aigenAPI } from './endpoints/aigen'; export const libraryAPI = library; export const imageAPI = image; export const scanAPI = scan; export { fileAPI }; -export { settingsAPI, hubAPI }; +export { settingsAPI, hubAPI, aigenAPI }; +export const batchAPI = batch; export { api, APIError } from './client'; diff --git a/frontend/src/components/AIGenModal.jsx b/frontend/src/components/AIGenModal.jsx new file mode 100644 index 0000000..2789c4d --- /dev/null +++ b/frontend/src/components/AIGenModal.jsx @@ -0,0 +1,432 @@ +import { useState, useEffect, useRef, useCallback } from 'react'; +import { + X, Wand2, Loader2, Download, Save, RefreshCw, Sparkles, + ChevronDown, FolderOpen, CheckCircle2, AlertTriangle +} from 'lucide-react'; +import { aigenAPI, fileAPI, imageAPI } from '../api'; +import { useLibraryStore } from '../stores/useLibraryStore'; +import { useImageStore } from '../stores/useImageStore'; +import { PROMPT_CATEGORIES } from '../constants/promptPresets'; + +/** + * AI 生图弹窗 + * - 热门提示词分类(点击填入/追加) + * - 内置模型(NewAPI:CF Workers AI / Pollinations)+ 自定义提供商 + * - 生成 → 预览 → 保存到素材库 / 下载 / 重新生成 + */ + +function flattenFolders(folders) { + // 节点自带完整 path(FolderModel.getTree) + const out = [{ path: '', label: '(根目录)' }]; + const walk = (list) => { + for (const f of list || []) { + if (f.path) out.push({ path: f.path, label: f.path }); + if (f.children && f.children.length) walk(f.children); + } + }; + walk(folders); + return out; +} + +export default function AIGenModal({ open, onClose, onSaved }) { + const { currentLibraryId } = useLibraryStore(); + const { folders, setFolders, setImages, selectedFolder } = useImageStore(); + + const [prompt, setPrompt] = useState(''); + const [cat, setCat] = useState('hot'); + const [groups, setGroups] = useState([]); + const [sizes, setSizes] = useState([]); + const [providerInfo, setProviderInfo] = useState(null); + const [model, setModel] = useState('flux-schnell'); + const [size, setSize] = useState('1024x1024'); + const [useCustom, setUseCustom] = useState(false); + + const [loading, setLoading] = useState(false); + const [error, setError] = useState(''); + const [result, setResult] = useState(null); // { b64, revisedPrompt, ms, model } + const [saveTarget, setSaveTarget] = useState(''); + const [saving, setSaving] = useState(false); + const [saved, setSaved] = useState(false); + const [showFolderPick, setShowFolderPick] = useState(false); + const [advanced, setAdvanced] = useState(false); + const imgRef = useRef(null); + + // 打开时拉模型列表 + 当前配置 + useEffect(() => { + if (!open) return; + setError(''); + setResult(null); + setSaved(false); + aigenAPI.getModels() + .then((d) => { + setGroups(d.groups || []); + setSizes(d.sizes || []); + setProviderInfo(d.provider || null); + const first = (d.groups || [])[0]; + if (first && first.models && first.models[0]) setModel(first.models[0].id); + if (d.provider && d.provider.type === 'custom') setUseCustom(true); + }) + .catch((e) => setError('读取模型列表失败: ' + (e.data?.error || e.message))); + }, [open]); + + const currentModelId = useCustom ? (providerInfo?.customModel || '') : model; + const handleGenerate = async () => { + if (!prompt.trim()) { setError('请先输入提示词,或点一个热门提示词'); return; } + setLoading(true); + setError(''); + setSaved(false); + try { + const d = await aigenAPI.generate({ + prompt: prompt.trim(), + model: useCustom ? undefined : model, + size, + provider: useCustom ? 'custom' : 'builtin' + }); + const img = d.images && d.images[0]; + if (!img || !img.b64) throw new Error('未返回图片数据'); + const ext = d.ext || img.ext || 'png'; + setResult({ b64: img.b64, ext, mime: ext === 'jpg' ? 'jpeg' : ext, revisedPrompt: d.revisedPrompt, ms: d.ms, model: d.model }); + // 生成成功后刷新一次文件夹(可能有别处新入库) + if (currentLibraryId) { + imageAPI.getFolders(currentLibraryId).then((r) => setFolders(r.folders)).catch(() => {}); + } + } catch (e) { + setError(e.data?.error || e.message || '生成失败'); + } finally { + setLoading(false); + } + }; + + const b64ToFile = () => { + const bin = atob(result.b64); + const arr = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i); + const ts = new Date(); + const pad = (n) => String(n).padStart(2, '0'); + const ext = result.ext || 'png'; + const name = `AI_${ts.getFullYear()}${pad(ts.getMonth() + 1)}${pad(ts.getDate())}_${pad(ts.getHours())}${pad(ts.getMinutes())}${pad(ts.getSeconds())}.${ext}`; + return new File([arr], name, { type: `image/${result.mime || ext}` }); + }; + + const handleSave = async () => { + if (!currentLibraryId) { setError('请先选择素材库'); return; } + setSaving(true); + setError(''); + try { + const file = b64ToFile(); + await fileAPI.upload(currentLibraryId, saveTarget, [file], undefined, 'rename'); + setSaved(true); + // 刷新文件夹与当前视图 + const r = await imageAPI.getFolders(currentLibraryId); + setFolders(r.folders); + const params = { folder: selectedFolder || '' }; + const resp = await imageAPI.search(currentLibraryId, params); + setImages(resp.images); + onSaved && onSaved(); + } catch (e) { + setError('保存失败: ' + (e.data?.error || e.message)); + } finally { + setSaving(false); + } + }; + + const handleDownload = () => { + const a = document.createElement('a'); + a.href = `data:image/${result.mime || 'png'};base64,${result.b64}`; + a.download = b64ToFile().name; + a.click(); + }; + + const appendPrompt = (p) => { + setPrompt((prev) => (prev.trim() ? prev.replace(/[,,、\s]+$/, '') + ',' + p : p)); + setError(''); + }; + + if (!open) return null; + + const activeCat = PROMPT_CATEGORIES.find((c) => c.key === cat) || PROMPT_CATEGORIES[0]; + const noKey = providerInfo && !providerInfo.hasKey && !useCustom; + + return ( +
+
e.stopPropagation()} + > + {/* 头部 */} +
+
+
+ +
+

AI 生图

+ 热门提示词 · 一键生成 · 入库 +
+ +
+ +
+
+ {/* 左:提示词 + 热门词库 */} +
+
+
+ + {prompt.length} 字 +
+