HEL-900: preserve visual director custom voice frontend unchanged
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -4,12 +4,13 @@ import type { DemoState, Settings, Theme } from '../domain/model';
|
||||
import { delay } from '../adapters/demo';
|
||||
import { exportDemo, parseState } from '../adapters/storage';
|
||||
import { BaseColor, Button, Field, Icon, Modal, Status } from '../shared/ui';
|
||||
const sections = [['her', 'user', '她'], ['relation', 'heart', '关系'], ['city', 'pin', '城市'], ['appearance', 'image', '外观素材'], ['backup', 'box', '本地演示导出'], ['services', 'plug', '外接服务'], ['display', 'moon', '显示']];
|
||||
import { VoiceSection, type VoiceCap } from './VoiceSection';
|
||||
const sections = [['her', 'user', '她'], ['relation', 'heart', '关系'], ['voice', 'mic', '她的声音'], ['city', 'pin', '城市'], ['appearance', 'image', '外观素材'], ['backup', 'box', '本地演示导出'], ['services', 'plug', '外接服务'], ['display', 'moon', '显示']];
|
||||
// What each section can actually do here (HEL-815 capability tags): read-only, adjustable, demo only, not connected, this device.
|
||||
type Cap = 'ro' | 'edit' | 'demo' | 'off' | 'live' | 'local';
|
||||
const CAP: Record<Cap, [string, string]> = { ro: ['只读', ''], edit: ['可以调整', 'accent'], demo: ['演示数据', 'demo'], off: ['未接入', 'off'], live: ['文字已接通', 'ok'], local: ['本机生效', 'ok'] };
|
||||
const capOf = (id: string, real: boolean): Cap => id === 'her' ? 'ro' : id === 'relation' ? 'edit' : id === 'display' ? 'local' : id === 'services' && real ? 'live' : real ? 'off' : 'demo';
|
||||
const NOTE: Record<string, string> = { her: '只读资料', relation: '可以调整', display: '本机生效' };
|
||||
const capOf = (id: string, real: boolean, voice: VoiceCap = 'unknown'): Cap => id === 'her' ? 'ro' : id === 'relation' ? 'edit' : id === 'voice' ? real ? voice === 'off' ? 'off' : 'edit' : 'demo' : id === 'display' ? 'local' : id === 'services' && real ? 'live' : real ? 'off' : 'demo';
|
||||
const NOTE: Record<string, string> = { her: '只读资料', relation: '可以调整', voice: '上传 · 录音 · 试听', display: '本机生效' };
|
||||
function CapTag({ cap }: { cap: Cap }) { const [text, tone] = CAP[cap]; return <span className={`tag cap ${tone}`}>{text}</span>; }
|
||||
// Honest placeholder for a capability that is not connected: what it will do once connected, and that nothing happens now.
|
||||
function Off({ title, will, now }: { title: string; will: string; now: string }) { return <div className="off-card"><p className="off-t">{title}</p><p>{will}</p><p className="d-dim">{now}</p></div>; }
|
||||
@@ -32,10 +33,12 @@ export function ManagePanel({ state, open, onClose, onSave, fail, theme, setThem
|
||||
const approvedNavigation = useRef(false);
|
||||
const pendingNavigation = useRef<(() => void) | null>(null);
|
||||
const [serviceHealth, setServiceHealth] = useState<Health>();
|
||||
// 她的声音 (HEL-900): an unregistered reference counts as unsaved; the tag follows what the server reports.
|
||||
const [voiceDirty, setVoiceDirty] = useState(false), [voiceCap, setVoiceCap] = useState<VoiceCap>('unknown');
|
||||
const request = useRef<AbortController | null>(null), generation = useRef(0), feedback = useRef<HTMLDivElement>(null);
|
||||
useEffect(()=>{if(message) feedback.current?.scrollIntoView({block:'center'});},[message]);
|
||||
const latestState = useRef(state); latestState.current = state;
|
||||
const dirtySections: Record<string, boolean> = {relation: JSON.stringify(draft.identity)!==JSON.stringify(state.identity), city: !real && draft.settings.city!==state.settings.city, services: !real && JSON.stringify(draft.settings.services)!==JSON.stringify(state.settings.services), display: draft.settings.reduced!==state.settings.reduced};
|
||||
const dirtySections: Record<string, boolean> = {relation: JSON.stringify(draft.identity)!==JSON.stringify(state.identity), city: !real && draft.settings.city!==state.settings.city, services: !real && JSON.stringify(draft.settings.services)!==JSON.stringify(state.settings.services), display: draft.settings.reduced!==state.settings.reduced, voice: real && voiceDirty};
|
||||
const dirty = !!dirtySections[section], anyDirty = Object.values(dirtySections).some(Boolean);
|
||||
useEffect(() => { if (!open) {
|
||||
request.current?.abort();
|
||||
@@ -168,7 +171,7 @@ export function ManagePanel({ state, open, onClose, onSave, fail, theme, setThem
|
||||
<div><h4>后来慢慢有的<small>成长 · 单独记录</small></h4>{p?.growth.length ? <ul>{p.growth.map(g => <li key={g.id}>{g.text}<small>{SOURCE[g.source] || '有来处的成长'} · {day(g.ts)}</small></li>)}</ul> : <p className="d-dim">{!p ? '读取中…' : '还没有记下的成长。长期记忆尚未接通,聊天记录已独立保存。'}</p>}</div></div>;
|
||||
}
|
||||
const sectionLabel = (id: string) => real && id === 'backup' ? '备份' : sections.find(s => s[0] === id)?.[2] || '';
|
||||
return <section hidden={!open} className={`pane pane-manage glass read ${open ? 'open' : ''} ${detail ? 'has-detail' : ''}`} aria-label="设置"><header><div className="ttl"><small className="kicker"><span className="k-wide">慢慢安排你们的世界 · {real ? '服务器档案' : '仅本机演示'}</span><span className="k-near"><i/>她此刻 · {now || '安静待着'}</span></small><h2>设置</h2></div><span className="grow"/><span className="tag-demo">{real ? '服务器档案' : '仅本机演示'}</span><button className="btn-round sm" aria-label="关闭设置" onClick={() => requestLeave(onClose)}><Icon name="x"/></button></header><div className="cols"><nav className="snav" aria-label="设置分区">{sections.map(([id, icon]) => { const cap = capOf(id, real); return <button key={id} className={dirtySections[id] ? 'is-dirty' : ''} aria-current={section === id} onClick={() => switchSection(id)}><Icon name={icon}/><span className="sl">{sectionLabel(id)}<small aria-hidden="true">{NOTE[id] || CAP[cap][0]}</small></span><i className="dirty"/><span className="chev" aria-hidden="true"><Icon name="next"/></span></button>; })}<p className="snav-foot">首版只有一位她 · 没有重建或清空</p></nav><div className="detail"><button className="btn-text back" onClick={() => setDetail(false)}><Icon name="back"/>设置</button><div className="sec-body on"><div className="sec-h"><h3>{section === 'her' ? state.identity.name : sectionLabel(section)}</h3><CapTag cap={capOf(section, real)}/></div><p className="lead">{section === 'her' ? '她还是她。外观和关系的变化,都不会改写最初的底色。' : real ? '资料保存在服务器。尚未接通的功能写明接上以后能做什么,现在不会发生任何事。' : '所有修改仅用于本机演示。未接通的服务会明确说明。'}</p>
|
||||
return <section hidden={!open} className={`pane pane-manage glass read ${open ? 'open' : ''} ${detail ? 'has-detail' : ''}`} aria-label="设置"><header><div className="ttl"><small className="kicker"><span className="k-wide">慢慢安排你们的世界 · {real ? '服务器档案' : '仅本机演示'}</span><span className="k-near"><i/>她此刻 · {now || '安静待着'}</span></small><h2>设置</h2></div><span className="grow"/><span className="tag-demo">{real ? '服务器档案' : '仅本机演示'}</span><button className="btn-round sm" aria-label="关闭设置" onClick={() => requestLeave(onClose)}><Icon name="x"/></button></header><div className="cols"><nav className="snav" aria-label="设置分区">{sections.map(([id, icon]) => { const cap = capOf(id, real); return <button key={id} className={dirtySections[id] ? 'is-dirty' : ''} aria-current={section === id} onClick={() => switchSection(id)}><Icon name={icon}/><span className="sl">{sectionLabel(id)}<small aria-hidden="true">{NOTE[id] || CAP[cap][0]}</small></span><i className="dirty"/><span className="chev" aria-hidden="true"><Icon name="next"/></span></button>; })}<p className="snav-foot">首版只有一位她 · 没有重建或清空</p></nav><div className="detail"><button className="btn-text back" onClick={() => setDetail(false)}><Icon name="back"/>设置</button><div className="sec-body on"><div className="sec-h"><h3>{section === 'her' ? state.identity.name : sectionLabel(section)}</h3>{!(real && section === 'voice' && voiceCap === 'unknown') && <CapTag cap={capOf(section, real, voiceCap)}/>}</div><p className="lead">{section === 'her' ? '她还是她。外观和关系的变化,都不会改写最初的底色。' : section === 'voice' ? `换${state.identity.name}说话的声音:给一段参考声音,先试听,再给她用。只换声音,名字、底色、关系、聊天和记忆都不变。` : real ? '资料保存在服务器。尚未接通的功能写明接上以后能做什么,现在不会发生任何事。' : '所有修改仅用于本机演示。未接通的服务会明确说明。'}</p>
|
||||
{section === 'her' && <><dl className="kv"><dt>名字</dt><dd>{state.identity.name}<small>由你在初次创建时起的名字;首版不另设改名流程。</small></dd><dt>生辰</dt><dd>{state.identity.birth} · {state.identity.hour}<small><Icon name="lock"/>只读</small></dd></dl>
|
||||
<h4 className="sub-h">她的底色<small>系统资料 · 每轮对话都会重新带上 · 关系设定不能改写</small></h4><BaseColor color={real ? (state.identity as RealIdentity).color : undefined}/>
|
||||
<h4 className="sub-h">她怎么理解自己<small>模型诠释 · 会延续,也会变化</small></h4>{real ? personaView() : <Off title="演示不生成她对自己的诠释。" will="接上以后,这里是她在相处和生活里慢慢形成的自我理解,带版本和时间;不是固定模板,也不能直接改写。" now="现在这里不显示任何固定段落,避免把模板当成她的个性。"/>}
|
||||
@@ -178,6 +181,8 @@ export function ManagePanel({ state, open, onClose, onSave, fail, theme, setThem
|
||||
{!real && section === 'appearance' && <><div className="card">当前素材:{state.settings.appearance}<small className="d-foot">参考静帧,不代表最终人物素材。</small></div><Field label="选择本地素材清单(演示 JSON)" hint="真实素材包格式尚待定稿。只读 JSON,不加载清单中的 URL 或脚本。"><input type="file" accept=".json,application/json" onChange={e => void importMaterial(e.target.files?.[0])}/></Field>{check && <Status text={check} error={!material}/>} {material && <><div className="compare"><figure><img src="/assets/her-room.jpg" alt="当前参考"/><figcaption>当前参考</figcaption></figure><figure className="new"><img src="/assets/her-room.jpg" alt="新外观模拟效果"/><figcaption>模拟效果 · 未加载素材</figcaption></figure></div><Button primary onClick={() => setConfirm('appearance')}>应用演示外观标识</Button></>}<p className="d-foot">只演示检查、预览与确认。媒体真实性未校验,不声称完成素材导入。</p></>}
|
||||
{!real && section === 'backup' && <><div className="card"><h4>真实后台备份 · 未接通</h4><p>服务器每日备份、数据库和素材完整备份均未提供。本地文件不包含真实后台资料。</p></div><div className="card"><h4>你自己的演示资料</h4><p>包括本机档案、设置、文字、演示日子和回忆;不包含素材文件。</p><Button onClick={() => { exportDemo(state); setMessage('已生成本地演示 JSON 下载。'); setError(false); }}>导出本地演示 JSON</Button></div><Field label="恢复同一位她的本地演示 JSON"><input type="file" accept=".json,application/json" onChange={e => void importBackup(e.target.files?.[0])}/></Field>{restore && <Button onClick={() => { setConfirmText(''); setConfirm('restore'); }}>检查通过,继续恢复</Button>}</>}
|
||||
{!real && section === 'services' && <>{Object.entries(draft.settings.services).map(([key, value]) => <div className="svc" key={key}><div className="nm">{key}<small>未接通 · 测试仅演示,不发网络请求</small></div><Button onClick={() => { setMessage(`${key}:界面演示,未真实检测。相关功能暂不可用,文字演示仍可使用。`); setError(false); }}>测试连接</Button><input className="input" aria-label={`${key}地址`} value={value} placeholder="服务地址(只保存,不连接)" onChange={e => settings({ services: { ...draft.settings.services, [key]: e.target.value } })}/></div>)}<p className="d-foot">真实麦克风和摄像头未启用。视觉窗只允许模拟状态,观察过期不当作眼前。</p></>}
|
||||
{!real && section === 'voice' && <><Off title="演示里不录音,也不上传。" will="接上真实服务以后:上传或录一段参考声音 → 试听她用这个声音说话 → 给她之后的通话用。只换声音,名字、底色、关系、聊天和记忆都不变。" now="演示里不会请求麦克风,也不会发出任何网络请求。"/><div className="field"><div className="seg" role="group" aria-label="参考声音来源"><button disabled>上传音频文件</button><button disabled>现在录一段</button></div></div></>}
|
||||
{real && open && <div hidden={section !== 'voice'}><VoiceSection name={state.identity.name} active={section === 'voice'} onDirty={setVoiceDirty} onCap={setVoiceCap}/></div>}
|
||||
{section === 'display' && <><div className="opt-row">{(['moon', 'fog'] as Theme[]).map(t => <button className="opt" data-t={t} key={t} aria-pressed={theme === t} onClick={() => setTheme(t)}><div className="sw"/><b>{t === 'moon' ? '靛蓝月光' : '蓝紫雾光'}</b><span>立即切换,保留你的选择</span></button>)}</div><label className="switch-row"><span>减少动效<small>镜头不推近,只做淡入淡出;循环动画停下</small></span><input type="checkbox" className="switch" checked={draft.settings.reduced} onChange={e => settings({ reduced: e.target.checked })}/></label><p className="d-foot">也会自动尊重系统的减少动效设置。切到其他网页时暂停背景动画。</p></>}
|
||||
{real && section === 'city' && <><Off title="城市与天气还没有接上。" will="接上以后,你选一个真实城市,她房间里的天气、白天黑夜和作息都跟着那里走;换城市不需要每次重新定位。" now="现在窗外的雨是界面氛围,不是真实天气。尚未设置可核实的城市,天气来源尚未确定。"/><Field label="搜索城市" hint="可浏览候选目录;当前无法保存,不会更改她的城市。"><input className="input" value={search} placeholder="输入城市名称" onChange={e => setSearch(e.target.value)}/></Field><ul className="city-list">{['杭州', '上海', '北京', '成都', '广州', '深圳'].filter(c => c.includes(search.trim())).map(c => <li key={c}><button disabled>{c}<small>候选城市 · 保存待接入</small></button></li>)}</ul>{!['杭州', '上海', '北京', '成都', '广州', '深圳'].some(c => c.includes(search.trim())) && <div className="empty">当前目录没有匹配的城市。</div>}<div className="actions"><Button disabled>保存城市 · 待接入</Button></div></>}
|
||||
{real && section === 'appearance' && <><dl className="kv"><dt>现在的样子</dt><dd>工程外观 v2<small>参考静帧 · 尚无成套日常与交谈视频</small></dd></dl><Off title="换外观还没有接上。" will="接上以后:选择素材包 → 检查素材 → 看新旧对比 → 确认「她还是她」。只换样子,名字、底色、记忆和关系都不变。" now="素材包规范与导入检查尚未定稿。这里不会导入、预览或替换任何素材。"/><Field label="选择外观素材包" hint="素材包格式与媒体检查将在后续接入。当前不上传、不读取文件。"><input type="file" disabled/></Field><ul className="phases">{['清单结构与版本', '媒体格式与时长', '人物一致性', '必要场景覆盖', '可用性与兼容性'].map(label => <li key={label}>待检查 · {label}</li>)}</ul><div className="compare"><figure><img src="/assets/her-room.jpg" alt="当前内置参考静帧"/><figcaption>当前参考</figcaption></figure><figure><div className="empty">导入并通过检查后显示新外观</div><figcaption>新旧对比 · 待接入</figcaption></figure></div><Button disabled>确认应用外观 · 待接入</Button></>}
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
// ── 她的声音 (CG-010 v1.12, HEL-900): reference → fresh preview → apply, inside the approved settings pane. ──
|
||||
// Your reference and her synthesized preview are labelled apart and never stand in for each other. Every request and
|
||||
// every audio URL belongs to one generation; switching voice, retrying, leaving or a late answer throws the old one away
|
||||
// (request aborted, audio stopped, object URL revoked), so an old sample can never pass for the new one.
|
||||
import { useEffect, useRef, useState, type RefObject } from 'react';
|
||||
import { clockOf } from '../adapters/real';
|
||||
import { applyVoice, LABEL_MAX, listVoices, PREVIEW_DEFAULT, PREVIEW_MAX, previewVoice, Recorder, registerVoice, SAY, SUGGEST_MAX, SUGGEST_MIN, TEXT_MAX, toReference, VoiceError, type CustomVoice, type RecView, type VoiceSelection } from '../voice/custom';
|
||||
import { Button, Field, Icon, Status } from '../shared/ui';
|
||||
|
||||
export type VoiceCap = 'edit' | 'off' | 'unknown';
|
||||
type Load = { state: 'loading' } | { state: 'ok'; voices: CustomVoice[]; selection: VoiceSelection } | { state: 'off'; text: string } | { state: 'error'; text: string };
|
||||
interface Take { wav: Blob; url: string; seconds: number; from: 'file' | 'record'; name: string }
|
||||
interface Sample { voice: string; url: string; state: 'loading' | 'ready' | 'error' }
|
||||
const message = (e: unknown) => e instanceof VoiceError ? e.message : SAY.failed;
|
||||
const secs = (s: number) => `${s.toFixed(1)} 秒`;
|
||||
const clock = (s: number) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
|
||||
|
||||
// A small themed player instead of the browser's grey bar; the <audio> under it does the playing and reports canplay.
|
||||
function Pill({ src, label, auto = false, tone, audio, onReady, onBroken }: { src: string; label: string; auto?: boolean; tone: 'ref' | 'her'; audio: RefObject<HTMLAudioElement>; onReady?: () => void; onBroken?: () => void }) {
|
||||
const [playing, setPlaying] = useState(false), [at, setAt] = useState(0), [length, setLength] = useState(0);
|
||||
return <div className={`pill ${tone} ${playing ? 'on' : ''}`} role="group" aria-label={label}>
|
||||
<audio ref={audio} src={src} preload="auto" autoPlay={auto} onCanPlay={onReady} onError={onBroken} onPlay={() => setPlaying(true)} onPause={() => setPlaying(false)} onEnded={() => setPlaying(false)} onTimeUpdate={e => setAt(e.currentTarget.currentTime)} onLoadedMetadata={e => setLength(Number.isFinite(e.currentTarget.duration) ? e.currentTarget.duration : 0)}/>
|
||||
<button className="pill-play" aria-label={playing ? `暂停${label}` : `播放${label}`} onClick={() => { const a = audio.current; if (!a) return; if (a.paused) void a.play().catch(() => {}); else a.pause(); }}><Icon name={playing ? 'pause' : 'play'}/></button>
|
||||
<span className="pill-track" aria-hidden="true"><i style={{ transform: `scaleX(${length ? Math.min(1, at / length) : 0})` }}/></span>
|
||||
<span className="pill-time">{clock(at)} / {clock(length)}</span>
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function VoiceSection({ name, active, onDirty, onCap }: { name: string; active: boolean; onDirty: (dirty: boolean) => void; onCap: (cap: VoiceCap) => void }) {
|
||||
const [load, setLoad] = useState<Load>({ state: 'loading' }), [reads, setReads] = useState(0), [seen, setSeen] = useState(active);
|
||||
const [from, setFrom] = useState<'file' | 'record'>('file'), [rec, setRec] = useState<RecView>({ phase: 'idle', seconds: 0 });
|
||||
const [take, setTake] = useState<Take | null>(null), [form, setForm] = useState({ label: '', text: '', allowAsr: false });
|
||||
const [registering, setRegistering] = useState(false), [regNote, setRegNote] = useState<{ text: string; error: boolean }>({ text: '', error: false });
|
||||
const [candidate, setCandidate] = useState(''), [line, setLine] = useState(''), [sample, setSample] = useState<Sample | null>(null);
|
||||
const [applying, setApplying] = useState(false), [note, setNote] = useState<{ text: string; error: boolean }>({ text: '', error: false });
|
||||
const fileInput = useRef<HTMLInputElement>(null), player = useRef<HTMLAudioElement>(null), refPlayer = useRef<HTMLAudioElement>(null);
|
||||
// One controller per kind of request; a new one aborts the old. `takeGen` guards decoding a file or a recording.
|
||||
const ctl = useRef<Record<'list' | 'register' | 'preview' | 'apply', AbortController | null>>({ list: null, register: null, preview: null, apply: null });
|
||||
const takeGen = useRef(0), urls = useRef(new Set<string>()), listed = useRef(false);
|
||||
const fresh = (kind: keyof typeof ctl.current) => { ctl.current[kind]?.abort(); const c = new AbortController(); ctl.current[kind] = c; return c; };
|
||||
const own = (blob: Blob) => { const url = URL.createObjectURL(blob); urls.current.add(url); return url; };
|
||||
const drop = (url?: string) => { if (url && urls.current.delete(url)) URL.revokeObjectURL(url); };
|
||||
|
||||
const recorder = useRef<Recorder | null>(null);
|
||||
recorder.current ??= new Recorder({ view: setRec, done: blob => void accept(blob, 'record', '这次录音'), fail: text => setRegNote({ text, error: true }) });
|
||||
|
||||
// Everything this section holds goes with it: requests, microphone, audio and every object URL.
|
||||
useEffect(() => () => {
|
||||
recorder.current?.cancel();
|
||||
Object.values(ctl.current).forEach(c => c?.abort());
|
||||
takeGen.current++;
|
||||
for (const url of urls.current) URL.revokeObjectURL(url);
|
||||
urls.current.clear();
|
||||
}, []);
|
||||
// Out of sight is out of use: the microphone closes and nothing keeps playing. A finished take stays for later.
|
||||
useEffect(() => {
|
||||
if (active) { setSeen(true); return; }
|
||||
if (recorder.current?.busy && recorder.current.view.phase !== 'converting') { recorder.current.cancel(); setRegNote({ text: '离开了这里,录音已停止并丢弃,麦克风已关闭。', error: false }); }
|
||||
player.current?.pause(); refPlayer.current?.pause();
|
||||
}, [active]);
|
||||
useEffect(() => { onDirty(!!take); return () => onDirty(false); }, [take, onDirty]);
|
||||
|
||||
// Read the list the first time the section is opened (and on retry). Reading never touches the microphone.
|
||||
useEffect(() => {
|
||||
if (!seen) return;
|
||||
const c = fresh('list');
|
||||
setLoad(l => l.state === 'ok' ? l : { state: 'loading' });
|
||||
listVoices(c.signal).then(list => {
|
||||
if (c.signal.aborted) return;
|
||||
if (!list.configured) { setLoad({ state: 'off', text: SAY.notConfigured }); onCap('off'); return; }
|
||||
listed.current = true; setNote(n => n.error ? { text: '', error: false } : n); setLoad({ state: 'ok', voices: list.voices, selection: list.selection }); onCap('edit');
|
||||
}, e => {
|
||||
if (c.signal.aborted) return;
|
||||
const status = e instanceof VoiceError ? e.status : 0;
|
||||
if (status === 404 || status === 405) { setLoad({ state: 'off', text: SAY.noRoute }); onCap('off'); return; }
|
||||
// A list already on screen stays usable; only the first read turns into the retry card.
|
||||
if (listed.current) { setNote({ text: message(e), error: true }); return; }
|
||||
setLoad({ state: 'error', text: message(e) }); onCap('unknown');
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- re-read only on first sight and explicit retries.
|
||||
}, [seen, reads]);
|
||||
|
||||
async function accept(input: Blob, kind: 'file' | 'record', label: string) {
|
||||
const gen = ++takeGen.current;
|
||||
setRegNote({ text: kind === 'file' ? '正在读取并转成 WAV…' : '', error: false });
|
||||
try {
|
||||
const ref = await toReference(input);
|
||||
if (gen !== takeGen.current) return;
|
||||
const url = own(ref.wav);
|
||||
setTake(old => { drop(old?.url); return { wav: ref.wav, url, seconds: ref.seconds, from: kind, name: label }; });
|
||||
setRegNote({ text: '', error: false });
|
||||
} catch (e) {
|
||||
if (gen !== takeGen.current) return;
|
||||
setRegNote({ text: message(e), error: true });
|
||||
} finally { if (gen === takeGen.current) recorder.current?.settled(); }
|
||||
}
|
||||
function chooseFile(file?: File) {
|
||||
if (fileInput.current) fileInput.current.value = '';
|
||||
if (!file || registering) return;
|
||||
void accept(file, 'file', file.name.slice(0, 60));
|
||||
}
|
||||
function discardTake() { takeGen.current++; recorder.current?.cancel(); setTake(old => { drop(old?.url); return null; }); setRegNote({ text: '', error: false }); }
|
||||
function switchFrom(next: 'file' | 'record') { if (next === from) return; recorder.current?.cancel(); setFrom(next); setRegNote({ text: '', error: false }); }
|
||||
|
||||
const text = form.text.trim(), needText = !text && !form.allowAsr;
|
||||
async function register() {
|
||||
// A second tap before the first answer is ignored (not a replacement): the first upload may already be on the server.
|
||||
if (!take || ctl.current.register || needText) return;
|
||||
const c = fresh('register'), sent = take;
|
||||
setRegistering(true); setRegNote({ text: form.allowAsr && !text ? '正在登记,并让服务器把这段声音转写成文字…' : '正在登记这段声音…', error: false });
|
||||
try {
|
||||
const done = await registerVoice(sent.wav, form, c.signal);
|
||||
if (c.signal.aborted) return;
|
||||
setTake(old => { if (old === sent) { drop(old.url); return null; } return old; });
|
||||
setForm({ label: '', text: '', allowAsr: false });
|
||||
setRegNote({ text: done.prompt_text_source === 'asr' ? `登记好了:「${done.label}」。服务器转写的参考文字是:${done.prompt_text || '(空)'}` : `登记好了:「${done.label}」。`, error: false });
|
||||
setLoad(l => l.state === 'ok' && !l.voices.some(v => v.id === done.id) ? { ...l, voices: [...l.voices, { id: done.id, label: done.label, source: 'custom', selected: false, previewed: false, registered_at: Date.now() }] } : l);
|
||||
pick(done.id, `先听听${name}用「${done.label}」说话,再决定要不要给她用。`);
|
||||
setReads(n => n + 1);
|
||||
} catch (e) {
|
||||
if (c.signal.aborted) return;
|
||||
// Nothing is lost on failure: the take, the label and the text all stay for another try.
|
||||
setRegNote({ text: message(e), error: true });
|
||||
} finally { if (ctl.current.register === c) { ctl.current.register = null; setRegistering(false); } }
|
||||
}
|
||||
|
||||
// Choosing another voice retires the sample of the previous one at once.
|
||||
function pick(id: string, say = '') {
|
||||
ctl.current.preview?.abort(); ctl.current.preview = null;
|
||||
player.current?.pause();
|
||||
setSample(old => { drop(old?.url); return null; });
|
||||
setCandidate(id); setNote({ text: say, error: false });
|
||||
}
|
||||
async function preview() {
|
||||
if (!candidate) return;
|
||||
const c = fresh('preview'), voice = candidate;
|
||||
player.current?.pause();
|
||||
setSample(old => { drop(old?.url); return { voice, url: '', state: 'loading' }; });
|
||||
setNote({ text: '正在用这个声音现场合成…', error: false });
|
||||
try {
|
||||
const wav = await previewVoice(voice, line, c.signal);
|
||||
if (c.signal.aborted) return;
|
||||
// Shown only once the browser has really loaded it (canplay); until then it is not "heard".
|
||||
const url = own(wav);
|
||||
setSample({ voice, url, state: 'loading' });
|
||||
} catch (e) {
|
||||
if (c.signal.aborted) return;
|
||||
setSample(null); setNote({ text: message(e), error: true });
|
||||
}
|
||||
}
|
||||
const playable = (url: string) => { setSample(s => s && s.url === url && s.state === 'loading' ? { ...s, state: 'ready' } : s); setNote(n => n.error ? n : { text: '', error: false }); };
|
||||
const unplayable = (url: string) => { setSample(s => { if (!s || s.url !== url) return s; drop(url); return null; }); setNote({ text: SAY.unplayable, error: true }); };
|
||||
|
||||
async function apply() {
|
||||
if (!candidate || ctl.current.apply || sample?.voice !== candidate || sample.state !== 'ready') return;
|
||||
const c = fresh('apply'), voice = candidate;
|
||||
setApplying(true); setNote({ text: '正在给她换上…', error: false });
|
||||
try {
|
||||
const selection = await applyVoice(voice, c.signal);
|
||||
if (c.signal.aborted) return;
|
||||
setLoad(l => l.state === 'ok' ? { ...l, selection, voices: l.voices.map(v => ({ ...v, selected: v.id === voice, previewed: v.previewed || v.id === voice })) } : l);
|
||||
setNote({ text: `好了,${name}之后的通话会用「${selection.label || voice}」。已经接通的通话不会中途换声。名字、底色、关系、聊天和记忆都没有变。`, error: false });
|
||||
} catch (e) {
|
||||
if (c.signal.aborted) return;
|
||||
setNote({ text: message(e), error: true });
|
||||
} finally { if (ctl.current.apply === c) { ctl.current.apply = null; setApplying(false); } }
|
||||
}
|
||||
|
||||
if (load.state === 'loading') return <div className="skel" aria-hidden="true">{[70, 54, 62].map(w => <i key={w} style={{ width: `${w}%` }}/>)}</div>;
|
||||
if (load.state === 'off') return <div className="off-card"><p className="off-t">{load.text}</p><p>接上以后:上传或录一段参考声音 → 试听{name}用它说话 → 给她用。只换声音,名字、底色、关系、聊天和记忆都不变。</p><p className="d-dim">这里不会请求麦克风,也不会上传任何声音。</p></div>;
|
||||
if (load.state === 'error') return <div className="off-card" role="alert"><p className="off-t">声音列表一时没读出来。</p><p>{load.text}</p><Button onClick={() => setReads(n => n + 1)}>再试一次</Button></div>;
|
||||
|
||||
const { voices, selection } = load, current = voices.find(v => v.id === selection.voice);
|
||||
const mine = voices.filter(v => v.source === 'custom'), builtin = voices.filter(v => v.source === 'builtin');
|
||||
const chosen = voices.find(v => v.id === candidate), ready = sample?.voice === candidate && sample.state === 'ready';
|
||||
const recording = rec.phase === 'asking' || rec.phase === 'recording';
|
||||
const row = (v: CustomVoice) => <li key={v.id}><button aria-pressed={candidate === v.id} onClick={() => pick(v.id)} disabled={applying}><span>{v.label}{v.selected && <span className="tag accent">正在用</span>}</span><small>{v.source === 'custom' ? `自定义${v.registered_at ? ` · ${clockOf(v.registered_at).date}` : ''}` : '服务自带'}{v.previewed ? ' · 试听过' : ''}</small></button></li>;
|
||||
|
||||
return <div className="voice-sec">
|
||||
<dl className="kv"><dt>现在的声音</dt><dd>{selection.voice ? <>{current?.label || selection.label || selection.voice}<small>{current?.source === 'custom' ? '自定义' : current ? '服务自带' : '这个声音已不在列表里,通话时会用默认声音'}{selection.updated_at ? ` · ${clockOf(selection.updated_at).date} ${clockOf(selection.updated_at).time} 换上` : ''}</small></> : <>还没有为她选过<small>通话时用服务默认的声音</small></>}</dd>
|
||||
<dt>什么时候生效</dt><dd>下一次通话<small>已经接通的通话不会中途换声</small></dd></dl>
|
||||
|
||||
<h4 className="sub-h">给一段参考声音<small>{SUGGEST_MIN}–{SUGGEST_MAX} 秒 · 安静的地方 · 念一两句完整的话</small></h4>
|
||||
<div className="field"><div className="seg" role="group" aria-label="参考声音来源">{([['file', '上传音频文件'], ['record', '现在录一段']] as const).map(([k, label]) => <button key={k} aria-pressed={from === k} disabled={registering || rec.phase === 'converting'} onClick={() => switchFrom(k)}>{label}</button>)}</div></div>
|
||||
{from === 'file' ? <div className="field file-pick"><label className={`btn-ghost sm ${registering ? 'is-disabled' : ''}`}><Icon name="up"/>选择音频文件<input ref={fileInput} type="file" accept=".wav,audio/wav,audio/*" disabled={registering} onChange={e => chooseFile(e.target.files?.[0])}/></label><small>WAV 最稳妥;其他格式要看这个浏览器能不能解开,解不开会直接说明。会转成 16kHz 单声道 WAV,只登记到这台服务器。</small></div>
|
||||
: <div className={`rec card ${recording ? 'on' : ''}`} data-phase={rec.phase}>
|
||||
{rec.phase === 'idle' && <><Button onClick={() => { setRegNote({ text: '', error: false }); void recorder.current?.start(); }} disabled={registering}><Icon name="mic"/>开始录音</Button><p className="d-dim">点了才会请求麦克风,只录声音。停止、取消或离开这里,麦克风马上关闭。最长 {SUGGEST_MAX} 秒,到时自动停。</p></>}
|
||||
{rec.phase === 'asking' && <><p className="rec-line" role="status"><i className="rec-dot"/>正在请求麦克风…</p><Button onClick={() => recorder.current?.cancel()}>取消</Button></>}
|
||||
{rec.phase === 'recording' && <><p className="rec-line" role="status" aria-live="off"><i className="rec-dot"/>正在录音 · 麦克风开着<b>{clock(rec.seconds)} / {clock(SUGGEST_MAX)}</b></p><div className="rec-bar" aria-hidden="true"><i style={{ transform: `scaleX(${Math.min(1, rec.seconds / SUGGEST_MAX)})` }}/><em style={{ left: `${SUGGEST_MIN / SUGGEST_MAX * 100}%` }}/></div><div className="rec-acts"><Button primary onClick={() => recorder.current?.stop()}><Icon name="stop"/>停止,用这段</Button><Button onClick={() => { recorder.current?.cancel(); setRegNote({ text: '录音已取消并丢弃,麦克风已关闭。', error: false }); }}>取消</Button></div></>}
|
||||
{rec.phase === 'converting' && <p className="rec-line" role="status">麦克风已关闭 · 正在转成 WAV…</p>}
|
||||
</div>}
|
||||
|
||||
{take && <div className="card take">
|
||||
<h4><Icon name="user"/>参考原声 · 你给的声音,不是{name}的声音</h4>
|
||||
<Pill key={take.url} src={take.url} label="参考原声" tone="ref" audio={refPlayer}/>
|
||||
<p className="d-dim">{take.from === 'record' ? '这次录音' : take.name} · 已转为 WAV · 16kHz 单声道 16 位 · {secs(take.seconds)}{take.seconds < SUGGEST_MIN ? ` · 偏短,建议 ${SUGGEST_MIN} 秒以上` : take.seconds > SUGGEST_MAX ? ` · 偏长,建议 ${SUGGEST_MAX} 秒以内` : ''}</p>
|
||||
<Field label="给这个声音起个名字" hint={`最多 ${LABEL_MAX} 个字,只用来在这里区分;不填就用编号。`}><input className="input" value={form.label} maxLength={LABEL_MAX} placeholder="比如:轻一点的她" disabled={registering} onChange={e => setForm(f => ({ ...f, label: e.target.value.replace(/[<>\p{Cc}]/gu, '') }))}/></Field>
|
||||
<Field label="参考文字" hint="这段声音里念的原话。写得越准,克隆越像。"><textarea className="textarea" value={form.text} maxLength={TEXT_MAX} rows={2} disabled={registering} placeholder="照着录音里念的内容写下来" onChange={e => setForm(f => ({ ...f, text: e.target.value }))}/></Field>
|
||||
<label className="switch-row"><span>参考文字留空时,允许服务器转写<small>{text ? '已经填写了参考文字,不会转写。' : '会用这台服务器上的语音识别听一遍这段声音;不打开就必须填写参考文字。'}</small></span><input type="checkbox" className="switch" checked={form.allowAsr && !text} disabled={!!text || registering} onChange={e => setForm(f => ({ ...f, allowAsr: e.target.checked }))}/></label>
|
||||
<div className="take-acts"><Button primary disabled={registering || needText} onClick={() => void register()}>{registering ? '正在登记…' : '登记这段声音'}</Button><Button disabled={registering} onClick={discardTake}>换一段</Button></div>
|
||||
{needText && !registering && <p className="d-dim">填写参考文字,或打开上面的转写开关,才能登记。</p>}
|
||||
</div>}
|
||||
<Status text={regNote.text} error={regNote.error}/>
|
||||
|
||||
<h4 className="sub-h">可以给她用的声音<small>先试听,再给她用</small></h4>
|
||||
<p className="voice-group">你给的声音</p>
|
||||
{mine.length ? <ul className="city-list voice-list">{mine.map(row)}</ul> : <div className="empty sm">还没有登记过自己的声音。</div>}
|
||||
{builtin.length > 0 && <details className="voice-builtin" open={!!chosen && chosen.source === 'builtin'}><summary>服务自带的声音 · {builtin.length} 个</summary><ul className="city-list voice-list">{builtin.map(row)}</ul></details>}
|
||||
|
||||
{chosen && <div className="card audition" aria-live="polite">
|
||||
<h4><Icon name="sparkle"/>试听 · {chosen.label}</h4>
|
||||
<Field label="试听这句话" hint={`可以换成你想听的话,最多 ${PREVIEW_MAX} 个字。每次都是现场合成,不拿旧的冒充。`}><input className="input" value={line} maxLength={PREVIEW_MAX} placeholder={PREVIEW_DEFAULT} onChange={e => setLine(e.target.value)}/></Field>
|
||||
<div className="take-acts"><Button disabled={sample?.state === 'loading' || applying} onClick={() => void preview()}>{sample?.state === 'loading' ? '正在现场合成…' : sample ? '再听一次' : '生成试听'}</Button>
|
||||
{chosen.selected ? <span className="tag accent">她现在就用这个</span> : <Button primary disabled={!ready || applying} onClick={() => void apply()}>{applying ? '正在换上…' : `给${name}用这个声音`}</Button>}</div>
|
||||
{sample?.url && <figure className={`sample ${ready ? 'ready' : ''}`}><Pill key={sample.url} src={sample.url} label="试听" tone="her" auto audio={player} onReady={() => playable(sample.url)} onBroken={() => unplayable(sample.url)}/><figcaption>{name}用「{chosen.label}」说的 · 刚刚现场合成 · 不是参考原声</figcaption></figure>}
|
||||
{!ready && !chosen.selected && <p className="d-dim">听过这次现场合成的试听,才能给她用。</p>}
|
||||
</div>}
|
||||
<Status text={note.text} error={note.error}/>
|
||||
<p className="d-foot">换声音只换她说话的声音:名字、出生底色、关系、聊天和记忆都不变,也不会重新创建她。声音登记在这台服务器上;暂时不能在这里删除登记过的声音。</p>
|
||||
</div>;
|
||||
}
|
||||
Reference in New Issue
Block a user