feat: AI生图提示词翻译成英文后再发往上流(img2img 全链路 + 视频/设置改动)

This commit is contained in:
jinghui committed 2026-11-19 08:30:20 +08:00
1 parent 76d9d45770
commit b6e0c475d3
9 files changed
+1169 -34

No files matched your search

+143 -13
View File
@@ -7,7 +7,45 @@
*/
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 fs = require('fs');
const path = require('path');
const { asyncHandler } = require('../middleware/errorHandler');
const logger = require('../utils/logger');
const { getSettings } = require('../../utils/settings');
@@ -38,6 +76,61 @@ const BUILTIN_GROUPS = [
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 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 */
function normalizeGenUrl(url) {
let u = String(url || '').trim().replace(/\/+$/, '');
@@ -87,6 +180,7 @@ router.get('/models', asyncHandler(async (req, res) => {
success: true,
data: {
groups: BUILTIN_GROUPS,
editModels: EDIT_MODELS,
sizes: ALLOWED_SIZES,
provider: {
type: cur.provider,
@@ -109,7 +203,13 @@ router.get('/models', asyncHandler(async (req, res) => {
*/
router.post('/generate', asyncHandler(async (req, res) => {
const t0 = Date.now();
const { prompt, model, size, provider } = req.body || {};
const { prompt, model, size, provider, libraryId } = req.body || {};
// 文生图:中文提示词先翻译成英文再发给上游(图生图同样翻译)
const originalPrompt = String(prompt || '').trim();
const effPrompt = await translatePromptToEnglish(originalPrompt, effUrl, effKey);
// 参考图(以图生图):兼容 refImages / refs / refPaths 三种字段
const rawRefs = (req.body && (req.body.refImages || req.body.refs || req.body.refPaths)) || [];
if (!prompt || !String(prompt).trim()) {
return res.status(400).json({ success: false, error: '提示词不能为空' });
@@ -140,26 +240,50 @@ router.post('/generate', asyncHandler(async (req, res) => {
}
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;
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 timer = setTimeout(() => ctrl.abort(), 150000); // 生图最长 150s
const timer = setTimeout(() => ctrl.abort(), isEdit ? 300000 : 150000); // 图生图更慢,最长 300s
let result;
try {
const resp = await fetch(genUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${effKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
let body;
let headers = { 'Authorization': `Bearer ${effKey}` };
if (isEdit) {
const form = new FormData();
form.append('model', String(effModel || 'flux-2'));
form.append('prompt', String(effPrompt));
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,
prompt: String(prompt),
prompt: String(effPrompt),
n: 1,
size: effSize
}),
});
}
const resp = await fetch(targetUrl, {
method: 'POST',
headers,
body,
signal: ctrl.signal
});
const text = await resp.text();
@@ -171,6 +295,9 @@ router.post('/generate', asyncHandler(async (req, res) => {
if (j.error && j.error.message) msg = j.error.message;
else if (j.message) msg = j.message;
} 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 });
}
result = JSON.parse(text);
@@ -227,6 +354,9 @@ router.post('/generate', asyncHandler(async (req, res) => {
revisedPrompt: result.data && result.data[0] && result.data[0].revised_prompt,
model: effModel,
size: effSize,
promptEn: effPrompt,
edited: isEdit,
refCount: refs.length,
ms: Date.now() - t0
}
});
+18
View File
@@ -40,6 +40,15 @@ router.get('/', (req, res) => {
apiKeyMasked: maskKey((ig.custom && 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)
}
}
}
});
@@ -73,6 +82,15 @@ router.put('/', (req, res) => {
apiKeyMasked: maskKey(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)
}
}
}
});
+199 -11
View File
@@ -14,9 +14,11 @@ const fs = require('fs');
const os = require('os');
const { asyncHandler, ValidationError, NotFoundError } = require('../middleware/errorHandler');
const { processImage } = require('../../utils/scanner');
const { getSettings } = require('../../utils/settings');
const { getSettings, resolveVideoGen } = require('../../utils/settings');
const logger = require('../utils/logger');
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']);
@@ -133,7 +135,8 @@ router.post(
model, // 模型名
voice = 'zh-CN-XiaoxiaoNeural',
resolution = '1920x1080',
extraPrompt = ''
extraPrompt = '',
subtitleStyle = {}
} = req.body || {};
if (!libraryId || !Array.isArray(images) || images.length < 2) {
@@ -156,14 +159,13 @@ router.post(
if (!library) throw new NotFoundError('Library', libraryId);
const settings = getSettings();
const gen = (settings.imagegen && settings.imagegen.provider === 'custom')
? settings.imagegen.custom
: settings.imagegen.newapi;
// 设置 - 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('未配置模型接口地址(填 BASE URL 或在设置里配置)');
if (!key) throw new ValidationError('请填写模型 KEY(或在设置-生图里配置)');
if (!url) throw new ValidationError('未配置模型接口地址(请到右上角设置 → AI 视频里填写)');
if (!key) throw new ValidationError('请先在右上角设置 → AI 视频里填写模型 KEY');
const id = `vt${++aiTaskSeq}_${Date.now()}`;
const [w, h] = String(resolution).split('x').map((n) => parseInt(n, 10));
@@ -185,7 +187,7 @@ router.post(
runAiVideo({
task, library, images, title: String(title).trim(), url, key, model: mdl,
voice, width: Number.isFinite(w) ? w : 1920, height: Number.isFinite(h) ? h : 1080,
extraPrompt: String(extraPrompt || ''),
extraPrompt: String(extraPrompt || ''), subtitleStyle: subtitleStyle || {},
req
}).catch((err) => {
task.status = 'error';
@@ -200,7 +202,7 @@ router.post(
router.get(
'/task/:id',
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);
res.json(task);
})
@@ -255,7 +257,7 @@ async function llmScript({ url, key, model, title, count, extraPrompt }) {
}
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) 校验图片文件
const files = [];
@@ -313,7 +315,7 @@ async function runAiVideo(ctx) {
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 });
await videotool.buildSegment(segments[i], out, { width, height, subtitleStyle: ctx.subtitleStyle });
segFiles.push(out);
}
@@ -348,4 +350,190 @@ 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 = '',
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');
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);
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||''), 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, subtitleStyle, req } = ctx;
const work = fs.mkdtempSync(path.join(os.tmpdir(), 'flypic-tv-'));
try {
// 生成背景图(若无图片)
let bgPath = '';
if (Array.isArray(images) && images.length) {
// 用第一张图作为背景
const rel = typeof images[0] === 'string' ? images[0] : images[0].path || images[0].url;
if (rel && fs.existsSync(path.join(library.path, rel))) bgPath = path.join(library.path, rel);
else if (rel && /^https?:/i.test(rel)) {
// 下载
try {
const r = await fetch(rel); const buf = Buffer.from(await r.arrayBuffer());
bgPath = path.join(work, 'bg.jpg'); fs.writeFileSync(bgPath, buf);
} catch (_) {}
}
}
if (!bgPath) {
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 });
}
// LLM 生成分镜:基于内容切分
task.step = 'script'; task.stepLabel = '正在生成脚本'; task.progress = 5;
let script = [];
if (content) {
// 让模型按内容生成 N 段(N = min(8, 句子数))
const sentences = content.split(/[。!?.!?]/).map(s=>s.trim()).filter(Boolean);
const n = Math.min(8, Math.max(2, sentences.length));
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 = [];
for (let i = 0; i < script.length; i++) {
task.step = 'tts'; task.stepLabel = `正在朗读 ${i+1}/${script.length}`; task.progress = 10 + Math.round((i/script.length)*40);
const seg = script[i];
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: bgPath, subtitle: seg.subtitle || seg.tts || title, ttsFile, duration: Math.max(2.5, Math.min(12, dur || 4)) });
}
// 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.concatSegments(segFiles, finalTmp);
const safeTitle = String(title).replace(/[\\/:*?"<>|]/g, '_').slice(0, 60) || 'AI视频';
let target = path.join(library.path, `${safeTitle}.mp4`);
let n = 1;
while (fs.existsSync(target)) { target = path.join(library.path, `${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;