Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
+213
View File
@@ -0,0 +1,213 @@
/*
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 { useCallback, useEffect, useRef, useState } from 'react';
import { API } from '../../helpers';
const errorCode = (error) => error?.response?.data?.error?.code || '';
const errorMessage = (error) =>
error?.response?.data?.error?.message || error?.message || '请求失败';
const readFileAsDataURL = (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(file);
});
export const usePortraitAssets = (open) => {
const [enabled, setEnabled] = useState(null);
const [loading, setLoading] = useState(false);
const [portraits, setPortraits] = useState([]);
const [assets, setAssets] = useState([]);
const [session, setSession] = useState(null);
const pollingRef = useRef(null);
const load = useCallback(async () => {
setLoading(true);
try {
const [portraitRes, assetRes] = await Promise.all([
API.get('/api/video/portraits', { skipErrorHandler: true }),
API.get('/api/video/assets?limit=100', { skipErrorHandler: true }),
]);
setEnabled(true);
setPortraits(portraitRes.data?.data || []);
setAssets(
(assetRes.data?.data || []).filter(
(asset) => asset.identity_type === 'real_person',
),
);
} catch (error) {
if (errorCode(error) === 'real_portrait_disabled') {
setEnabled(false);
} else {
throw error;
}
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
if (open) load().catch(() => {});
}, [open, load]);
const stopPolling = useCallback(() => {
if (pollingRef.current) {
clearInterval(pollingRef.current);
pollingRef.current = null;
}
}, []);
useEffect(() => stopPolling, [stopPolling]);
const createPortrait = useCallback(
async (name) => {
const response = await API.post(
'/api/video/portraits',
{
name,
consent_accepted: true,
consent_version: '2026-08-20',
},
{ skipErrorHandler: true },
);
await load();
return response.data;
},
[load],
);
const pollVerification = useCallback(
(sessionId) => {
stopPolling();
pollingRef.current = setInterval(async () => {
try {
const response = await API.get(
`/api/video/portrait-verifications/${sessionId}`,
{ skipErrorHandler: true, disableDuplicate: true },
);
const next = response.data;
setSession((current) => ({ ...current, ...next }));
if (
['succeeded', 'failed', 'expired', 'superseded'].includes(
next.status,
)
) {
stopPolling();
await load();
}
} catch {
// The next poll retries transient browser or gateway failures.
}
}, 2500);
},
[load, stopPolling],
);
const startVerification = useCallback(
async (portraitId) => {
const response = await API.post(
`/api/video/portraits/${portraitId}/verification-sessions`,
{},
{ skipErrorHandler: true },
);
setSession(response.data);
pollVerification(response.data.session_id);
return response.data;
},
[pollVerification],
);
const uploadPortraitAsset = useCallback(
async (portraitId, file) => {
const image = await readFileAsDataURL(file);
const response = await API.post(
'/api/video/assets',
{
portrait_id: portraitId,
image,
name: file.name,
asset_type: 'Image',
},
{ skipErrorHandler: true },
);
await load();
return response.data;
},
[load],
);
const refreshAssetUntilTerminal = useCallback(
async (assetId) => {
for (let attempt = 0; attempt < 90; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 2000));
const response = await API.get(`/api/video/assets/${assetId}`, {
skipErrorHandler: true,
disableDuplicate: true,
});
if (response.data?.status !== 'processing') {
await load();
return response.data;
}
}
await load();
return null;
},
[load],
);
const deleteAsset = useCallback(
async (assetId) => {
await API.delete(`/api/video/assets/${assetId}`, {
skipErrorHandler: true,
});
await load();
},
[load],
);
const deletePortrait = useCallback(
async (portraitId) => {
await API.delete(`/api/video/portraits/${portraitId}`, {
skipErrorHandler: true,
});
setSession(null);
await load();
},
[load],
);
return {
enabled,
loading,
portraits,
assets,
session,
setSession,
createPortrait,
startVerification,
uploadPortraitAsset,
refreshAssetUntilTerminal,
deleteAsset,
deletePortrait,
errorMessage,
};
};
+369
View File
@@ -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(用于播放)
};
};