- VideoEditModal /api/video/edit、AIVideoModal /api/video/aigenerate+task轮询均裸fetch未带Authorization,后端/api全组401 → 补token头 - 错误信息经errText()解析(对象取message兜底状态码),不再显示[object Object] - MergeCollage拼图找相似接口同样缺token,一并修复 - Sidebar首项文案「全部图片」→「全部」 - 版本4处升v1.4.3
239 lines
11 KiB
React
239 lines
11 KiB
React
/**
|
||
* AI 生成视频弹窗
|
||
* 多选图片 + 标题 + 模型 KEY → 一键生成带字幕和朗读的视频
|
||
* 后端:POST /api/video/aigenerate(异步任务)+ GET /api/video/task/:id 轮询
|
||
*/
|
||
import { useEffect, useRef, useState } from 'react';
|
||
import { X, Loader2, Film, CheckCircle2, AlertCircle, KeyRound } from 'lucide-react';
|
||
import { imageAPI } from '../api';
|
||
import { getToken } from '../api/client';
|
||
|
||
// 后端错误可能为字符串或 {code,message} 对象,统一取可读文本
|
||
const errText = (e, fallback) => {
|
||
if (!e) return fallback;
|
||
if (typeof e === 'string') return e;
|
||
return e.message || JSON.stringify(e);
|
||
};
|
||
|
||
const VOICES = [
|
||
{ 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: '云扬(男声·播音)' },
|
||
{ key: 'zh-TW-HsiaoChenNeural', label: '晓臻(台湾腔)' }
|
||
];
|
||
|
||
const RESOLUTIONS = [
|
||
{ key: '1920x1080', label: '横屏 1920×1080' },
|
||
{ key: '1080x1920', label: '竖屏 1080×1920' },
|
||
{ key: '1280x720', label: '横屏 1280×720' }
|
||
];
|
||
|
||
const STEPS = {
|
||
script: '正在生成分镜脚本',
|
||
tts: '正在朗读配音',
|
||
compose: '正在合成画面',
|
||
merge: '正在合并视频',
|
||
done: '完成'
|
||
};
|
||
|
||
function AIVideoModal({ libraryId, images, onClose, onDone }) {
|
||
const [title, setTitle] = useState('');
|
||
const [apiKey, setApiKey] = useState('');
|
||
const [showKey, setShowKey] = useState(false);
|
||
const [voice, setVoice] = useState(VOICES[0].key);
|
||
const [resolution, setResolution] = useState('1920x1080');
|
||
const [extraPrompt, setExtraPrompt] = useState('');
|
||
|
||
const [taskId, setTaskId] = useState('');
|
||
const [task, setTask] = useState(null);
|
||
const [error, setError] = useState('');
|
||
const [starting, setStarting] = useState(false);
|
||
const timerRef = useRef(null);
|
||
|
||
const list = Array.isArray(images) ? images : [];
|
||
|
||
// 轮询任务进度
|
||
useEffect(() => {
|
||
if (!taskId) return;
|
||
timerRef.current = setInterval(async () => {
|
||
try {
|
||
const res = await fetch(`/api/video/task/${taskId}`, {
|
||
headers: { Authorization: `Bearer ${getToken()}` }
|
||
});
|
||
if (!res.ok) return;
|
||
const data = await res.json();
|
||
setTask(data);
|
||
if (data.status === 'done' || data.status === 'error') {
|
||
clearInterval(timerRef.current);
|
||
if (data.status === 'done') {
|
||
setTimeout(() => { onDone && onDone(data.resultPath); onClose(); }, 1200);
|
||
}
|
||
}
|
||
} catch (_) { /* 网络抖动继续轮询 */ }
|
||
}, 1500);
|
||
return () => timerRef.current && clearInterval(timerRef.current);
|
||
}, [taskId, onDone, onClose]);
|
||
|
||
const handleStart = async () => {
|
||
setError('');
|
||
if (!title.trim()) { setError('请填写视频标题'); return; }
|
||
if (list.length < 2) { setError('请至少选择 2 张图片'); return; }
|
||
setStarting(true);
|
||
try {
|
||
const res = await fetch('/api/video/aigenerate', {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
Authorization: `Bearer ${getToken()}`
|
||
},
|
||
body: JSON.stringify({
|
||
libraryId,
|
||
images: list.map((img) => ({ path: img.path })),
|
||
title: title.trim(),
|
||
apiKey: apiKey.trim(),
|
||
voice,
|
||
resolution,
|
||
extraPrompt: extraPrompt.trim()
|
||
})
|
||
});
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok || data.error) throw new Error(errText(data.error, `启动失败 (${res.status})`));
|
||
setTaskId(data.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 label = 'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1';
|
||
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-lg max-h-[92vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
|
||
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-200 dark:border-gray-700">
|
||
<div className="flex items-center 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>
|
||
<span className="text-xs px-2 py-0.5 rounded-full bg-purple-100 dark:bg-purple-900/40 text-purple-700 dark:text-purple-300">{list.length} 张图片</span>
|
||
</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">
|
||
{/* 图片缩略条 */}
|
||
<div className="flex gap-2 overflow-x-auto pb-1">
|
||
{list.map((img, i) => (
|
||
<div key={img.id || i} className="flex-shrink-0 w-20 h-14 rounded bg-gray-100 dark:bg-gray-700 overflow-hidden relative">
|
||
<img
|
||
src={img.thumbnailPath ? imageAPI.getThumbnailUrl(libraryId, img.thumbnailPath.replace(/\\/g, '/').split('/').pop(), img.modifiedAt) : ''}
|
||
alt={img.filename || ''}
|
||
className="w-full h-full object-cover"
|
||
onError={(e) => { e.target.style.display = 'none'; }}
|
||
/>
|
||
<span className="absolute top-0.5 left-0.5 text-[10px] bg-black bg-opacity-55 text-white px-1 rounded z-10">{i + 1}</span>
|
||
</div>
|
||
))}
|
||
</div>
|
||
|
||
<div>
|
||
<label className={label}>视频标题</label>
|
||
<input className={input} value={title} onChange={(e) => setTitle(e.target.value)} placeholder="例如:周末探店 vlog / 产品功能速览" maxLength={60} disabled={running || done} />
|
||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">AI 将按此标题撰写分镜旁白,成片文件名也用它。</p>
|
||
</div>
|
||
|
||
<div>
|
||
<label className={`${label} flex items-center gap-1`}><KeyRound className="w-3.5 h-3.5" /> 模型 KEY(OpenAI 兼容)</label>
|
||
<div className="relative">
|
||
<input
|
||
type={showKey ? 'text' : 'password'}
|
||
className={`${input} pr-16`}
|
||
value={apiKey}
|
||
onChange={(e) => setApiKey(e.target.value)}
|
||
placeholder="留空则使用服务器已配置的 KEY"
|
||
disabled={running || done}
|
||
/>
|
||
<button type="button" onClick={() => setShowKey(!showKey)} className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 px-1">
|
||
{showKey ? '隐藏' : '显示'}
|
||
</button>
|
||
</div>
|
||
</div>
|
||
|
||
<div className="grid grid-cols-2 gap-3">
|
||
<div>
|
||
<label className={label}>朗读音色</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={label}>画幅</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>
|
||
<label className={label}>补充要求(可选)</label>
|
||
<input className={input} value={extraPrompt} onChange={(e) => setExtraPrompt(e.target.value)} placeholder="例如:语气轻松活泼 / 强调性价比 / 结尾加行动号召" maxLength={100} disabled={running || done} />
|
||
</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 || STEPS[task.step] || '处理中')}
|
||
</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>}
|
||
|
||
<p className="text-xs text-gray-500 dark:text-gray-400">
|
||
流程:AI 写分镜脚本 → 逐段朗读配音 → 图片逐段配字幕合成 → 拼接成片入库。图片越多耗时越长(约 10–60 秒/张)。
|
||
</p>
|
||
|
||
<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>
|
||
);
|
||
}
|
||
|
||
export default AIVideoModal;
|