Initial import of weiyuan frontend
This commit is contained in:
@@ -0,0 +1,369 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API, showError, showSuccess, showInfo } from '../../helpers';
|
||||
import { DEFAULT_FORM_DATA } from '../../constants/video-generation.constant';
|
||||
import {
|
||||
canCancelVideoTask,
|
||||
canRegenerateVideoTask,
|
||||
getVideoURLFromDetail,
|
||||
normalizeExperienceVideoError,
|
||||
normalizeVideoTaskStatus,
|
||||
} from '../../helpers/videoTask';
|
||||
|
||||
const DRAFT_STORAGE_KEY = 'video_generation_draft_v2';
|
||||
const POLLING_INTERVAL = 3000; // 轮询间隔(毫秒)
|
||||
|
||||
export const useVideoGeneration = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// 表单数据
|
||||
const [formData, setFormData] = useState(() => {
|
||||
// 从 localStorage 加载草稿
|
||||
const draft = localStorage.getItem(DRAFT_STORAGE_KEY);
|
||||
return draft ? JSON.parse(draft) : DEFAULT_FORM_DATA;
|
||||
});
|
||||
|
||||
// 模型相关 - selectedModel 现在是完整的模型对象(也兼容字符串)
|
||||
const [selectedModel, setSelectedModel] = useState(null);
|
||||
|
||||
// 从选中的模型对象生成 modelInfo
|
||||
// 如果 selectedModel 是字符串(从 retryTask 来的),则 modelInfo 为 null
|
||||
const modelInfo =
|
||||
selectedModel && typeof selectedModel === 'object'
|
||||
? {
|
||||
provider: selectedModel.vendor || selectedModel.provider || '未知',
|
||||
description: selectedModel.description || '',
|
||||
features: selectedModel.features || [],
|
||||
maxDuration: selectedModel.maxDuration || 10,
|
||||
maxResolution: selectedModel.maxResolution || '1080P',
|
||||
audioSupport: selectedModel.audioSupport || false,
|
||||
price: selectedModel.model_price || selectedModel.price || '0.00',
|
||||
}
|
||||
: null;
|
||||
|
||||
// 生成相关
|
||||
const [generating, setGenerating] = useState(false);
|
||||
const [currentTask, setCurrentTask] = useState(null);
|
||||
|
||||
// 任务列表
|
||||
const [tasks, setTasks] = useState([]);
|
||||
|
||||
// 轮询引用
|
||||
const pollingTimerRef = useRef(null);
|
||||
|
||||
// 自动保存草稿
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
localStorage.setItem(DRAFT_STORAGE_KEY, JSON.stringify(formData));
|
||||
}, 1000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [formData]);
|
||||
|
||||
// 加载任务列表
|
||||
const loadTasks = useCallback(async () => {
|
||||
try {
|
||||
const res = await API.get('/api/video/tasks');
|
||||
if (res?.data?.success) {
|
||||
setTasks(res.data.data?.items || []);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load tasks:', error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 初始加载
|
||||
useEffect(() => {
|
||||
loadTasks();
|
||||
}, [loadTasks]);
|
||||
|
||||
// 轮询任务状态
|
||||
const startPolling = useCallback(
|
||||
(taskId) => {
|
||||
if (pollingTimerRef.current) {
|
||||
clearInterval(pollingTimerRef.current);
|
||||
}
|
||||
|
||||
pollingTimerRef.current = setInterval(async () => {
|
||||
try {
|
||||
const res = await API.get(`/api/video/tasks/${taskId}`);
|
||||
if (res?.data?.success) {
|
||||
const task = res.data.data;
|
||||
setCurrentTask(task);
|
||||
|
||||
const normalizedStatus = normalizeVideoTaskStatus(task.status);
|
||||
|
||||
// 如果任务完成或失败,停止轮询
|
||||
// 支持 'completed'/'success' 和 'failed'/'failure' 两种格式
|
||||
if (
|
||||
normalizedStatus === 'success' ||
|
||||
normalizedStatus === 'failure'
|
||||
) {
|
||||
setGenerating(false);
|
||||
clearInterval(pollingTimerRef.current);
|
||||
pollingTimerRef.current = null;
|
||||
|
||||
// 刷新任务列表
|
||||
loadTasks();
|
||||
|
||||
// 显示通知
|
||||
if (normalizedStatus === 'success') {
|
||||
showSuccess(t('视频生成成功!'));
|
||||
} else if (normalizedStatus === 'failure') {
|
||||
showError(
|
||||
t('视频生成失败: ') + (task.fail_reason || t('未知错误')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to poll task status:', error);
|
||||
}
|
||||
}, POLLING_INTERVAL);
|
||||
},
|
||||
[loadTasks, t],
|
||||
);
|
||||
|
||||
// 停止轮询
|
||||
const stopPolling = useCallback(() => {
|
||||
if (pollingTimerRef.current) {
|
||||
clearInterval(pollingTimerRef.current);
|
||||
pollingTimerRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 清理定时器
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
stopPolling();
|
||||
};
|
||||
}, [stopPolling]);
|
||||
|
||||
const submitVideo = useCallback(
|
||||
async (requestData, model = selectedModel) => {
|
||||
if (!requestData.prompt) {
|
||||
showError(t('请输入提示词或选择场景模板'));
|
||||
return false;
|
||||
}
|
||||
if (!model) {
|
||||
showError(t('请选择模型'));
|
||||
return false;
|
||||
}
|
||||
if (typeof model === 'object' && model.level_locked) {
|
||||
showError(t('当前等级无权调用此模型,请选择其他模型'));
|
||||
return false;
|
||||
}
|
||||
if (requestData.mode === 'image2video' && !requestData.image) {
|
||||
showError(t('请上传首帧图片'));
|
||||
return false;
|
||||
}
|
||||
|
||||
const modelName =
|
||||
typeof model === 'object' ? model.model_name || model.id : model;
|
||||
setGenerating(true);
|
||||
try {
|
||||
const res = await API.post('/api/video/generate', {
|
||||
...requestData,
|
||||
model: modelName,
|
||||
});
|
||||
if (!res?.data?.success) {
|
||||
throw res?.data || new Error(t('提交失败'));
|
||||
}
|
||||
const task = res.data.data;
|
||||
setCurrentTask(task);
|
||||
showInfo(t('视频生成任务已提交,请稍候...'));
|
||||
startPolling(task.task_id);
|
||||
return true;
|
||||
} catch (error) {
|
||||
setGenerating(false);
|
||||
const normalized = normalizeExperienceVideoError(error, t('提交失败'));
|
||||
showError(`${t('提交失败')}: ${normalized.message}`);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[selectedModel, startPolling, t],
|
||||
);
|
||||
|
||||
// 生成视频
|
||||
const handleGenerate = useCallback(async () => {
|
||||
if (!formData.prompt && !formData.selectedTemplate) {
|
||||
showError(t('请输入提示词或选择场景模板'));
|
||||
return;
|
||||
}
|
||||
|
||||
let finalPrompt = formData.prompt;
|
||||
if (formData.selectedTemplate) {
|
||||
finalPrompt =
|
||||
formData.selectedTemplate +
|
||||
(formData.prompt ? '\n' + formData.prompt : '');
|
||||
}
|
||||
const requestData = {
|
||||
mode: formData.mode,
|
||||
prompt: finalPrompt,
|
||||
negative_prompt: formData.negative_prompt,
|
||||
resolution: formData.resolution,
|
||||
duration: formData.duration,
|
||||
fps: formData.fps,
|
||||
ratio: formData.ratio,
|
||||
audio: formData.audio,
|
||||
seed: formData.seed === -1 ? null : formData.seed,
|
||||
prompt_extend: formData.prompt_extend,
|
||||
watermark: formData.watermark,
|
||||
};
|
||||
|
||||
// 如果是图生视频,添加图片
|
||||
if (formData.mode === 'image2video' && formData.image) {
|
||||
requestData.image = formData.image;
|
||||
}
|
||||
await submitVideo(requestData, selectedModel);
|
||||
}, [formData, selectedModel, submitVideo, t]);
|
||||
|
||||
// 取消生成
|
||||
const handleCancel = useCallback(async () => {
|
||||
if (!currentTask?.task_id || !canCancelVideoTask(currentTask)) return;
|
||||
|
||||
try {
|
||||
const res = await API.post(
|
||||
`/api/video/tasks/${currentTask.task_id}/cancel`,
|
||||
);
|
||||
|
||||
if (res?.data?.success) {
|
||||
showSuccess(t('已取消任务'));
|
||||
setGenerating(false);
|
||||
stopPolling();
|
||||
setCurrentTask(null);
|
||||
loadTasks();
|
||||
} else {
|
||||
throw new Error(res?.data?.message || t('取消失败'));
|
||||
}
|
||||
} catch (error) {
|
||||
showError(t('取消失败: ') + (error.message || error));
|
||||
}
|
||||
}, [currentTask, t, stopPolling, loadTasks]);
|
||||
|
||||
// 刷新任务列表
|
||||
const refreshTasks = useCallback(() => {
|
||||
loadTasks();
|
||||
}, [loadTasks]);
|
||||
|
||||
// 删除任务
|
||||
const deleteTask = useCallback(
|
||||
async (taskId) => {
|
||||
try {
|
||||
const res = await API.delete(`/api/video/tasks/${taskId}`);
|
||||
|
||||
if (res?.data?.success) {
|
||||
showSuccess(t('任务已删除'));
|
||||
loadTasks();
|
||||
} else {
|
||||
throw new Error(res?.data?.message || t('删除失败'));
|
||||
}
|
||||
} catch (error) {
|
||||
showError(t('删除失败: ') + (error.message || error));
|
||||
}
|
||||
},
|
||||
[t, loadTasks],
|
||||
);
|
||||
|
||||
const getRegenerationTask = useCallback(
|
||||
async (taskId) => {
|
||||
try {
|
||||
const res = await API.get(`/api/video/tasks/${taskId}`);
|
||||
const task = res?.data?.data;
|
||||
if (!res?.data?.success || !canRegenerateVideoTask(task)) {
|
||||
showError(t('该任务不支持再生成'));
|
||||
return null;
|
||||
}
|
||||
return task;
|
||||
} catch (error) {
|
||||
const normalized = normalizeExperienceVideoError(
|
||||
error,
|
||||
t('获取任务失败'),
|
||||
);
|
||||
showError(normalized.message);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
[t],
|
||||
);
|
||||
|
||||
// 获取任务的最新视频URL(用于播放/下载)
|
||||
const getTaskVideoUrl = useCallback(async (taskId) => {
|
||||
try {
|
||||
const res = await API.get(`/api/video/tasks/${taskId}`);
|
||||
if (res?.data?.success) {
|
||||
const taskData = res.data.data;
|
||||
const data = taskData?.data;
|
||||
if (data && typeof data === 'object') {
|
||||
return getVideoURLFromDetail(taskData);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to get task video url:', error);
|
||||
}
|
||||
return null;
|
||||
}, []);
|
||||
|
||||
// 下载任务
|
||||
const downloadTask = useCallback(
|
||||
async (task) => {
|
||||
// 先获取最新的预签名URL
|
||||
const videoUrl = await getTaskVideoUrl(task.task_id);
|
||||
|
||||
if (videoUrl) {
|
||||
const link = document.createElement('a');
|
||||
link.href = videoUrl;
|
||||
link.download = `video_${task.task_id}.mp4`;
|
||||
link.target = '_blank';
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
showSuccess(t('开始下载'));
|
||||
} else {
|
||||
showError(t('未找到视频URL'));
|
||||
}
|
||||
},
|
||||
[t, getTaskVideoUrl],
|
||||
);
|
||||
|
||||
return {
|
||||
// 表单数据
|
||||
formData,
|
||||
setFormData,
|
||||
// 模型相关
|
||||
selectedModel,
|
||||
setSelectedModel,
|
||||
modelInfo,
|
||||
// 生成相关
|
||||
generating,
|
||||
currentTask,
|
||||
handleGenerate,
|
||||
submitVideo,
|
||||
handleCancel,
|
||||
// 任务列表
|
||||
tasks,
|
||||
refreshTasks,
|
||||
deleteTask,
|
||||
getRegenerationTask,
|
||||
downloadTask,
|
||||
getTaskVideoUrl, // 获取最新的视频URL(用于播放)
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user