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
@@ -0,0 +1,905 @@
/*
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 React, { useEffect, useState, useRef } from 'react';
import {
Button,
Col,
Form,
Row,
Spin,
Table,
Modal,
Tag,
Popconfirm,
Space,
Input,
InputNumber,
Switch,
Typography,
} from '@douyinfe/semi-ui';
import { IconPlus, IconDelete, IconEdit } from '@douyinfe/semi-icons';
import {
API,
showError,
showSuccess,
} from '../../../helpers';
import { useTranslation } from 'react-i18next';
// 视频相关的渠道类型
const VIDEO_CHANNEL_TYPES = [
{ value: 1, label: 'OpenAI', provider: 'openai' },
{ value: 17, label: '阿里通义', provider: 'ali' },
{ value: 35, label: 'MiniMax/Hailuo', provider: 'hailuo' },
{ value: 54, label: '豆包视频', provider: 'doubao' },
{ value: 55, label: 'Sora', provider: 'sora' },
];
// 提供商选项
const PROVIDER_OPTIONS = [
{ value: 'openai', label: 'OpenAI 兼容' },
{ value: 'ali', label: '阿里云' },
{ value: 'hailuo', label: 'Hailuo/MiniMax' },
{ value: 'doubao', label: '豆包' },
{ value: 'sora', label: 'Sora' },
];
const defaultVideoModelInputs = {
'video.custom_video_models': '[]',
'video.video_second_pricing': '[]',
'video.asset_library_user_limit': 50,
'video.real_portrait_enabled': false,
};
// 按秒分档:选档字段选项
const TIER_PARAM_OPTIONS = [
{ value: 'resolution', label: '分辨率 (resolution)' },
{ value: 'mode', label: '模式 (mode)' },
{ value: 'size', label: '尺寸 (size)' },
];
export default function SettingVideoModel(props) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
const [, setInputs] = useState(defaultVideoModelInputs);
const [models, setModels] = useState([]);
const [modalVisible, setModalVisible] = useState(false);
const [editingModel, setEditingModel] = useState(null);
const [editingIndex, setEditingIndex] = useState(-1);
const modalFormRef = useRef();
// 解析模型列表
const parseModels = (jsonStr) => {
try {
if (!jsonStr || jsonStr === '[]') return [];
return JSON.parse(jsonStr);
} catch (e) {
return [];
}
};
// 序列化模型列表
const serializeModels = (modelList) => {
return JSON.stringify(modelList);
};
// 保存到服务器
const saveToServer = async (modelList) => {
setLoading(true);
try {
const value = serializeModels(modelList);
const res = await API.put('/api/option/', {
key: 'video.custom_video_models',
value,
});
if (res.data.success) {
showSuccess(t('保存成功'));
props.refresh();
} else {
showError(res.data.message || t('保存失败'));
}
} catch (e) {
showError(t('保存失败,请重试'));
} finally {
setLoading(false);
}
};
// 添加模型
const handleAddModel = () => {
setEditingModel(null);
setEditingIndex(-1);
setModalVisible(true);
};
// 编辑模型
const handleEditModel = (record, index) => {
setEditingModel(record);
setEditingIndex(index);
setModalVisible(true);
};
// 删除模型
const handleDeleteModel = (index) => {
const newModels = [...models];
newModels.splice(index, 1);
setModels(newModels);
saveToServer(newModels);
};
// 切换启用状态
const handleToggleEnabled = (index) => {
const newModels = [...models];
newModels[index].enabled = !newModels[index].enabled;
setModels(newModels);
saveToServer(newModels);
};
// 提交模型表单
const handleModalOk = () => {
modalFormRef.current.validate().then((values) => {
const newModel = {
model_name: values.model_name,
provider: values.provider,
channel_type: values.channel_type,
supports_i2v: values.supports_i2v || false,
enabled: values.enabled !== false,
endpoint: values.endpoint || '',
};
const newModels = [...models];
if (editingIndex >= 0) {
newModels[editingIndex] = newModel;
} else {
newModels.push(newModel);
}
setModels(newModels);
saveToServer(newModels);
setModalVisible(false);
});
};
// 根据 provider 自动设置 channel_type
const handleProviderChange = (value) => {
const channelType = VIDEO_CHANNEL_TYPES.find((c) => c.provider === value);
if (channelType && modalFormRef.current) {
modalFormRef.current.setValue('channel_type', channelType.value);
}
};
// ===== 视频按秒分档定价 =====
const [pricingConfigs, setPricingConfigs] = useState([]);
const [pricingModalVisible, setPricingModalVisible] = useState(false);
const [editingPricingIndex, setEditingPricingIndex] = useState(-1);
const [tierRows, setTierRows] = useState([]);
const pricingFormRef = useRef();
const savePricingToServer = async (list) => {
setLoading(true);
try {
const res = await API.put('/api/option/', {
key: 'video.video_second_pricing',
value: JSON.stringify(list),
});
if (res.data.success) {
showSuccess(t('保存成功'));
props.refresh();
} else {
showError(res.data.message || t('保存失败'));
}
} catch (e) {
showError(t('保存失败,请重试'));
} finally {
setLoading(false);
}
};
const handleAddPricing = () => {
setEditingPricingIndex(-1);
setTierRows([{ key: '', label: '', price_per_second: 0, aliases: '' }]);
setPricingModalVisible(true);
};
const handleEditPricing = (record, index) => {
setEditingPricingIndex(index);
setTierRows(
(record.tiers || []).map((tier) => ({
key: tier.key || '',
label: tier.label || '',
price_per_second: tier.price_per_second || 0,
aliases: Array.isArray(tier.aliases) ? tier.aliases.join(',') : '',
})),
);
setPricingModalVisible(true);
// 表单初值通过 initValues 设置,这里延迟回填以确保 formApi 就绪
setTimeout(() => {
if (pricingFormRef.current) {
pricingFormRef.current.setValues({
model_name: record.model_name,
tier_param: record.tier_param || 'resolution',
default_tier: record.default_tier || '',
default_duration: record.default_duration || undefined,
enabled: record.enabled !== false,
});
}
}, 0);
};
const handleDeletePricing = (index) => {
const next = [...pricingConfigs];
next.splice(index, 1);
setPricingConfigs(next);
savePricingToServer(next);
};
const handleTogglePricingEnabled = (index) => {
const next = [...pricingConfigs];
next[index] = { ...next[index], enabled: !next[index].enabled };
setPricingConfigs(next);
savePricingToServer(next);
};
const updateTierRow = (idx, patch) => {
setTierRows((rows) =>
rows.map((r, i) => (i === idx ? { ...r, ...patch } : r)),
);
};
const addTierRow = () => {
setTierRows((rows) => [
...rows,
{ key: '', label: '', price_per_second: 0, aliases: '' },
]);
};
const removeTierRow = (idx) => {
setTierRows((rows) => rows.filter((_, i) => i !== idx));
};
const handlePricingModalOk = () => {
pricingFormRef.current.validate().then((values) => {
const tiers = tierRows
.filter((r) => r.key && r.key.trim() !== '')
.map((r) => ({
key: r.key.trim(),
label: r.label?.trim() || r.key.trim(),
price_per_second: Number(r.price_per_second) || 0,
aliases: (r.aliases || '')
.split(',')
.map((a) => a.trim())
.filter((a) => a !== ''),
}));
if (tiers.length === 0) {
showError(t('请至少配置一个档位'));
return;
}
// 单价必须为正,避免保存后该档位静默 0 扣费
if (tiers.some((tier) => !(tier.price_per_second > 0))) {
showError(t('每个档位的每秒单价必须大于 0'));
return;
}
// default_tier 留空时回退到首个档位,避免请求未带档位/档位不匹配时计费档位不确定
const defaultTier = (values.default_tier || '').trim() || tiers[0].key;
const newConfig = {
model_name: values.model_name,
tier_param: values.tier_param || 'resolution',
default_tier: defaultTier,
default_duration: Math.max(0, parseInt(values.default_duration, 10) || 0),
enabled: values.enabled !== false,
tiers,
};
const next = [...pricingConfigs];
if (editingPricingIndex >= 0) {
next[editingPricingIndex] = newConfig;
} else {
next.push(newConfig);
}
setPricingConfigs(next);
savePricingToServer(next);
setPricingModalVisible(false);
});
};
const pricingColumns = [
{ title: t('模型名称'), dataIndex: 'model_name', key: 'model_name' },
{
title: t('选档字段'),
dataIndex: 'tier_param',
key: 'tier_param',
render: (text) => {
const opt = TIER_PARAM_OPTIONS.find((o) => o.value === text);
return opt ? opt.label : text || 'resolution';
},
},
{
title: t('缺省时长'),
dataIndex: 'default_duration',
key: 'default_duration',
render: (v) => (v > 0 ? `${v}s` : t('全局缺省')),
},
{
title: t('档位'),
dataIndex: 'tiers',
key: 'tiers',
render: (tiers) => (
<Space wrap>
{(tiers || []).map((tier) => (
<Tag key={tier.key} color='blue'>
{(tier.label || tier.key) + ':$' + tier.price_per_second + '/s'}
</Tag>
))}
</Space>
),
},
{
title: t('状态'),
dataIndex: 'enabled',
key: 'enabled',
render: (value, record, index) => (
<Tag
color={value ? 'green' : 'red'}
style={{ cursor: 'pointer' }}
onClick={() => handleTogglePricingEnabled(index)}
>
{value ? t('启用') : t('禁用')}
</Tag>
),
},
{
title: t('操作'),
key: 'action',
render: (text, record, index) => (
<Space>
<Button
icon={<IconEdit />}
size='small'
onClick={() => handleEditPricing(record, index)}
/>
<Popconfirm
title={t('确定要删除此定价配置吗?')}
onConfirm={() => handleDeletePricing(index)}
>
<Button icon={<IconDelete />} size='small' type='danger' />
</Popconfirm>
</Space>
),
},
];
// 表格列定义
const columns = [
{
title: t('模型名称'),
dataIndex: 'model_name',
key: 'model_name',
},
{
title: t('提供商'),
dataIndex: 'provider',
key: 'provider',
render: (text) => {
const provider = PROVIDER_OPTIONS.find((p) => p.value === text);
return provider ? provider.label : text;
},
},
{
title: t('渠道类型'),
dataIndex: 'channel_type',
key: 'channel_type',
render: (text) => {
const channel = VIDEO_CHANNEL_TYPES.find((c) => c.value === text);
return channel ? channel.label : text;
},
},
{
title: t('自定义端点'),
dataIndex: 'endpoint',
key: 'endpoint',
render: (text) => text || <Tag color='grey'>{t('默认')}</Tag>,
},
{
title: t('支持图生视频'),
dataIndex: 'supports_i2v',
key: 'supports_i2v',
render: (value) =>
value ? (
<Tag color='green'>{t('是')}</Tag>
) : (
<Tag color='grey'>{t('否')}</Tag>
),
},
{
title: t('状态'),
dataIndex: 'enabled',
key: 'enabled',
render: (value, record, index) => (
<Tag
color={value ? 'green' : 'red'}
style={{ cursor: 'pointer' }}
onClick={() => handleToggleEnabled(index)}
>
{value ? t('启用') : t('禁用')}
</Tag>
),
},
{
title: t('操作'),
key: 'action',
render: (text, record, index) => (
<Space>
<Button
icon={<IconEdit />}
size='small'
onClick={() => handleEditModel(record, index)}
/>
<Popconfirm
title={t('确定要删除此模型吗?')}
onConfirm={() => handleDeleteModel(index)}
>
<Button icon={<IconDelete />} size='small' type='danger' />
</Popconfirm>
</Space>
),
},
];
useEffect(() => {
const currentInputs = {};
for (const key of Object.keys(defaultVideoModelInputs)) {
if (props.options[key] !== undefined) {
let value = props.options[key];
currentInputs[key] = value;
} else {
currentInputs[key] = defaultVideoModelInputs[key];
}
}
setInputs(currentInputs);
setModels(parseModels(currentInputs['video.custom_video_models']));
setPricingConfigs(parseModels(currentInputs['video.video_second_pricing']));
setAssetLimit(
parseInt(currentInputs['video.asset_library_user_limit'], 10) || 50,
);
setRealPortraitEnabled(
String(currentInputs['video.real_portrait_enabled']).toLowerCase() ===
'true',
);
}, [props.options]);
// ===== 素材库配额 =====
const [assetLimit, setAssetLimit] = useState(50);
const [realPortraitEnabled, setRealPortraitEnabled] = useState(false);
const saveAssetLimit = async () => {
if (!assetLimit || assetLimit <= 0) {
showError(t('配额必须为正整数'));
return;
}
setLoading(true);
try {
const res = await API.put('/api/option/', {
key: 'video.asset_library_user_limit',
value: String(assetLimit),
});
if (res.data.success) {
showSuccess(t('保存成功'));
props.refresh();
} else {
showError(res.data.message || t('保存失败'));
}
} catch (e) {
showError(t('保存失败,请重试'));
} finally {
setLoading(false);
}
};
const saveRealPortraitEnabled = async () => {
setLoading(true);
try {
const res = await API.put('/api/option/', {
key: 'video.real_portrait_enabled',
value: String(realPortraitEnabled),
});
if (res.data.success) {
showSuccess(t('保存成功'));
props.refresh();
} else {
showError(res.data.message || t('保存失败'));
}
} catch (e) {
showError(t('保存失败,请重试'));
} finally {
setLoading(false);
}
};
return (
<>
<Spin spinning={loading}>
<Form style={{ marginBottom: 15 }}>
<Form.Section text={t('自定义视频模型')}>
<Row style={{ marginBottom: 16 }}>
<Col span={24}>
<div
style={{ color: 'var(--semi-color-text-2)', marginBottom: 8 }}
>
{t(
'在此配置自定义视频生成模型,这些模型将与内置模型一起可用于视频生成功能。',
)}
</div>
</Col>
</Row>
<Row style={{ marginBottom: 16 }}>
<Col span={24}>
<Button icon={<IconPlus />} onClick={handleAddModel}>
{t('添加模型')}
</Button>
</Col>
</Row>
<Row>
<Col span={24}>
<Table
columns={columns}
dataSource={models}
rowKey={(record, index) => index}
pagination={false}
empty={t('暂无自定义视频模型')}
/>
</Col>
</Row>
<Row style={{ marginBottom: 8 }}>
<Col span={24}>
<div
style={{ color: 'var(--semi-color-text-2)', marginBottom: 8 }}
>
{t(
'真人人像需要 TokenPony 素材权限、公网 HTTPS 服务地址、稳定的 CRYPTO_SECRET 和私有 COS。',
)}
</div>
</Col>
</Row>
<Row style={{ marginBottom: 16 }}>
<Col span={24}>
<Space>
<Switch
checked={realPortraitEnabled}
onChange={setRealPortraitEnabled}
/>
<Button onClick={saveRealPortraitEnabled}>
{t('保存真人人像设置')}
</Button>
</Space>
</Col>
</Row>
</Form.Section>
<Form.Section text={t('视频按秒分档定价')}>
<Row style={{ marginBottom: 16 }}>
<Col span={24}>
<div
style={{ color: 'var(--semi-color-text-2)', marginBottom: 8 }}
>
{t(
'为视频模型配置「按秒分档」计费:每个档位设置每秒单价(官方原价),实际计费 = 单价 × 视频时长 × 分组倍率(分组折扣无需在此重复配置)。配置后该模型计费类型变为「按秒计费」。',
)}
</div>
</Col>
</Row>
<Row style={{ marginBottom: 16 }}>
<Col span={24}>
<Button icon={<IconPlus />} onClick={handleAddPricing}>
{t('添加定价配置')}
</Button>
</Col>
</Row>
<Row>
<Col span={24}>
<Table
columns={pricingColumns}
dataSource={pricingConfigs}
rowKey={(record, index) => index}
pagination={false}
empty={t('暂无按秒分档定价配置')}
/>
</Col>
</Row>
</Form.Section>
<Form.Section text={t('视频素材库')}>
<Row style={{ marginBottom: 8 }}>
<Col span={24}>
<div
style={{ color: 'var(--semi-color-text-2)', marginBottom: 8 }}
>
{t(
'每用户素材数量上限(审核中与已通过的素材计入,审核失败不计入)。保存后约 1 分钟内生效,无需重启。',
)}
</div>
</Col>
</Row>
<Row style={{ marginBottom: 16 }}>
<Col xs={24} sm={12} md={8}>
<InputNumber
value={assetLimit}
min={1}
max={10000}
onChange={(v) => setAssetLimit(v)}
style={{ width: 200, marginRight: 12 }}
/>
<Button onClick={saveAssetLimit}>{t('保存素材库配额')}</Button>
</Col>
</Row>
</Form.Section>
</Form>
</Spin>
<Modal
title={editingIndex >= 0 ? t('编辑模型') : t('添加模型')}
visible={modalVisible}
onOk={handleModalOk}
onCancel={() => setModalVisible(false)}
okText={t('确定')}
cancelText={t('取消')}
>
<Form
getFormApi={(formAPI) => (modalFormRef.current = formAPI)}
initValues={
editingModel || {
model_name: '',
provider: 'ali',
channel_type: 17,
supports_i2v: false,
enabled: true,
endpoint: '',
}
}
>
<Form.Input
field='model_name'
label={t('模型名称')}
placeholder={t('请输入模型名称,如 my-video-model')}
rules={[{ required: true, message: t('请输入模型名称') }]}
/>
<Form.Select
field='provider'
label={t('提供商')}
placeholder={t('请选择提供商')}
rules={[{ required: true, message: t('请选择提供商') }]}
onChange={handleProviderChange}
>
{PROVIDER_OPTIONS.map((option) => (
<Form.Select.Option key={option.value} value={option.value}>
{option.label}
</Form.Select.Option>
))}
</Form.Select>
<Form.Select
field='channel_type'
label={t('渠道类型')}
placeholder={t('请选择渠道类型')}
rules={[{ required: true, message: t('请选择渠道类型') }]}
extraText={t('渠道类型决定了使用哪种 API 协议与上游通信')}
>
{VIDEO_CHANNEL_TYPES.map((option) => (
<Form.Select.Option key={option.value} value={option.value}>
{option.label}
</Form.Select.Option>
))}
</Form.Select>
<Form.Input
field='endpoint'
label={t('自定义API端点')}
placeholder={t('如 /v1/chat/completions,留空则使用默认端点')}
extraText={t('自定义请求的API路径,默认为 /v1/videos/generations')}
/>
<Form.Switch
field='supports_i2v'
label={t('支持图生视频')}
extraText={t('是否支持以图片作为输入生成视频')}
/>
<Form.Switch
field='enabled'
label={t('启用')}
extraText={t('是否启用此模型')}
/>
</Form>
</Modal>
<Modal
title={
editingPricingIndex >= 0 ? t('编辑定价配置') : t('添加定价配置')
}
visible={pricingModalVisible}
onOk={handlePricingModalOk}
onCancel={() => setPricingModalVisible(false)}
okText={t('确定')}
cancelText={t('取消')}
width={640}
>
<Form
getFormApi={(formAPI) => (pricingFormRef.current = formAPI)}
initValues={{
model_name: '',
tier_param: 'resolution',
default_tier: '',
default_duration: undefined,
enabled: true,
}}
>
<Form.Input
field='model_name'
label={t('模型名称')}
placeholder={t('请输入模型名称,如 kling-v2-master')}
rules={[{ required: true, message: t('请输入模型名称') }]}
extraText={t('支持前缀匹配,例如填 kling 可匹配所有 kling 开头模型')}
/>
<Form.Select
field='tier_param'
label={t('选档字段')}
extraText={t('请求中用于选择档位的字段:分辨率/模式/尺寸')}
>
{TIER_PARAM_OPTIONS.map((option) => (
<Form.Select.Option key={option.value} value={option.value}>
{option.label}
</Form.Select.Option>
))}
</Form.Select>
<Form.Input
field='default_tier'
label={t('默认档位')}
placeholder={t('请求未带档位或不匹配时使用的档位 key')}
extraText={t(
'请填上游模型自身的默认档位,避免按错档计费(如 kling 默认 std、vidu 默认 1080p);留空则默认取第一个档位。',
)}
/>
<Form.InputNumber
field='default_duration'
label={t('缺省时长(秒)')}
min={0}
precision={0}
style={{ width: '100%' }}
placeholder={t('请求未带时长时使用,留空则按全局缺省 5 秒')}
extraText={t(
'应填该上游模型自身的默认时长(如 hailuo 默认 6 秒),避免省略时长时按 5 秒少扣。',
)}
/>
<Form.Switch field='enabled' label={t('启用')} />
</Form>
<div
style={{
marginTop: 8,
padding: '8px 12px',
borderRadius: 6,
background: 'var(--semi-color-fill-0)',
color: 'var(--semi-color-text-2)',
fontSize: 12,
lineHeight: 1.6,
}}
>
<Typography.Text strong style={{ fontSize: 12 }}>
{t('选档值来源说明')}
</Typography.Text>
<div style={{ marginTop: 4 }}>
{t(
'视频生成接口(/v1/video/generations)与任务接口会自动读取请求中的 resolution / mode / size 字段来选档。',
)}
</div>
<div>
{t(
'通过对话接口(/v1/chat/completions)调用时,自然语言无法可靠表达计费档位,需在请求体的 metadata 中显式传入,例如:',
)}
</div>
<pre
style={{
margin: '4px 0 0',
padding: '6px 8px',
borderRadius: 4,
background: 'var(--semi-color-fill-1)',
whiteSpace: 'pre-wrap',
fontSize: 12,
}}
>
{'"metadata": { "mode": "pro", "resolution": "1080P" }'}
</pre>
<div style={{ marginTop: 4 }}>
{t('未传入选档值时,将按上面配置的「默认档位」计费。')}
</div>
</div>
<div style={{ marginTop: 12 }}>
<Typography.Text strong>{t('档位列表')}</Typography.Text>
<div
style={{
color: 'var(--semi-color-text-2)',
fontSize: 12,
margin: '4px 0 8px',
}}
>
{t(
'key 为档位标识(需与请求字段值或别名匹配),label 用于展示(如 1080P/S),单价为每秒美元价。别名用英文逗号分隔。',
)}
</div>
{tierRows.map((row, idx) => (
<Row
key={idx}
gutter={8}
type='flex'
align='middle'
style={{ marginBottom: 8 }}
>
<Col span={5}>
<Input
placeholder={t('key 如 1080P')}
value={row.key}
onChange={(v) => updateTierRow(idx, { key: v })}
/>
</Col>
<Col span={5}>
<Input
placeholder={t('展示名 如 1080P/S')}
value={row.label}
onChange={(v) => updateTierRow(idx, { label: v })}
/>
</Col>
<Col span={5}>
<InputNumber
placeholder={t('单价/秒')}
prefix='$'
min={0}
step={0.01}
style={{ width: '100%' }}
value={row.price_per_second}
onChange={(v) =>
updateTierRow(idx, { price_per_second: v })
}
/>
</Col>
<Col span={7}>
<Input
placeholder={t('别名(逗号分隔) 如 std,standard')}
value={row.aliases}
onChange={(v) => updateTierRow(idx, { aliases: v })}
/>
</Col>
<Col span={2}>
<Button
icon={<IconDelete />}
size='small'
type='danger'
onClick={() => removeTierRow(idx)}
/>
</Col>
</Row>
))}
<Button icon={<IconPlus />} size='small' onClick={addTierRow}>
{t('添加档位')}
</Button>
</div>
</Modal>
</>
);
}