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

+210 -3
View File
@@ -1,7 +1,8 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import {
X, Wand2, Loader2, Download, Save, RefreshCw, Sparkles,
ChevronDown, FolderOpen, CheckCircle2, AlertTriangle
ChevronDown, FolderOpen, CheckCircle2, AlertTriangle,
Image as ImageIcon, Search, Plus, Trash2
} from 'lucide-react';
import { aigenAPI, fileAPI, imageAPI } from '../api';
import { useLibraryStore } from '../stores/useLibraryStore';
@@ -49,6 +50,14 @@ export default function AIGenModal({ open, onClose, onSaved }) {
const [saved, setSaved] = useState(false);
const [showFolderPick, setShowFolderPick] = useState(false);
const [advanced, setAdvanced] = useState(false);
// 参考图(以图生图)
const [editModels, setEditModels] = useState([]);
const [refs, setRefs] = useState([]); // [{ path, filename, thumbnailPath }]
const [showRefPicker, setShowRefPicker] = useState(false);
const [refList, setRefList] = useState([]);
const [refQuery, setRefQuery] = useState('');
const [refLoading, setRefLoading] = useState(false);
const imgRef = useRef(null);
// 打开时拉模型列表 + 当前配置
@@ -57,9 +66,13 @@ export default function AIGenModal({ open, onClose, onSaved }) {
setError('');
setResult(null);
setSaved(false);
setRefs([]);
setShowRefPicker(false);
setRefQuery('');
aigenAPI.getModels()
.then((d) => {
setGroups(d.groups || []);
setEditModels(d.editModels || []);
setSizes(d.sizes || []);
setProviderInfo(d.provider || null);
const first = (d.groups || [])[0];
@@ -70,17 +83,70 @@ export default function AIGenModal({ open, onClose, onSaved }) {
}, [open]);
const currentModelId = useCustom ? (providerInfo?.customModel || '') : model;
/** 素材库缩略图地址 */
const thumbUrl = (img) => {
if (!img || !currentLibraryId) return '';
const raw = img.thumbnailPath || img.path || img.filename || '';
const fn = String(raw).replace(/\\/g, '/').split('/').pop();
return `/api/image/thumbnail/${currentLibraryId}/${encodeURIComponent(fn)}`;
};
/** 打开素材库选图:读当前库的图片(只图片,不含视频) */
const openRefPicker = async () => {
setShowRefPicker(true);
setRefLoading(true);
setRefList([]);
try {
const resp = await imageAPI.search(currentLibraryId, { limit: 200, offset: 0, q: refQuery || undefined });
const list = (resp.images || []).filter((it) => {
const t = String(it.fileType || it.type || '').toLowerCase();
if (t === 'video') return false;
const ext = String(it.filename || it.path || '').split('.').pop().toLowerCase();
return !['mp4', 'mov', 'mkv', 'webm', 'avi', 'm4v', 'ts', 'flv'].includes(ext);
});
setRefList(list);
} catch (e) {
setError('读取素材库图片失败: ' + (e.data?.error || e.message));
} finally {
setRefLoading(false);
}
};
const isPickedRef = (img) => refs.some((r) => r.path === img.path);
const toggleRef = (img) => {
setError('');
if (isPickedRef(img)) {
setRefs((prev) => prev.filter((r) => r.path !== img.path));
return;
}
if (refs.length >= 4) { setError('最多选 4 张参考图'); return; }
setRefs((prev) => [...prev, img]);
// 选了参考图就自动切到图生图模型,避免用户忘记换模型导致图片没被用上
if (editModels.length && !String(model).startsWith('flux-2')) {
setModel(editModels[0].id);
}
};
const handleGenerate = async () => {
if (!prompt.trim()) { setError('请先输入提示词,或点一个热门提示词'); return; }
setLoading(true);
setError('');
setSaved(false);
try {
if (refs.length > 0 && !useCustom && !String(model).startsWith('flux-2')) {
setError('已选参考图,请把模型切换为「FLUX.2 图生图」系列');
setLoading(false);
return;
}
const d = await aigenAPI.generate({
prompt: prompt.trim(),
model: useCustom ? undefined : model,
size,
provider: useCustom ? 'custom' : 'builtin'
provider: useCustom ? 'custom' : 'builtin',
libraryId: currentLibraryId,
refImages: refs.map((r) => ({ path: r.path, filename: r.filename })),
...(refs.length ? {} : {})
});
const img = d.images && d.images[0];
if (!img || !img.b64) throw new Error('未返回图片数据');
@@ -265,6 +331,13 @@ export default function AIGenModal({ open, onClose, onSaved }) {
))}
</optgroup>
))}
{editModels.length > 0 && (
<optgroup label="以图生图(需要参考图)">
{editModels.map((m) => (
<option key={m.id} value={m.id}>{m.name}</option>
))}
</optgroup>
)}
</select>
</div>
)}
@@ -282,6 +355,52 @@ export default function AIGenModal({ open, onClose, onSaved }) {
</div>
)}
{/* 参考图:以图生图 */}
<div>
<div className="flex items-center justify-between mb-1.5">
<label className="text-xs font-medium text-gray-500 dark:text-gray-400">
参考图(以图生图){refs.length > 0 && <span className="text-purple-600 dark:text-purple-400">· 已选 {refs.length}/4</span>}
</label>
{refs.length > 0 && (
<button
onClick={() => setRefs([])}
className="text-[11px] text-gray-400 hover:text-red-500 flex items-center gap-0.5"
>
<Trash2 className="w-3 h-3" />清空
</button>
)}
</div>
<div className="flex items-center gap-1.5 flex-wrap">
{refs.map((r, i) => (
<div key={r.path || i} className="relative w-14 h-14 rounded-lg overflow-hidden border border-gray-200 dark:border-gray-600">
<img src={thumbUrl(r)} alt={r.filename || ''} className="w-full h-full object-cover" />
<button
onClick={() => toggleRef(r)}
className="absolute top-0 right-0 p-0.5 bg-black/60 text-white rounded-bl"
title="移除"
>
<X className="w-3 h-3" />
</button>
</div>
))}
{refs.length < 4 && (
<button
onClick={openRefPicker}
className="w-14 h-14 rounded-lg border-2 border-dashed border-gray-300 dark:border-gray-600 text-gray-400 hover:border-purple-400 hover:text-purple-500 flex flex-col items-center justify-center gap-0.5"
title="从素材库选择参考图"
>
<Plus className="w-4 h-4" />
<span className="text-[9px]">选图</span>
</button>
)}
</div>
<p className="mt-1 text-[11px] text-gray-400 dark:text-gray-500">
{refs.length > 0
? '将按参考图生成(自动切到 FLUX.2 图生图模型),图片只在本机读取,不上传到第三方'
: '选 1-4 张素材库图片做参考,即可换背景、改风格、保持人物一致'}
</p>
</div>
{/* 尺寸 */}
<div>
<label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1.5">尺寸</label>
@@ -323,7 +442,8 @@ export default function AIGenModal({ open, onClose, onSaved }) {
{loading && (
<div className="text-[11px] text-gray-400 dark:text-gray-500 text-center">
正在调用 {useCustom ? '自定义提供商' : (model || '')},超时上限 150 秒
正在调用 {useCustom ? '自定义提供商' : (model || '')}
{refs.length > 0 ? '(以图生图,约 20-60 秒)' : ',超时上限 150 秒'}
</div>
)}
</div>
@@ -427,6 +547,93 @@ export default function AIGenModal({ open, onClose, onSaved }) {
)}
</div>
</div>
{/* 素材库选图(以图生图) */}
{showRefPicker && (
<div
className="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 p-4"
onClick={() => setShowRefPicker(false)}
>
<div
className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-3xl max-h-[85vh] flex flex-col overflow-hidden"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-2">
<ImageIcon className="w-4 h-4 text-purple-500" />
<h3 className="text-sm font-semibold text-gray-900 dark:text-white">从素材库选择参考图</h3>
<span className="text-[11px] text-gray-400">已选 {refs.length}/4</span>
</div>
<button onClick={() => setShowRefPicker(false)} className="p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-700">
<X className="w-4 h-4 text-gray-500" />
</button>
</div>
<div className="px-4 py-2.5 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
<div className="relative flex-1">
<Search className="w-3.5 h-3.5 text-gray-400 absolute left-2.5 top-1/2 -translate-y-1/2" />
<input
value={refQuery}
onChange={(e) => setRefQuery(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') openRefPicker(); }}
placeholder="搜索文件名,回车查询"
className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
/>
</div>
<button
onClick={openRefPicker}
className="px-3 py-1.5 text-xs rounded-lg bg-purple-600 text-white hover:bg-purple-700"
>
查询
</button>
</div>
<div className="flex-1 overflow-y-auto p-3">
{refLoading ? (
<div className="flex items-center justify-center py-16 text-xs text-gray-400 gap-2">
<Loader2 className="w-4 h-4 animate-spin" />读取图片中…
</div>
) : refList.length === 0 ? (
<div className="py-16 text-center text-xs text-gray-400">这个素材库里没有可选图片</div>
) : (
<div className="grid grid-cols-4 sm:grid-cols-5 md:grid-cols-6 gap-2">
{refList.map((img) => {
const picked = isPickedRef(img);
const idx = refs.findIndex((r) => r.path === img.path);
return (
<button
key={img.path || img.filename}
onClick={() => toggleRef(img)}
title={img.filename || img.path}
className={`relative aspect-square rounded-lg overflow-hidden border-2 transition-all ${
picked ? 'border-purple-500 ring-2 ring-purple-300' : 'border-transparent hover:border-gray-300'
}`}
>
<img src={thumbUrl(img)} alt={img.filename || ''} className="w-full h-full object-cover" />
{picked && (
<span className="absolute top-1 left-1 w-5 h-5 rounded-full bg-purple-600 text-white text-[11px] flex items-center justify-center font-medium">
{idx + 1}
</span>
)}
</button>
);
})}
</div>
)}
</div>
<div className="flex items-center justify-between px-4 py-2.5 border-t border-gray-200 dark:border-gray-700">
<span className="text-[11px] text-gray-400">点图多选,按点选顺序作为参考顺序</span>
<button
onClick={() => setShowRefPicker(false)}
className="px-4 py-1.5 text-xs font-medium rounded-lg bg-purple-600 text-white hover:bg-purple-700"
>
完成
</button>
</div>
</div>
</div>
)}
</div>
);
}
@@ -0,0 +1,393 @@
import { useState, useEffect } from 'react';
import { X, Film, Loader2, CheckCircle2, AlertCircle, Link as LinkIcon, FileText, Image as ImageIcon, Sparkles, Search, Check, Settings } from 'lucide-react';
import { getToken } from '../api/client';
const VOICES = [
{ key: 'zh-CN-XiaoxiaoNeural', label: '晓晓(女声·自然)' },
{ key: 'zh-CN-YunxiNeural', label: '云希(男声·温暖)' },
{ key: 'zh-CN-YunjianNeural', label: '云健(男声·浑厚)' },
{ key: 'zh-CN-XiaoyiNeural', label: '晓伊(女声·活泼)' },
{ key: 'zh-CN-YunyangNeural', label: '云扬(男声·播音)' },
];
const RESOLUTIONS = [
{ key: '1920x1080', label: '横屏 1920×1080' },
{ key: '1080x1920', label: '竖屏 1080×1920' },
];
const SUBTITLE_STYLES = [
{ key: 'bottom-center', label: '底部居中', position: 'bottom-center' },
{ key: 'top-center', label: '顶部居中', position: 'top-center' },
{ key: 'center', label: '画面中央', position: 'center' },
];
const SUBTITLE_COLORS = [
{ key: 'white', label: '白色' },
{ key: '#FFD700', label: '金色' },
{ key: '#00FFCC', label: '青色' },
];
const POPULAR_PROMPTS = [
'产品功能速览:突出核心卖点与使用场景',
'周末探店 vlog:轻松活泼的语气',
'知识科普:分步骤讲解一个概念',
'旅行日记:描述风景与心情',
'健身打卡:励志、节奏感强',
'美食制作:步骤清晰、诱人',
'读书分享:提炼要点与感悟',
'科技新闻:简洁、专业',
];
function errText(e, fb) { if (!e) return fb; if (typeof e === 'string') return e; return e.message || JSON.stringify(e); }
function thumbUrl(libraryId, img) {
const tp = img.thumbnailPath || '';
const fn = tp ? tp.replace(/\\/g, '/').split('/').pop() : '';
if (fn) return `/api/image/thumbnail/${libraryId}/${encodeURIComponent(fn)}${img.modifiedAt ? `?v=${img.modifiedAt}` : ''}`;
return `/api/image/original/${libraryId}/${String(img.path || '').split('/').map(encodeURIComponent).join('/')}`;
}
export default function AIVideoStudioModal({ libraryId, onClose, onDone }) {
const [tab, setTab] = useState('prompt');
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [url, setUrl] = useState('');
const [extracted, setExtracted] = useState(null);
const [extracting, setExtracting] = useState(false);
const [file, setFile] = useState(null);
const [voice, setVoice] = useState(VOICES[0].key);
const [resolution, setResolution] = useState('1920x1080');
const [subtitlePos, setSubtitlePos] = useState('bottom-center');
const [subtitleColor, setSubtitleColor] = useState('white');
const [subtitleSize, setSubtitleSize] = useState(5);
// 素材库图片选择(弹窗内直接挑选)
const [libImgs, setLibImgs] = useState([]);
const [libLoading, setLibLoading] = useState(false);
const [keyword, setKeyword] = useState('');
const [picked, setPicked] = useState([]);
const [taskId, setTaskId] = useState('');
const [task, setTask] = useState(null);
const [error, setError] = useState('');
const [starting, setStarting] = useState(false);
const timerRef = { current: null };
const auth = { Authorization: `Bearer ${getToken()}` };
const loadImages = async (kw) => {
setLibLoading(true);
try {
const q = new URLSearchParams({ libraryId: String(libraryId), offset: '0', limit: '120' });
if (kw && kw.trim()) q.set('keywords', kw.trim());
const r = await fetch(`/api/image?${q}`, { headers: auth });
const d = await r.json();
// 只允许图片做视频画面:视频文件当图传给 ffmpeg 会直接报 Option loop not found
const VIDEO_EXT = ['mp4', 'mov', 'mkv', 'webm', 'avi', 'm4v', 'flv', 'wmv', 'ts'];
setLibImgs(((d && d.data && d.data.images) || []).filter((i) => {
if (!i || !i.path) return false;
const t = String(i.fileType || i.type || '').toLowerCase();
if (t === 'video') return false;
const ext = String(i.filename || i.path).split('.').pop().toLowerCase();
return !VIDEO_EXT.includes(ext);
}));
} catch (_) {
setLibImgs([]);
} finally {
setLibLoading(false);
}
};
useEffect(() => { if (libraryId) loadImages(''); }, [libraryId]);
const togglePick = (img) => {
setPicked((list) => {
const i = list.findIndex((x) => x.path === img.path);
if (i >= 0) return list.filter((x) => x.path !== img.path);
return [...list, img];
});
};
const poll = (id) => {
const iv = setInterval(async () => {
try {
const r = await fetch(`/api/video/task/${id}`, { headers: { Authorization: `Bearer ${getToken()}` } });
if (!r.ok) return;
const d = await r.json();
setTask(d);
if (d.status === 'done' || d.status === 'error') {
clearInterval(iv);
if (d.status === 'done') setTimeout(() => { onDone && onDone(d.resultPath); onClose(); }, 1200);
}
} catch (_) {}
}, 1500);
timerRef.current = iv;
};
const handleExtractUrl = async () => {
setExtracting(true); setError('');
try {
const r = await fetch('/api/video/extract-url', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }, body: JSON.stringify({ url }) });
const d = await r.json();
if (!r.ok || d.error) throw new Error(errText(d.error, `失败 (${r.status})`));
setExtracted(d);
if (!title) setTitle(d.title || '');
setContent(d.text || '');
} catch (e) { setError(e.message); }
finally { setExtracting(false); }
};
const handleExtractDoc = async () => {
if (!file) return;
setExtracting(true); setError('');
try {
const fd = new FormData(); fd.append('file', file);
const r = await fetch('/api/video/extract-doc', { method: 'POST', headers: { Authorization: `Bearer ${getToken()}` }, body: fd });
const d = await r.json();
if (!r.ok || d.error) throw new Error(errText(d.error, `失败 (${r.status})`));
setExtracted(d);
if (!title) setTitle(d.title || '');
setContent(d.text || '');
} catch (e) { setError(e.message); }
finally { setExtracting(false); }
};
const handleStart = async () => {
setError('');
if (!title.trim()) { setError('请填写视频标题'); return; }
if (tab === 'images' && picked.length === 0) { setError('请先在「素材库图片」里选择至少 1 张'); return; }
setStarting(true);
try {
const imgs = picked.length
? picked.map((i) => ({ path: i.path, filename: i.filename, width: i.width, height: i.height }))
: ((extracted && extracted.images) || []);
const body = {
libraryId, title: title.trim(),
content: content.trim(),
images: imgs,
voice, resolution, extraPrompt: '',
subtitleStyle: { position: subtitlePos, color: subtitleColor, fontSizePct: subtitleSize }
};
const r = await fetch('/api/video/aigenerate-text', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }, body: JSON.stringify(body) });
const d = await r.json().catch(() => ({}));
if (!r.ok || d.error) throw new Error(errText(d.error, `启动失败 (${r.status})`));
setTaskId(d.taskId); poll(d.taskId);
} catch (e) { setError(e.message || '启动失败'); }
finally { setStarting(false); }
};
const running = !!taskId && task && task.status === 'running';
const failed = task && task.status === 'error';
const done = task && task.status === 'done';
const input = 'w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent';
return (
<div className="fixed inset-0 z-50 bg-black bg-opacity-60 flex items-center justify-center p-4" onClick={(running||starting)?undefined:onClose}>
<div className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-2xl max-h-[92vh] overflow-y-auto" onClick={(e)=>e.stopPropagation()}>
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-2">
<Film className="w-5 h-5 text-purple-500" />
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">AI 一键生成视频</h2>
</div>
<button onClick={onClose} disabled={running||starting} className="p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded"><X className="w-5 h-5 text-gray-500" /></button>
</div>
<div className="p-5 space-y-4">
{/* tabs */}
<div className="flex gap-2 border-b border-gray-200 dark:border-gray-700 pb-2">
{[
{ k: 'prompt', l: '提示词', icon: Sparkles },
{ k: 'url', l: '链接抓取', icon: LinkIcon },
{ k: 'doc', l: '文档/PDF', icon: FileText },
{ k: 'images', l: '素材库图片', icon: ImageIcon },
].map(({ k, l, icon: Icon }) => (
<button key={k} onClick={() => setTab(k)} className={`flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm ${tab===k ? 'bg-purple-600 text-white' : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'}`}>
<Icon className="w-4 h-4" /> {l}
{k === 'images' && picked.length > 0 && <span className="ml-0.5 text-[10px] px-1 rounded bg-white/25">{picked.length}</span>}
</button>
))}
</div>
{tab === 'prompt' && (
<div className="space-y-3">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">常用热门提示词</label>
<div className="flex flex-wrap gap-2">
{POPULAR_PROMPTS.map((p) => (
<button key={p} onClick={() => { setContent(p); if (!title) setTitle(p.slice(0, 20)); }} className="px-3 py-1 text-xs rounded-full bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-purple-100 dark:hover:bg-purple-900/40">
{p}
</button>
))}
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">提示词 / 内容</label>
<textarea className={input} rows={4} value={content} onChange={(e) => setContent(e.target.value)} placeholder="描述你想要的视频内容…" />
</div>
</div>
)}
{tab === 'url' && (
<div className="space-y-3">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">网页链接</label>
<div className="flex gap-2">
<input className={input} value={url} onChange={(e) => setUrl(e.target.value)} placeholder="https://..." />
<button onClick={handleExtractUrl} disabled={extracting || !url} className="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm disabled:opacity-50">
{extracting ? '抓取中…' : '抓取'}
</button>
</div>
</div>
{extracted && <p className="text-xs text-green-600">已抓取:{extracted.title}({extracted.images?.length || 0} 张图)</p>}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">内容预览</label>
<textarea className={input} rows={4} value={content} onChange={(e) => setContent(e.target.value)} />
</div>
</div>
)}
{tab === 'doc' && (
<div className="space-y-3">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">上传 PDF / 文档</label>
<input type="file" accept=".pdf,.txt,.md,.doc,.docx" onChange={(e) => setFile(e.target.files?.[0] || null)} />
<button onClick={handleExtractDoc} disabled={extracting || !file} className="mt-2 px-4 py-2 bg-blue-600 text-white rounded-lg text-sm disabled:opacity-50">
{extracting ? '识别中…' : 'AI 识别'}
</button>
</div>
{extracted && <p className="text-xs text-green-600">已识别:{extracted.title}</p>}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">内容预览</label>
<textarea className={input} rows={4} value={content} onChange={(e) => setContent(e.target.value)} />
</div>
</div>
)}
{tab === 'images' && (
<div className="space-y-3">
<div className="flex items-center gap-2">
<div className="relative flex-1">
<Search className="w-4 h-4 text-gray-400 absolute left-2.5 top-1/2 -translate-y-1/2" />
<input
className={`${input} pl-8`}
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') loadImages(keyword); }}
placeholder="搜索素材库图片(回车)"
/>
</div>
<button onClick={() => loadImages(keyword)} className="px-3 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">搜索</button>
{picked.length > 0 && (
<button onClick={() => setPicked([])} className="px-3 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-600 text-gray-500 hover:bg-gray-50 dark:hover:bg-gray-700">清空</button>
)}
</div>
<div className="max-h-64 overflow-y-auto rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/40 p-2">
{libLoading && <div className="py-8 text-center text-sm text-gray-500"><Loader2 className="w-4 h-4 animate-spin inline mr-1" />加载图片…</div>}
{!libLoading && libImgs.length === 0 && <div className="py-8 text-center text-sm text-gray-500">这个素材库还没有图片</div>}
{!libLoading && libImgs.length > 0 && (
<div className="grid grid-cols-4 sm:grid-cols-5 gap-2">
{libImgs.map((img) => {
const on = picked.some((x) => x.path === img.path);
return (
<button
key={img.path}
onClick={() => togglePick(img)}
title={img.filename || img.path}
className={`relative aspect-square rounded-lg overflow-hidden border-2 ${on ? 'border-purple-500 ring-2 ring-purple-300' : 'border-transparent hover:border-gray-300'}`}
>
<img src={thumbUrl(libraryId, img)} alt={img.filename || ''} className="w-full h-full object-cover" />
{on && (
<span className="absolute top-1 right-1 w-5 h-5 rounded-full bg-purple-600 text-white flex items-center justify-center">
<Check className="w-3.5 h-3.5" />
</span>
)}
{on && (
<span className="absolute bottom-0 left-0 right-0 bg-purple-600/85 text-white text-[10px] py-0.5 truncate px-1">
#{picked.findIndex((x) => x.path === img.path) + 1}
</span>
)}
</button>
);
})}
</div>
)}
</div>
<p className="text-xs text-gray-500 dark:text-gray-400">
已选 {picked.length} 张(按点击顺序作为画面顺序);不选则按内容自动配图。
</p>
<textarea className={input} rows={2} value={content} onChange={(e) => setContent(e.target.value)} placeholder="补充说明(可选):想表达的主题、语气…" />
</div>
)}
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">视频标题</label>
<input className={input} value={title} onChange={(e) => setTitle(e.target.value)} placeholder="例如:产品速览 / 探店 vlog" maxLength={60} disabled={running||done} />
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">朗读音色</label>
<select className={input} value={voice} onChange={(e) => setVoice(e.target.value)} disabled={running||done}>
{VOICES.map((v) => <option key={v.key} value={v.key}>{v.label}</option>)}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">画幅</label>
<select className={input} value={resolution} onChange={(e) => setResolution(e.target.value)} disabled={running||done}>
{RESOLUTIONS.map((r) => <option key={r.key} value={r.key}>{r.label}</option>)}
</select>
</div>
</div>
<div className="grid grid-cols-3 gap-3">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">字幕位置</label>
<select className={input} value={subtitlePos} onChange={(e) => setSubtitlePos(e.target.value)} disabled={running||done}>
{SUBTITLE_STYLES.map((s) => <option key={s.key} value={s.key}>{s.label}</option>)}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">字幕颜色</label>
<select className={input} value={subtitleColor} onChange={(e) => setSubtitleColor(e.target.value)} disabled={running||done}>
{SUBTITLE_COLORS.map((c) => <option key={c.key} value={c.key}>{c.label}</option>)}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">字幕字号</label>
<input type="range" min={3} max={8} value={subtitleSize} onChange={(e) => setSubtitleSize(parseInt(e.target.value))} disabled={running||done} className="w-full" />
</div>
</div>
<div className="flex items-start gap-2 rounded-lg bg-gray-50 dark:bg-gray-900/50 border border-gray-200 dark:border-gray-700 px-3 py-2 text-xs text-gray-600 dark:text-gray-400">
<Settings className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />
<span>提供商 / 模型 / KEY 在右上角「设置 → AI 视频」里配置,普通文本模型即可;配音与字幕由本地合成。</span>
</div>
{(running || done || failed) && (
<div className={`rounded-lg border px-4 py-3 ${failed ? 'border-red-200 bg-red-50 dark:bg-red-900/20' : done ? 'border-green-200 bg-green-50 dark:bg-green-900/20' : 'border-blue-200 bg-blue-50 dark:bg-blue-900/20'}`}>
<div className="flex items-center gap-2 text-sm">
{failed ? <AlertCircle className="w-4 h-4 text-red-500" /> : done ? <CheckCircle2 className="w-4 h-4 text-green-500" /> : <Loader2 className="w-4 h-4 animate-spin text-blue-500" />}
<span className={`font-medium ${failed ? 'text-red-700 dark:text-red-300' : done ? 'text-green-700 dark:text-green-300' : 'text-blue-700 dark:text-blue-300'}`}>
{failed ? '生成失败' : done ? '生成完成' : (task?.stepLabel || '处理中')}
</span>
{running && <span className="ml-auto text-xs text-blue-600 dark:text-blue-300">{task?.progress || 0}%</span>}
</div>
{running && <div className="mt-2 h-1.5 bg-blue-100 dark:bg-blue-900/50 rounded-full overflow-hidden"><div className="h-full bg-blue-500 rounded-full transition-all" style={{ width: `${task?.progress || 0}%` }} /></div>}
{failed && <p className="mt-1 text-xs text-red-600 dark:text-red-400">{task?.error}</p>}
{done && task?.resultPath && <p className="mt-1 text-xs text-green-600 dark:text-green-400">已保存:{task.resultPath}</p>}
</div>
)}
{error && <div className="text-sm text-red-600 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-lg px-3 py-2">{error}</div>}
<div className="flex justify-end gap-3 pt-1">
<button onClick={onClose} disabled={running||starting} className="px-4 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50">
{done ? '关闭' : '取消'}
</button>
{!running && !done && (
<button onClick={handleStart} disabled={starting} className="px-5 py-2 text-sm rounded-lg bg-purple-600 hover:bg-purple-700 text-white font-medium disabled:opacity-50 flex items-center gap-2">
{starting && <Loader2 className="w-4 h-4 animate-spin" />}
{starting ? '启动中…' : '一键生成'}
</button>
)}
</div>
</div>
</div>
</div>
);
}
+12 -1
View File
@@ -1,5 +1,5 @@
import { useState, useEffect, useMemo, useRef } from 'react';
import { Sun, Moon, Search, Filter, Sliders, RefreshCw, ScanLine, Star, Bell, Github, Settings, ExternalLink, Wand2 } from 'lucide-react';
import { Sun, Moon, Search, Filter, Sliders, RefreshCw, ScanLine, Star, Bell, Github, Settings, ExternalLink, Wand2, Film } from 'lucide-react';
import { useLibraryStore } from '../stores/useLibraryStore';
import { useImageStore } from '../stores/useImageStore';
import { useUIStore } from '../stores/useUIStore';
@@ -9,6 +9,7 @@ import { useHub } from '../hooks/useHub';
import { libraryAPI, scanAPI, watchAPI } from '../api';
import SettingsModal from './SettingsModal';
import AIGenModal from './AIGenModal';
import AIVideoStudioModal from './AIVideoStudioModal';
import { createLogger } from '../utils/logger';
const logger = createLogger('Header');
@@ -33,6 +34,7 @@ function Header() {
const [showSettings, setShowSettings] = useState(false);
const [settingsTab, setSettingsTab] = useState('ocr');
const [showAIGen, setShowAIGen] = useState(false);
const [showAIVideo, setShowAIVideo] = useState(false);
const searchDebounceRef = useRef(null);
// 授权系统 hub:版本 / 公告 / 在线人数
@@ -410,6 +412,14 @@ function Header() {
)}
</div>
<button
onClick={() => setShowAIVideo(true)}
title="AI 生成视频"
className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
>
<Film className="w-5 h-5 text-purple-600 dark:text-purple-400" />
</button>
<button
onClick={() => setShowAIGen(true)}
title="AI 生图"
@@ -432,6 +442,7 @@ function Header() {
<SettingsModal open={showSettings} onClose={() => setShowSettings(false)} versionLabel={appVersion} initialTab={settingsTab} />
<AIGenModal open={showAIGen} onClose={() => setShowAIGen(false)} />
{showAIVideo && <AIVideoStudioModal libraryId={currentLibraryId} onClose={() => setShowAIVideo(false)} onDone={() => { setShowAIVideo(false); window.location.reload(); }} />}
</>
);
+123 -2
View File
@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react';
import { X, ScanText, Info, Save, FlaskConical, Github, ExternalLink, Wand2 } from 'lucide-react';
import { X, ScanText, Info, Save, FlaskConical, Github, ExternalLink, Wand2, Film } from 'lucide-react';
import { settingsAPI } from '../api';
const APP_VERSION = 'v1.4.8';
@@ -17,6 +17,8 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
const [ig, setIg] = useState(null); // imagegen 配置
const [igNewKey, setIgNewKey] = useState(''); // NewAPI 新密钥
const [igCustomKey, setIgCustomKey] = useState(''); // 自定义提供商新密钥
const [va, setVa] = useState(null); // AI 视频文本模型配置
const [vaKey, setVaKey] = useState(''); // AI 视频新密钥
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false);
const [msg, setMsg] = useState(null); // { type, text }
@@ -28,6 +30,7 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
setApiKeyInput('');
setIgNewKey('');
setIgCustomKey('');
setVaKey('');
settingsAPI.getSettings()
.then((d) => { setCfg({
provider: d?.provider || 'local',
@@ -51,6 +54,15 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
apiKeyMasked: d?.imagegen?.custom?.apiKeyMasked || ''
}
});
setVa({
provider: d?.videoai?.provider === 'custom' ? 'custom' : 'inherit',
custom: {
url: d?.videoai?.custom?.url || '',
model: d?.videoai?.custom?.model || '',
apiKeyMasked: d?.videoai?.custom?.apiKeyMasked || '',
configured: !!d?.videoai?.custom?.configured
}
});
})
.catch((e) => setMsg({ type: 'error', text: '读取设置失败: ' + (e.data?.message || e.message) }));
}, [open]);
@@ -85,6 +97,16 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
apiKey: igCustomKey || ''
}
}
} : {}),
...(va ? {
videoai: {
provider: va.provider,
custom: {
url: va.custom.url,
model: va.custom.model,
apiKey: vaKey || ''
}
}
} : {})
};
const data = await settingsAPI.updateSettings(payload);
@@ -105,8 +127,20 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
});
}
setApiKeyInput('');
if (data?.videoai) {
setVa({
provider: data.videoai.provider === 'custom' ? 'custom' : 'inherit',
custom: {
url: data.videoai.custom?.url || '',
model: data.videoai.custom?.model || '',
apiKeyMasked: data.videoai.custom?.apiKeyMasked || '',
configured: !!data.videoai.custom?.configured
}
});
}
setIgNewKey('');
setIgCustomKey('');
setVaKey('');
setMsg({ type: 'ok', text: '已保存,新配置立即生效' });
} catch (e) {
setMsg({ type: 'error', text: '保存失败: ' + (e.data?.message || e.message) });
@@ -142,6 +176,7 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
const menus = [
{ key: 'ocr', label: 'OCR 识别', icon: ScanText },
{ key: 'aigen', label: 'AI 生图', icon: Wand2 },
{ key: 'videoai', label: 'AI 视频', icon: Film },
{ key: 'about', label: '关于', icon: Info }
];
@@ -174,7 +209,7 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
<div className="flex-1 p-6 overflow-y-auto">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">
{active === 'ocr' ? 'OCR 识别设置' : active === 'aigen' ? 'AI 生图设置' : '关于'}
{active === 'ocr' ? 'OCR 识别设置' : active === 'aigen' ? 'AI 生图设置' : active === 'videoai' ? 'AI 视频设置' : '关于'}
</h2>
<button onClick={onClose} className="p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">
<X className="w-5 h-5 text-gray-500" />
@@ -395,6 +430,92 @@ export default function SettingsModal({ open, onClose, versionLabel, initialTab
</div>
)}
{active === 'videoai' && cfg && va && (
<div className="space-y-5">
<p className="text-xs text-gray-500 dark:text-gray-400">
AI 视频用这个模型来写分镜脚本、把提示词/网页/文档内容组织成讲解稿(普通文本模型即可,无需多模态)。
配音、字幕与成片合成由服务器本地完成。密钥只保存在本机,不出服务器。
</p>
<div>
<div className="text-xs font-medium text-gray-600 dark:text-gray-400 mb-2">文本模型来源</div>
<div className="space-y-2">
<label className="flex items-start gap-2.5 p-3 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50">
<input
type="radio"
className="mt-0.5"
checked={va.provider === 'inherit'}
onChange={() => setVa((v) => ({ ...v, provider: 'inherit' }))}
/>
<span>
<span className="block text-sm font-medium text-gray-900 dark:text-white">复用「AI 生图」配置(推荐)</span>
<span className="block text-xs text-gray-500 dark:text-gray-400 mt-0.5">用上面 AI 生图里的地址与 Key,无需重复填写</span>
</span>
</label>
<label className="flex items-start gap-2.5 p-3 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50">
<input
type="radio"
className="mt-0.5"
checked={va.provider === 'custom'}
onChange={() => setVa((v) => ({ ...v, provider: 'custom' }))}
/>
<span>
<span className="block text-sm font-medium text-gray-900 dark:text-white">单独配置提供商 / 模型 / Key</span>
<span className="block text-xs text-gray-500 dark:text-gray-400 mt-0.5">任意 OpenAI 兼容 /v1/chat/completions 的文本模型</span>
</span>
</label>
</div>
</div>
{va.provider === 'custom' && (
<div className="space-y-3 p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg border border-gray-200 dark:border-gray-700">
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">接口地址(BASE URL)</label>
<input
type="text"
value={va.custom.url}
onChange={(e) => setVa((v) => ({ ...v, custom: { ...v.custom, url: e.target.value } }))}
placeholder="https://api.openai.com/v1 或 http://192.168.68.19:3099/v1"
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">模型名称</label>
<input
type="text"
value={va.custom.model}
onChange={(e) => setVa((v) => ({ ...v, custom: { ...v.custom, model: e.target.value } }))}
placeholder="mimo-v2.6-flash / gpt-4o-mini / qwen-plus ..."
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">API Key</label>
<input
type="password"
value={vaKey}
onChange={(e) => setVaKey(e.target.value)}
placeholder={va.custom.apiKeyMasked ? `已配置(${va.custom.apiKeyMasked}),留空保持不变` : 'sk-... 或中转站 48 位令牌'}
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
/>
</div>
</div>
)}
<div className="flex items-center gap-3">
<button
onClick={handleSave}
disabled={saving}
className="flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg disabled:opacity-50"
>
<Save className="w-4 h-4" />
{saving ? '保存中...' : '保存'}
</button>
<span className="text-xs text-gray-400 dark:text-gray-500">保存后立即生效,无需重启</span>
</div>
</div>
)}
{active === 'about' && (
<div className="space-y-4 text-sm">
<div className="flex items-center justify-between py-2 border-b border-gray-100 dark:border-gray-700">