refactor: adjust playground pages dir

This commit is contained in:
jialin
2026-03-17 16:35:55 +08:00
committed by jialin
parent 64955c26a7
commit 9447088f89
25 changed files with 262 additions and 317 deletions
+129
View File
@@ -0,0 +1,129 @@
import CheckboxField from '@/components/seal-form/checkbox-field';
import SealInput from '@/components/seal-form/seal-input';
import UploadAudio from '@/components/upload-audio';
import useAppUtils from '@/hooks/use-app-utils';
import { convertFileToBase64 } from '@/utils/load-audio-file';
import { CloseCircleFilled } from '@ant-design/icons';
import { useIntl } from '@umijs/max';
import { Form } from 'antd';
import React from 'react';
import styled from 'styled-components';
import { useFormContext } from '../config/form-context';
const SuffixWrapper = styled.div.attrs({
className: 'suffix-wrapper'
})`
display: flex;
align-items: center;
.icon {
display: none;
font-size: 12px;
color: var(--ant-color-text-quaternary);
cursor: pointer;
&:hover {
color: var(--ant-color-text-tertiary);
}
}
`;
const Container = styled.div`
&:hover {
.suffix-wrapper {
.icon {
display: block;
}
}
}
`;
export const RefAudioFormItem: React.FC = () => {
const { getRuleMessage } = useAppUtils();
const { meta, onValuesChange } = useFormContext();
const form = Form.useFormInstance();
const intl = useIntl();
const [fileName, setFileName] = React.useState<string>('');
const taskType = Form.useWatch('task_type', form);
// handle upload audio file, transfer to a base64 url
const handleUploadChange = async (data: { file: any; fileList: any }) => {
const { file } = data;
const base64 = await convertFileToBase64(file);
form.setFieldsValue({
ref_audio: base64
});
setFileName(file.name);
onValuesChange?.(
{ ref_audio: base64 },
{ ...form.getFieldsValue(), ref_audio: base64 }
);
};
const handleClear = () => {
form.setFieldsValue({
ref_audio: ''
});
setFileName('');
onValuesChange?.(
{ ref_audio: '' },
{ ...form.getFieldsValue(), ref_audio: '' }
);
};
return (
<>
<Container>
<Form.Item
name="ref_audio"
getValueProps={(value) => ({ value: fileName ? fileName : value })}
rules={[
{
required: taskType === 'Base',
message: getRuleMessage('input', 'playground.params.refAudio')
}
]}
dependencies={['task_type']}
>
<SealInput.Input
allowClear
readOnly={!!fileName}
required={taskType === 'Base'}
suffix={
<SuffixWrapper>
{fileName ? (
<span onClick={handleClear}>
<CloseCircleFilled className="icon" />
</span>
) : null}
<UploadAudio
size="small"
type="text"
accept={['.mp3', '.mp4', '.wav', '.m4a'].join(', ')}
onChange={handleUploadChange}
></UploadAudio>
</SuffixWrapper>
}
description={intl.formatMessage({
id: 'playground.params.refAudio.tips'
})}
label={intl.formatMessage({ id: 'playground.params.refAudio' })}
></SealInput.Input>
</Form.Item>
</Container>
<Form.Item name="ref_text" style={{ marginBottom: 8 }}>
<SealInput.TextArea
allowClear
scaleSize={true}
label={intl.formatMessage({ id: 'playground.params.refAudio.text' })}
></SealInput.TextArea>
</Form.Item>
<Form.Item name="x_vector_only_mode" valuePropName="checked">
<CheckboxField
label={intl.formatMessage({
id: 'playground.params.refAudio.vectorMode'
})}
></CheckboxField>
</Form.Item>
</>
);
};
+228
View File
@@ -0,0 +1,228 @@
import IconFont from '@/components/icon-font';
import breakpoints from '@/config/breakpoints';
import HotKeys from '@/config/hotkeys';
import useWindowResize from '@/hooks/use-window-resize';
import { ExtraContent } from '@/layouts/extraRender';
import { modelCategoriesMap } from '@/pages/llmodels/config';
import { AudioOutlined } from '@ant-design/icons';
import { useIntl, useSearchParams } from '@umijs/max';
import useMemoizedFn from 'ahooks/lib/useMemoizedFn';
import { Divider, Segmented, Tabs, TabsProps } from 'antd';
import classNames from 'classnames';
import _ from 'lodash';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useHotkeys } from 'react-hotkeys-hook';
import { PageContainerInner } from '../../_components/page-box';
import { queryModelsList } from '../apis';
import ViewCodeButtons from '../components/view-code-buttons';
import '../style/play-ground.less';
import GroundSTT from './stt';
import GroundTTS from './tts';
const TabsValueMap = {
Tab1: 'tts',
Tab2: 'stt',
tts: 'tts',
stt: 'stt'
};
const Playground: React.FC = () => {
const intl = useIntl();
const [searchParams] = useSearchParams();
const modelType = searchParams.get('type') || '';
const { size } = useWindowResize();
const [activeKey, setActiveKey] = useState(modelType || TabsValueMap.Tab1);
const groundTabRef1 = useRef<any>(null);
const groundTabRef2 = useRef<any>(null);
const [textToSpeechModels, setTextToSpeechModels] = useState<
Global.BaseOption<string>[]
>([]);
const [speechModelList, setSpeechModelList] = useState<
Global.BaseOption<string>[]
>([]);
const optionsList = useMemo(() => {
return [
{
label: intl.formatMessage({ id: 'playground.audio.texttospeech' }),
value: TabsValueMap.Tab1,
icon: <IconFont type={'icon-audio'}></IconFont>
},
{
label: intl.formatMessage({ id: 'playground.audio.speechtotext' }),
value: TabsValueMap.Tab2,
icon: <AudioOutlined />
}
];
}, [intl]);
const handleViewCode = useMemoizedFn(() => {
if (activeKey === TabsValueMap.Tab1) {
groundTabRef1.current?.viewCode?.();
} else if (activeKey === TabsValueMap.Tab2) {
groundTabRef2.current?.viewCode?.();
}
});
const handleToggleCollapse = useMemoizedFn(() => {
if (activeKey === TabsValueMap.Tab1) {
groundTabRef1.current?.setCollapse?.();
return;
}
groundTabRef2.current?.setCollapse?.();
});
const items: TabsProps['items'] = useMemo(() => {
return [
{
key: 'tts',
label: 'TTS',
children: (
<GroundTTS
ref={groundTabRef1}
modelList={textToSpeechModels}
></GroundTTS>
)
},
{
key: 'stt',
label: 'Realtime',
children: <GroundSTT modelList={speechModelList} ref={groundTabRef2} />
}
];
}, [textToSpeechModels, speechModelList]);
useEffect(() => {
if (size.width < breakpoints.lg) {
if (!groundTabRef1.current?.collapse) {
groundTabRef1.current?.setCollapse?.();
}
if (!groundTabRef2.current?.collapse) {
groundTabRef2.current?.setCollapse?.();
}
}
}, [size.width]);
useEffect(() => {
const getTextToSpeechModels = async () => {
try {
const params = {
categories: modelCategoriesMap.text_to_speech,
with_meta: true
};
const res = await queryModelsList(params);
const list = _.map(res.data || [], (item: any) => {
return {
value: item.id,
label: item.id,
meta: item.meta
};
}) as Global.BaseOption<string>[];
return list;
} catch (error) {
console.error(error);
return [];
}
};
const getSpeechToText = async () => {
try {
const params = {
categories: modelCategoriesMap.speech_to_text,
with_meta: true
};
const res = await queryModelsList(params);
const list = _.map(res.data || [], (item: any) => {
return {
value: item.id,
label: item.id,
meta: item.meta
};
}) as Global.BaseOption<string>[];
return list;
} catch (error) {
console.error(error);
return [];
}
};
const fetchData = async () => {
try {
const [textToSpeechModels, speechToTextModels] = await Promise.all([
getTextToSpeechModels(),
getSpeechToText()
]);
setTextToSpeechModels(textToSpeechModels);
setSpeechModelList(speechToTextModels);
} catch (error) {
// error
}
};
fetchData();
}, []);
const header = useMemo(() => {
return {
title: (
<div className="flex items-center">
<span className="font-600">
{intl.formatMessage({ id: 'menu.playground.speech' })}
</span>
{
<Segmented
options={optionsList}
size="middle"
className="m-l-24 font-600"
value={activeKey}
onChange={(key) => setActiveKey(key)}
></Segmented>
}
</div>
)
};
}, [activeKey, optionsList, intl]);
useHotkeys(
HotKeys.RIGHT.join(','),
() => {
groundTabRef1.current?.setCollapse?.();
},
{
preventDefault: true
}
);
return (
<PageContainerInner
header={header}
extra={[
<ViewCodeButtons
activeKey=""
handleViewCode={handleViewCode}
handleToggleCollapse={handleToggleCollapse}
key="view-code-buttons"
></ViewCodeButtons>,
<Divider
key="divider"
orientation="vertical"
style={{ height: 16, marginInline: 16 }}
/>,
<ExtraContent key="extra-content" />
]}
className={classNames('playground-container', {
compare: activeKey === 'compare',
chat: activeKey !== 'compare'
})}
>
<div className="play-ground">
<div className="chat">
<Tabs items={items} activeKey={activeKey}></Tabs>
</div>
</div>
</PageContainerInner>
);
};
export default Playground;
@@ -0,0 +1,160 @@
import _ from 'lodash';
import { ParamsSchema } from '../config/types';
export const TTSAdvancedParamsConfig: ParamsSchema[] = [
{
type: 'Input',
name: 'task_type',
options: [],
attrs: {
allowClear: true
},
label: {
text: 'playground.params.taskType',
isLocalized: true
},
rules: [
{
required: false
}
]
},
{
type: 'AutoComplete',
name: 'language',
options: [],
initAttrs: (meta: any) => {
return {
options: _.map(meta?.languages || [], (item: string) => ({
label: item,
value: item
}))
};
},
attrs: {
allowClear: true
},
label: {
text: 'playground.params.language',
isLocalized: true
},
rules: [
{
required: false
}
]
},
{
type: 'Input',
name: 'instructions',
label: {
text: 'playground.params.instructions',
isLocalized: true
},
description: {
text: 'playground.params.instructions.tips',
isLocalized: true
},
attrs: {
allowClear: true
},
initAttrs: (meta: any) => {
return {
options: _.map(meta?.voices || [], (item: string) => ({
label: item,
value: item
}))
};
},
rules: [
{
required: false
}
]
},
{
type: 'InputNumber',
name: 'max_new_tokens',
label: {
text: 'playground.params.maxTokens',
isLocalized: true
},
attrs: {
allowClear: true,
step: 1,
min: 0,
max: 4096
},
formItemAttrs: {
getValueProps: (value: number) => {
return {
value: value || null
};
}
},
rules: [
{
required: false
}
]
}
];
export const TTSParamsConfig: ParamsSchema[] = [
{
type: 'AutoComplete',
name: 'voice',
options: [],
label: {
text: 'playground.params.voice',
isLocalized: true
},
rules: [
{
required: false,
message: 'Voice is required'
}
]
},
{
type: 'Select',
name: 'response_format',
options: [
{ label: 'mp3', value: 'mp3' },
// { label: 'opus', value: 'opus' },
// { label: 'aac', value: 'aac' },
// { label: 'flac', value: 'flac' },
{ label: 'wav', value: 'wav' }
// { label: 'pcm', value: 'pcm' }
],
label: {
text: 'playground.params.format',
isLocalized: true
},
rules: [
{
required: false
}
]
}
// {
// type: 'Select',
// name: 'speed',
// options: [
// { label: '0.25x', value: 0.25 },
// { label: '0.5x', value: 0.5 },
// { label: '1x', value: 1 },
// { label: '2x', value: 2 },
// { label: '4x', value: 4 }
// ],
// label: {
// text: 'playground.params.speed',
// isLocalized: true
// },
// rules: [
// {
// required: false
// }
// ]
// }
];
+513
View File
@@ -0,0 +1,513 @@
import { setRouteCache } from '@/atoms/route-cache';
import AlertInfo from '@/components/alert-info';
import AudioAnimation from '@/components/audio-animation';
import AudioPlayer from '@/components/audio-player';
import CopyButton from '@/components/copy-button';
import IconFont from '@/components/icon-font';
import UploadAudio from '@/components/upload-audio';
import routeCachekey from '@/config/route-cachekey';
import { HEADER_HEIGHT } from '@/config/settings';
import useOverlayScroller from '@/hooks/use-overlay-scroller';
import { useCancelToken } from '@/hooks/use-request-token';
import { readAudioFile } from '@/utils/load-audio-file';
import { SendOutlined } from '@ant-design/icons';
import { useIntl, useSearchParams } from '@umijs/max';
import { Button, Spin, Tooltip } from 'antd';
import _ from 'lodash';
import React, {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState
} from 'react';
import { AUDIO_SPEECH_TO_TEXT_API, speechToText } from '../apis';
import AudioInput from '../components/audio-input';
import DynamicParams from '../components/dynamic-params';
import RightContainer from '../components/right-container';
import ViewCommonCode from '../components/view-common-code';
import {
SpeechToTextFormat,
defaultLanguages,
extractErrorMessage
} from '../config';
import { allLanguages } from '../config/languages';
import { RealtimeParamsConfig as paramsConfig } from '../config/params-config';
import { ParamsSchema } from '../config/types';
import '../style/ground-llm.less';
import '../style/speech-to-text.less';
import '../style/system-message-wrap.less';
import { speechToTextCode } from '../view-code/audio';
interface MessageProps {
modelList: Global.BaseOption<string>[];
ref?: any;
}
const GroundSTT: React.FC<MessageProps> = forwardRef((props, ref) => {
const intl = useIntl();
const { modelList } = props;
const messageId = useRef<number>(0);
const [messageList, setMessageList] = useState<
{ uid: number; content: string }[]
>([]);
const [searchParams] = useSearchParams();
const modelType = searchParams.get('type') || '';
const selectModel = searchParams.get('model')
? modelType === 'stt' && searchParams.get('model')
: '';
const defaultModel = selectModel || modelList[0]?.value || '';
const [parameters, setParams] = useState<any>({
model: defaultModel,
language: 'auto'
});
const [show, setShow] = useState(false);
const [loading, setLoading] = useState(false);
const [tokenResult, setTokenResult] = useState<any>(null);
const [collapse, setCollapse] = useState(false);
const scroller = useRef<any>(null);
const [audioPermissionOn, setAudioPermissionOn] = useState(true);
const [audioData, setAudioData] = useState<any>(null);
const [audioChunks, setAudioChunks] = useState<any>({
data: [],
analyser: null
});
const [isRecording, setIsRecording] = useState(false);
const formRef = useRef<any>(null);
const { updateCancelToken, getCanceltToken, cancelRequest } =
useCancelToken();
const { initialize, updateScrollerPosition } = useOverlayScroller();
const [modelMeta, setModelMeta] = useState<any>(null);
const [fieldsConfig, setFieldsConfig] =
useState<ParamsSchema[]>(paramsConfig);
useImperativeHandle(ref, () => {
return {
viewCode() {
setShow(true);
},
setCollapse() {
setCollapse(!collapse);
},
collapse: collapse
};
});
const setMessageId = () => {
messageId.current = messageId.current + 1;
};
const viewCodeContent = useMemo(() => {
return speechToTextCode({
api: AUDIO_SPEECH_TO_TEXT_API,
parameters: {
...parameters
}
});
}, [parameters]);
const handleStopConversation = () => {
cancelRequest();
setLoading(false);
};
const submitMessage = async () => {
try {
await formRef.current?.form.validateFields();
if (!parameters.model) return;
setLoading(true);
setMessageId();
setTokenResult(null);
setMessageList([]);
updateCancelToken();
setRouteCache(routeCachekey['/playground/speech'], true);
const params = {
...parameters,
file: new File([audioData.data], audioData.name, {
type: audioData.type
})
};
const result: any = await speechToText(
{
data: params
},
{
cancelToken: getCanceltToken()
}
);
if (
(result?.status_code && result?.status_code !== 200) ||
result?.error
) {
setTokenResult({
error: true,
errorMessage: extractErrorMessage(result)
});
return;
}
setMessageList([
{
content: result.text,
uid: messageId.current
}
]);
} catch (error: any) {
console.log('error:', error);
const res = error?.response?.data;
if (res?.error || (res?.status_code && res?.status_code !== 200)) {
setTokenResult({
error: true,
errorMessage: extractErrorMessage(res)
});
}
} finally {
setLoading(false);
setIsRecording(false);
setRouteCache(routeCachekey['/playground/speech'], false);
}
};
const handleClear = () => {
setMessageId();
setMessageList([]);
setTokenResult(null);
};
const handleCloseViewCode = () => {
setShow(false);
};
const handleOnAudioData = useCallback(
(data: {
chunks: Blob[];
url: string;
name: string;
duration: number;
type: string;
}) => {
setAudioData(() => {
return {
url: data.url,
name: data.name,
data: data.chunks,
type: data.type,
duration: data.duration
};
});
},
[]
);
const handleOnAudioPermission = useCallback((permission: boolean) => {
setAudioPermissionOn(permission);
}, []);
const handleUploadChange = useCallback(
async (data: { file: any; fileList: any }) => {
try {
const res = await readAudioFile(data.file);
setAudioData(res);
setTokenResult(null);
} catch (error) {}
},
[]
);
const handleOnAnalyse = useCallback((data: any, analyser: any) => {
setAudioChunks((pre: any) => {
return {
data: data,
analyser: analyser
};
});
}, []);
const handleOnRecord = useCallback((val: boolean) => {
setIsRecording(val);
setAudioData(null);
setTokenResult(null);
setMessageList([]);
}, []);
const handleOnGenerate = async () => {
if (loading) {
handleStopConversation();
return;
}
submitMessage();
};
const renderAniamtion = () => {
if (!audioPermissionOn) {
return (
<div className="tips-text">
<IconFont type={'icon-audio'} style={{ fontSize: 20 }}></IconFont>
<span>
{intl.formatMessage({ id: 'playground.audio.enablemic' })}
</span>
</div>
);
}
if (isRecording) {
return (
<AudioAnimation
fixedHeight={true}
height={82}
width={500}
analyserData={audioChunks}
></AudioAnimation>
);
}
return (
<div className="tips-text">
<IconFont type={'icon-audio'} style={{ fontSize: 18 }}></IconFont>
<span>
{intl.formatMessage({ id: 'playground.audio.speechtotext.tips' })}
</span>
</div>
);
};
const handleSelectModel = (model: string) => {
if (!model) return;
const selected = modelList.find((item) => item.value === model);
setModelMeta(selected?.meta || {});
const languages = selected?.meta?.languages || [];
let currentLanguage = [...defaultLanguages];
if (languages.length > 0) {
// sort languages based on the order in the model meta
currentLanguage = [];
languages.forEach((langCode: string) => {
const langItem = allLanguages.find((item) => item.value === langCode);
if (langItem) {
currentLanguage.push(langItem);
}
});
const newConfig = paramsConfig.map((item) => {
const oItem = _.cloneDeep(item);
if (item.name === 'language') {
return {
...oItem,
options: currentLanguage
};
}
return oItem;
});
setFieldsConfig(newConfig);
}
setParams((pre: any) => {
return {
...pre,
language:
selected?.meta?.language || currentLanguage[0]?.value || 'auto',
model: model
};
});
};
const handleOnValuesChange = (changedValues: any, allValues: any) => {
if (changedValues.model) {
handleSelectModel(changedValues.model);
} else {
setParams(allValues);
}
};
useEffect(() => {
if (scroller.current) {
initialize(scroller.current);
}
}, [initialize]);
useEffect(() => {
if (loading) {
updateScrollerPosition();
}
}, [messageList, loading]);
useEffect(() => {
const defaultModel = selectModel || modelList[0]?.value || '';
handleSelectModel(defaultModel);
}, [modelList, selectModel]);
return (
<div
className="ground-left-wrapper"
style={{
height: `calc(100vh - ${HEADER_HEIGHT}px)`
}}
>
<div className="ground-left">
<div className="ground-left-footer" style={{ flex: 1 }}>
<div className="speech-to-text">
<div className="speech-box">
{!isRecording && (
<UploadAudio
type="default"
accept={SpeechToTextFormat.join(', ')}
onChange={handleUploadChange}
></UploadAudio>
)}
<AudioInput
type="default"
voiceActivity={true}
onAudioData={handleOnAudioData}
onAudioPermission={handleOnAudioPermission}
onAnalyse={handleOnAnalyse}
onRecord={handleOnRecord}
></AudioInput>
</div>
{audioData ? (
<div className="flex-between flex-center justify-center relative">
<div style={{ width: 600 }}>
<AudioPlayer
url={audioData.url}
name={audioData.name}
duration={audioData.duration}
extra={
<Tooltip
title={
loading
? intl.formatMessage({
id: 'common.button.stop'
})
: intl.formatMessage({
id: 'playground.audio.button.generate'
})
}
>
{
<Button
disabled={!audioData}
type="primary"
size="middle"
shape="circle"
onClick={handleOnGenerate}
icon={
loading ? (
<IconFont
type="icon-stop1"
className="font-size-14"
></IconFont>
) : (
<SendOutlined></SendOutlined>
)
}
></Button>
}
</Tooltip>
}
></AudioPlayer>
</div>
</div>
) : (
renderAniamtion()
)}
</div>
</div>
<div
style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
overflow: 'auto'
}}
>
<div
className="message-list-wrap"
style={{
flex: 1,
position: 'relative'
}}
>
{messageList?.length > 0 && (
<span
style={{
position: 'absolute',
top: 20,
right: 32,
zIndex: 10
}}
>
<CopyButton
text={messageList[0]?.content}
type="link"
></CopyButton>
</span>
)}
<div
className="content"
style={{ height: '100%', overflow: 'auto' }}
ref={scroller}
>
<div>
{!tokenResult && (
<div
style={{
padding: '8px 14px',
lineHeight: '20px',
display: 'flex',
justifyContent: 'center',
wordBreak: 'break-word'
}}
>
{messageList.length ? (
messageList[0]?.content
) : (
<span className="text-tertiary">
{intl.formatMessage({
id: 'playground.audio.generating.tips'
})}
</span>
)}
</div>
)}
{tokenResult && (
<div style={{ height: 40 }}>
<AlertInfo
type="danger"
message={tokenResult?.errorMessage}
></AlertInfo>
</div>
)}
</div>
</div>
{loading && (
<div style={{ width: '100%', flex: 1 }}>
<Spin size="small">
<div style={{ height: '46px' }}></div>
</Spin>
</div>
)}
</div>
</div>
</div>
<RightContainer collapsed={collapse}>
<DynamicParams
ref={formRef}
onValuesChange={handleOnValuesChange}
paramsConfig={fieldsConfig}
initialValues={parameters}
modelList={modelList}
/>
</RightContainer>
<ViewCommonCode
open={show}
viewCodeContent={viewCodeContent}
onCancel={handleCloseViewCode}
title={intl.formatMessage({ id: 'playground.viewcode' })}
></ViewCommonCode>
</div>
);
});
export default GroundSTT;
+501
View File
@@ -0,0 +1,501 @@
import { setRouteCache } from '@/atoms/route-cache';
import AlertInfo from '@/components/alert-info';
import IconFont from '@/components/icon-font';
import AutoComplete from '@/components/seal-form/auto-complete';
import FieldComponent from '@/components/seal-form/field-component';
import SealSelect from '@/components/seal-form/seal-select';
import SpeechContent from '@/components/speech-content';
import routeCachekey from '@/config/route-cachekey';
import useOverlayScroller from '@/hooks/use-overlay-scroller';
import CollapsePanel from '@/pages/_components/collapse-panel';
import { getLocale, useIntl, useSearchParams } from '@umijs/max';
import { Form, Spin } from 'antd';
import _ from 'lodash';
import 'overlayscrollbars/overlayscrollbars.css';
import React, {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState
} from 'react';
import { AUDIO_TEXT_TO_SPEECH_API, CHAT_API, textToSpeech } from '../apis';
import DynamicParams from '../components/dynamic-params';
import MessageInput from '../components/message-input';
import RightContainer from '../components/right-container';
import ViewCommonCode from '../components/view-common-code';
import { extractErrorMessage } from '../config';
import { MessageItem, ParamsSchema } from '../config/types';
import '../style/ground-llm.less';
import '../style/system-message-wrap.less';
import { TextToSpeechCode } from '../view-code/audio';
import { RefAudioFormItem } from './form';
import {
TTSParamsConfig as paramsConfig,
TTSAdvancedParamsConfig
} from './params-config';
const MetaFields = [
'task_type',
'language',
'instructions',
'max_new_tokens',
'ref_audio'
];
interface MessageProps {
modelList: Global.BaseOption<string>[];
loaded?: boolean;
ref?: any;
}
const GroundTTS: React.FC<MessageProps> = forwardRef((props, ref) => {
const { modelList } = props;
const messageId = useRef<number>(0);
const [messageList, setMessageList] = useState<
{
input: string;
voice: string;
format: string;
speed: number;
uid: number;
autoplay: boolean;
audioUrl: string;
}[]
>([]);
const locale = getLocale();
const intl = useIntl();
const [searchParams] = useSearchParams();
const modelType = searchParams.get('type') || '';
const selectModel = searchParams.get('model')
? modelType === 'tts' && searchParams.get('model')
: '';
const [parameters, setParams] = useState<any>({
model: selectModel,
voice: '',
response_format: 'mp3'
});
const [show, setShow] = useState(false);
const [loading, setLoading] = useState(false);
const [tokenResult, setTokenResult] = useState<any>(null);
const [collapse, setCollapse] = useState(false);
const controllerRef = useRef<any>(null);
const scroller = useRef<any>(null);
const checkvalueRef = useRef<any>(true);
const [currentPrompt, setCurrentPrompt] = useState<string>('');
const [voiceDataList, setVoiceList] = useState<Global.BaseOption<string>[]>(
[]
);
const [modelMeta, setModelMeta] = useState<any>({});
const formRef = useRef<any>(null);
const { initialize } = useOverlayScroller();
const [activeKey, setActiveKey] = useState<string | string[]>(
'advanced_config'
);
useImperativeHandle(ref, () => {
return {
viewCode() {
setShow(true);
},
setCollapse() {
setCollapse(!collapse);
},
collapse: collapse
};
});
const defaultModel = useMemo(() => {
return selectModel || modelList[0]?.value || '';
}, [modelList]);
const dropEmptyFields = (parameters: Record<string, any>) => {
const fields = [
'task_type',
'instructions',
'max_new_tokens',
'ref_audio',
'ref_text',
'language',
'x_vector_only_mode'
];
const newParams = { ...parameters };
return _.omitBy(newParams, (value: any, key: string) => {
return fields.includes(key) && !value;
});
};
const viewCodeContent = useMemo(() => {
return TextToSpeechCode({
api: AUDIO_TEXT_TO_SPEECH_API,
parameters: {
...dropEmptyFields(parameters),
input: currentPrompt
}
});
}, [parameters, currentPrompt]);
const sortVoiceList = useCallback(
(locale: string, voiceDataList: Global.BaseOption<string>[]) => {
const lang = locale === 'en-US' ? 'english' : 'chinese';
const list = voiceDataList.sort((a, b) => {
const aContains = a.value.toLowerCase().includes(lang) ? 1 : 0;
const bContains = b.value.toLowerCase().includes(lang) ? 1 : 0;
return bContains - aContains;
});
return list;
},
[]
);
const voiceList = useMemo(() => {
if (!voiceDataList.length) return [];
const newList = sortVoiceList(locale, voiceDataList);
return newList;
}, [locale, voiceDataList, sortVoiceList]);
useEffect(() => {
const newList = sortVoiceList(locale, voiceDataList);
setParams((pre: any) => {
return {
...pre,
voice: newList[0]?.value
};
});
formRef.current?.form.setFieldValue('voice', newList[0]?.value);
}, [locale, voiceDataList, sortVoiceList]);
const setMessageId = () => {
messageId.current = messageId.current + 1;
};
const handleStopConversation = () => {
controllerRef.current?.abort?.();
setLoading(false);
};
const handleInputChange = (e: any) => {
setCurrentPrompt(e.target.value);
};
const submitMessage = async (current?: { role: string; content: string }) => {
try {
await formRef.current?.form.validateFields();
if (!parameters.model) return;
setLoading(true);
setMessageId();
setTokenResult(null);
setCurrentPrompt(current?.content || '');
setMessageList([]);
setRouteCache(routeCachekey['/playground/speech'], true);
controllerRef.current?.abort?.();
controllerRef.current = new AbortController();
const signal = controllerRef.current.signal;
const params = {
...dropEmptyFields(parameters),
input: current?.content || currentPrompt
};
const res: any = await textToSpeech({
data: params,
url: CHAT_API,
signal
});
setParams(params);
console.log('result:', res);
if ((res?.status_code && res?.status_code !== 200) || res?.error) {
setTokenResult({
error: true,
errorMessage: extractErrorMessage(res)
});
setMessageList([]);
return;
}
setMessageList([
{
input: current?.content || currentPrompt,
voice: parameters.voice,
format: parameters.response_format,
speed: parameters.speed,
uid: messageId.current,
autoplay: checkvalueRef.current,
audioUrl: res.url
}
]);
} catch (error: any) {
const res = error?.response?.data;
console.log('error:', error);
if (res?.error) {
setTokenResult({
error: true,
errorMessage: extractErrorMessage(res)
});
}
} finally {
setLoading(false);
setRouteCache(routeCachekey['/playground/speech'], false);
}
};
const handleClear = () => {
setMessageId();
setMessageList([]);
setTokenResult(null);
};
const handleSendMessage = (message: Omit<MessageItem, 'uid'>) => {
submitMessage(message);
};
const handleCloseViewCode = () => {
setShow(false);
};
const handleSelectModel = async (value: string) => {
if (!value) {
return;
}
const model = modelList.find((item) => item.value === value);
const list = _.map(model?.meta?.voices || [], (item: any) => {
return {
label: item,
value: item
};
});
const newList = sortVoiceList(locale, list);
setVoiceList(newList);
setModelMeta(model?.meta || {});
setParams((pre: any) => {
return {
...pre,
..._.pick(model?.meta || {}, MetaFields),
task_type: model?.meta?.task_type,
model: value,
language: model?.meta?.languages?.[0] || '',
voice: newList[0]?.value
};
});
};
const handleOnValuesChange = useCallback(
(changeValues: Record<string, any>, allValues: Record<string, any>) => {
if (changeValues.model) {
handleSelectModel(changeValues.model);
} else {
setParams(allValues);
}
},
[handleSelectModel]
);
const handleOnCheckChange = (e: any) => {
checkvalueRef.current = e.target.checked;
};
const handleOnCollapse = (keys: string | string[]) => {
setActiveKey(keys);
};
const renderAdvancedFields = () => {
const formItems = TTSAdvancedParamsConfig.map((item: ParamsSchema) => {
const comProps = {
...item.attrs,
label: item.label.isLocalized
? intl.formatMessage({ id: item.label.text })
: item.label.text
};
return (
<>
<Form.Item
name={item.name}
rules={item.rules}
key={item.name}
{...item.formItemAttrs}
>
<FieldComponent
{...comProps}
description={
item.description?.isLocalized
? intl.formatMessage({ id: item.description.text })
: item.description?.text
}
onChange={null}
{..._.omit(item, [
'name',
'rules',
'disabledConfig',
'description'
])}
{...item.initAttrs?.(modelMeta)}
></FieldComponent>
</Form.Item>
</>
);
});
return (
<CollapsePanel
activeKey={activeKey}
onChange={handleOnCollapse}
accordion={false}
items={[
{
key: 'advanced_config',
label: intl.formatMessage({ id: 'resources.form.advanced' }),
forceRender: true,
children: (
<>
{formItems}
<RefAudioFormItem />
</>
)
}
]}
></CollapsePanel>
);
};
const renderExtra = () => {
return paramsConfig.map((item: ParamsSchema) => {
const comProps = {
...item.attrs,
options: item.name === 'voice' ? voiceList : item.options,
label: item.label.isLocalized
? intl.formatMessage({ id: item.label.text })
: item.label.text
};
return (
<>
<Form.Item name={item.name} rules={item.rules} key={item.name}>
{item.type === 'AutoComplete' ? (
<AutoComplete {...comProps} />
) : (
<SealSelect {...comProps}></SealSelect>
)}
</Form.Item>
</>
);
});
};
useEffect(() => {
if (defaultModel && modelList.length) {
handleSelectModel(defaultModel);
}
}, [defaultModel, modelList.length]);
useEffect(() => {
if (scroller.current) {
initialize(scroller.current);
}
}, [initialize]);
return (
<div className="ground-left-wrapper">
<div className="ground-left">
<div className="message-list-wrap">
<div
style={{
height: '100%',
display: 'flex',
justifyContent: 'center',
alignItems: 'center'
}}
>
<div className="content" style={{ maxWidth: 1000 }}>
{messageList.length ? (
<SpeechContent dataList={messageList} loading={loading} />
) : (
<div className="flex-column font-size-14 flex-center gap-20">
<span>
<IconFont
type="icon-audio "
className="font-size-32 text-secondary"
></IconFont>
</span>
<span>
{intl.formatMessage({
id: 'playground.audio.texttospeech.tips'
})}
</span>
</div>
)}
{loading && (
<Spin size="small">
<div style={{ height: '46px' }}></div>
</Spin>
)}
</div>
</div>
</div>
{tokenResult && (
<div style={{ height: 40 }}>
<AlertInfo
type="danger"
message={tokenResult?.errorMessage}
></AlertInfo>
</div>
)}
<div className="ground-left-footer">
<MessageInput
actions={['check']}
checkLabel={intl.formatMessage({
id: 'playground.toolbar.autoplay'
})}
placeholer={intl.formatMessage({
id: 'playground.input.text.holder'
})}
defaultSize={{
minRows: 5,
maxRows: 5
}}
title={intl.formatMessage({ id: 'playground.audio.textinput' })}
onCheck={handleOnCheckChange}
loading={loading}
disabled={!parameters.model}
isEmpty={true}
handleSubmit={handleSendMessage}
handleAbortFetch={handleStopConversation}
onInputChange={handleInputChange}
clearAll={handleClear}
shouldResetMessage={false}
/>
</div>
</div>
<RightContainer collapsed={collapse}>
<DynamicParams
ref={formRef}
meta={modelMeta}
onValuesChange={handleOnValuesChange}
initialValues={parameters}
modelList={modelList}
extra={[
<>
{renderExtra()}
{renderAdvancedFields()}
</>
]}
/>
</RightContainer>
<ViewCommonCode
open={show}
viewCodeContent={viewCodeContent}
onCancel={handleCloseViewCode}
title={intl.formatMessage({ id: 'playground.viewcode' })}
></ViewCommonCode>
</div>
);
});
export default GroundTTS;