/* 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 . 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 '@/components/ui'; import { IconPlus, IconDelete, IconEdit } from '@/components/ui/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) => ( {(tiers || []).map((tier) => ( {(tier.label || tier.key) + ':$' + tier.price_per_second + '/s'} ))} ), }, { title: t('状态'), dataIndex: 'enabled', key: 'enabled', render: (value, record, index) => ( handleTogglePricingEnabled(index)} > {value ? t('启用') : t('禁用')} ), }, { title: t('操作'), key: 'action', render: (text, record, index) => ( index} pagination={false} empty={t('暂无自定义视频模型')} />
{t( '真人人像需要 TokenPony 素材权限、公网 HTTPS 服务地址、稳定的 CRYPTO_SECRET 和私有 COS。', )}
{t( '为视频模型配置「按秒分档」计费:每个档位设置每秒单价(官方原价),实际计费 = 单价 × 视频时长 × 分组倍率(分组折扣无需在此重复配置)。配置后该模型计费类型变为「按秒计费」。', )}
index} pagination={false} empty={t('暂无按秒分档定价配置')} />
{t( '每用户素材数量上限(审核中与已通过的素材计入,审核失败不计入)。保存后约 1 分钟内生效,无需重启。', )}
setAssetLimit(v)} style={{ width: 200, marginRight: 12 }} /> = 0 ? t('编辑模型') : t('添加模型')} visible={modalVisible} onOk={handleModalOk} onCancel={() => setModalVisible(false)} okText={t('确定')} cancelText={t('取消')} >
(modalFormRef.current = formAPI)} initValues={ editingModel || { model_name: '', provider: 'ali', channel_type: 17, supports_i2v: false, enabled: true, endpoint: '', } } > {PROVIDER_OPTIONS.map((option) => ( {option.label} ))} {VIDEO_CHANNEL_TYPES.map((option) => ( {option.label} ))}
= 0 ? t('编辑定价配置') : t('添加定价配置') } visible={pricingModalVisible} onOk={handlePricingModalOk} onCancel={() => setPricingModalVisible(false)} okText={t('确定')} cancelText={t('取消')} width={640} >
(pricingFormRef.current = formAPI)} initValues={{ model_name: '', tier_param: 'resolution', default_tier: '', default_duration: undefined, enabled: true, }} > {TIER_PARAM_OPTIONS.map((option) => ( {option.label} ))}
{t('选档值来源说明')}
{t( '视频生成接口(/v1/video/generations)与任务接口会自动读取请求中的 resolution / mode / size 字段来选档。', )}
{t( '通过对话接口(/v1/chat/completions)调用时,自然语言无法可靠表达计费档位,需在请求体的 metadata 中显式传入,例如:', )}
            {'"metadata": { "mode": "pro", "resolution": "1080P" }'}
          
{t('未传入选档值时,将按上面配置的「默认档位」计费。')}
{t('档位列表')}
{t( 'key 为档位标识(需与请求字段值或别名匹配),label 用于展示(如 1080P/S),单价为每秒美元价。别名用英文逗号分隔。', )}
{tierRows.map((row, idx) => (
updateTierRow(idx, { key: v })} /> updateTierRow(idx, { label: v })} /> updateTierRow(idx, { price_per_second: v }) } /> updateTierRow(idx, { aliases: v })} /> ); }