feat(v1.3.0): 图片编辑器(裁剪/旋转/图像大小/调色) + 批量水印 + AI生图 + 收藏体系 + 图片新窗口打开按钮 + 合拼拼图 + 返回顶部

This commit is contained in:
jinghui committed 2026-11-17 23:36:32 +08:00
1 parent e345456abf
commit 94ac94436c
46 files changed
+6521 -114

No files matched your search

+6
View File
@@ -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) => {
+6
View File
@@ -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';
+235
View File
@@ -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;
+403
View File
@@ -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 = `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">` +
`<rect width="${width}" height="${height}" fill="black"/>` +
`<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="white"/></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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(/"/g, '&quot;').replace(/'/g, '&apos;');
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(
`<text x="${x + offset}" y="${y}" font-size="${fontSize}" ${font} ` +
`fill="${fill}" fill-opacity="${opacity}"${stroke}>${esc}</text>`
);
}
row++;
}
const cx = width / 2;
const cy = height / 2;
return `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">` +
`<g transform="rotate(${rotate} ${cx} ${cy})">${items.join('')}</g></svg>`;
}
// 单个水印:九宫格定位
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(
`<text x="${x}" y="${y}" font-size="${fontSize}" ${font} text-anchor="${anchor}" ` +
`fill="${fill}" fill-opacity="${opacity}"${stroke}${transform}>${esc}</text>`
);
return `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">` +
items.join('') + `</svg>`;
}
/** 结果 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;
+368
View File
@@ -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);
}
})
);
/** 生成不冲突的相对路径:<base>.<ext> / <base>(1).<ext> ... */
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;
+7 -3
View File
@@ -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 } });
}));
+33 -2
View File
@@ -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) {