Open History to see the last commit
1import { useEffect, useMemo, useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { useGenerateSpeech } from '@tanstack/ai-react'
4import type { UseGenerateSpeechReturn } from '@tanstack/ai-react'
5import { fetchServerSentEvents } from '@tanstack/ai-client'
6import { byteplusVoiceByok } from '@tanstack/ai-byteplus/byok'
7import { generateSpeechFn, generateSpeechStreamFn } from '../lib/server-fns'
8import { byok } from '../lib/byok'
9import {
10 SPEECH_PROVIDERS,
11 type SpeechProviderConfig,
12 type SpeechProviderId,
13} from '../lib/audio-providers'
14
15type SpeechOutput = { audioUrl: string; format?: string; duration?: number }
16
17type Mode = 'streaming' | 'direct' | 'server-fn'
18
19// Persist each variant's lightweight resume snapshot across reloads.
20
21function toSpeechOutput(raw: {
22 audio: string
23 contentType?: string
24 format?: string
25 duration?: number
26}): SpeechOutput {
27 const audioData = atob(raw.audio)
28 const bytes = new Uint8Array(audioData.length)
29 for (let i = 0; i < audioData.length; i++) {
30 bytes[i] = audioData.charCodeAt(i)
31 }
32 const blob = new Blob([bytes], {
33 type: raw.contentType ?? 'audio/mpeg',
34 })
35 return {
36 audioUrl: URL.createObjectURL(blob),
37 format: raw.format,
38 duration: raw.duration,
39 }
40}
41
42function SpeechGenerationForm({
43 mode,
44 config,
45}: {
46 mode: Mode
47 config: SpeechProviderConfig
48}) {
49 const [text, setText] = useState('')
50 const [voice, setVoice] = useState(config.voices[0]?.id ?? '')
51
52 const hookOptions = useMemo(() => {
53 if (mode === 'streaming') {
54 return {
55 threadId: `speech:${mode}:${config.id}`,
56 connection: fetchServerSentEvents('/api/generate/speech'),
57 body: { provider: config.id },
58 persistence: true,
59 onResult: toSpeechOutput,
60 ...(config.id === 'byteplus'
61 ? { byok, byokProvider: () => byteplusVoiceByok.id }
62 : {}),
63 }
64 }
65 if (mode === 'direct') {
66 return {
67 threadId: `speech:${mode}:${config.id}`,
68 // `text` is optional on the hook's input because a dialogue request
69 // sends `turns` instead. This form only sends text, so default it.
70 fetcher: (
71 input: { text?: string; voice?: string },
72 { threadId }: { threadId: string },
73 ) =>
74 generateSpeechFn({
75 data: {
76 ...input,
77 text: input.text ?? '',
78 provider: config.id,
79 threadId,
80 },
81 }),
82 persistence: true,
83 onResult: toSpeechOutput,
84 }
85 }
86 return {
87 threadId: `speech:${mode}:${config.id}`,
88 fetcher: (
89 input: { text?: string; voice?: string },
90 { threadId }: { threadId: string },
91 ) =>
92 generateSpeechStreamFn({
93 data: {
94 ...input,
95 text: input.text ?? '',
96 provider: config.id,
97 threadId,
98 },
99 }),
100 persistence: true,
101 onResult: toSpeechOutput,
102 }
103 }, [mode, config.id])
104
105 const hookReturn = useGenerateSpeech(hookOptions)
106
107 return (
108 <SpeechGenerationUI
109 {...hookReturn}
110 config={config}
111 text={text}
112 setText={setText}
113 voice={voice}
114 setVoice={setVoice}
115 />
116 )
117}
118
119function SpeechGenerationUI({
120 config,
121 text,
122 setText,
123 voice,
124 setVoice,
125 generate,
126 result,
127 isLoading,
128 error,
129 reset,
130}: UseGenerateSpeechReturn<SpeechOutput> & {
131 config: SpeechProviderConfig
132 text: string
133 setText: (v: string) => void
134 voice: string
135 setVoice: (v: string) => void
136}) {
137 const handleGenerate = () => {
138 if (!text.trim()) return
139 generate({ text: text.trim(), voice })
140 }
141
142 // Track the last object URL we created so we can revoke it when the
143 // result changes, reset is invoked, or the component unmounts.
144 const lastBlobUrlRef = useRef<string | null>(null)
145 useEffect(() => {
146 const current = result?.audioUrl
147 if (current && current.startsWith('blob:')) {
148 if (lastBlobUrlRef.current && lastBlobUrlRef.current !== current) {
149 URL.revokeObjectURL(lastBlobUrlRef.current)
150 }
151 lastBlobUrlRef.current = current
152 } else if (!current && lastBlobUrlRef.current) {
153 URL.revokeObjectURL(lastBlobUrlRef.current)
154 lastBlobUrlRef.current = null
155 }
156 }, [result?.audioUrl])
157 useEffect(() => {
158 return () => {
159 if (lastBlobUrlRef.current) {
160 URL.revokeObjectURL(lastBlobUrlRef.current)
161 lastBlobUrlRef.current = null
162 }
163 }
164 }, [])
165
166 return (
167 <div className="space-y-6">
168 <div className="space-y-3">
169 <label className="text-sm text-gray-400">Text</label>
170 <textarea
171 data-testid="speech-text-input"
172 value={text}
173 onChange={(e) => setText(e.target.value)}
174 placeholder={config.placeholder}
175 className="w-full rounded-lg border border-orange-500/20 bg-gray-800/50 px-4 py-3 text-sm text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-orange-500/50 resize-none"
176 rows={4}
177 disabled={isLoading}
178 />
179 </div>
180
181 <div className="space-y-3">
182 <label className="text-sm text-gray-400">Voice</label>
183 <div className="flex flex-wrap gap-2">
184 {config.voices.map((v) => (
185 <button
186 key={v.id}
187 onClick={() => setVoice(v.id)}
188 data-testid={`voice-${v.id}`}
189 className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
190 voice === v.id
191 ? 'bg-orange-600 text-white'
192 : 'bg-gray-800 text-gray-300 hover:bg-gray-700'
193 }`}
194 >
195 {v.label}
196 </button>
197 ))}
198 </div>
199 </div>
200
201 <div className="flex gap-3">
202 <button
203 onClick={handleGenerate}
204 disabled={!text.trim() || isLoading}
205 data-testid="speech-generate-button"
206 className="px-6 py-2 bg-orange-600 hover:bg-orange-700 disabled:bg-gray-700 disabled:text-gray-500 text-white rounded-lg text-sm font-medium transition-colors"
207 >
208 {isLoading ? 'Generating...' : 'Generate Speech'}
209 </button>
210 {result && (
211 <button
212 onClick={reset}
213 className="px-6 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg text-sm font-medium transition-colors"
214 >
215 Clear
216 </button>
217 )}
218 </div>
219
220 {error && (
221 <div
222 data-testid="speech-error"
223 className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg"
224 >
225 <p className="text-red-400 text-sm">{error.message}</p>
226 </div>
227 )}
228
229 {result && (
230 <div className="p-4 bg-gray-800/50 border border-gray-700 rounded-lg space-y-3">
231 <p className="text-sm text-gray-400">
232 Model: <span className="text-gray-200">{config.model}</span>
233 {result.format != null && ` | Format: ${result.format}`}
234 {result.duration != null && ` | Duration: ${result.duration}s`}
235 </p>
236 <audio
237 data-testid="speech-audio"
238 src={result.audioUrl}
239 controls
240 className="w-full"
241 />
242 </div>
243 )}
244 </div>
245 )
246}
247
248function SpeechGenerationPage() {
249 const [mode, setMode] = useState<Mode>('streaming')
250 const [provider, setProvider] = useState<SpeechProviderId>('openai')
251
252 const config = SPEECH_PROVIDERS.find((p) => p.id === provider)!
253
254 return (
255 <div className="flex flex-col h-[calc(100vh-72px)] bg-gray-900 text-white">
256 <div className="border-b border-orange-500/20 bg-gray-800 px-6 py-4">
257 <div className="flex items-center justify-between">
258 <div>
259 <h2 className="text-xl font-semibold">Text-to-Speech</h2>
260 <p className="text-sm text-gray-400 mt-1">
261 Convert text to spoken audio. Try each provider to compare voices
262 and quality.
263 </p>
264 </div>
265 <div className="flex gap-1 bg-gray-900/50 rounded-lg p-1">
266 {(['streaming', 'direct', 'server-fn'] as const).map((m) => (
267 <button
268 key={m}
269 onClick={() => setMode(m)}
270 className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${
271 mode === m
272 ? 'bg-orange-600 text-white'
273 : 'text-gray-400 hover:text-white'
274 }`}
275 >
276 {m === 'server-fn'
277 ? 'Server Fn'
278 : m[0].toUpperCase() + m.slice(1)}
279 </button>
280 ))}
281 </div>
282 </div>
283 </div>
284
285 <div className="border-b border-orange-500/20 bg-gray-800/60 px-6 py-3">
286 <div className="flex flex-wrap gap-2">
287 {SPEECH_PROVIDERS.map((p) => (
288 <button
289 key={p.id}
290 data-testid={`provider-tab-${p.id}`}
291 onClick={() => setProvider(p.id)}
292 className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${
293 provider === p.id
294 ? 'bg-orange-500/80 text-white'
295 : 'bg-gray-900 text-gray-300 hover:bg-gray-700'
296 }`}
297 >
298 {p.label}
299 </button>
300 ))}
301 </div>
302 </div>
303
304 <div className="flex-1 overflow-y-auto p-6">
305 <div className="max-w-2xl mx-auto">
306 <SpeechGenerationForm
307 key={`${mode}-${config.id}`}
308 mode={mode}
309 config={config}
310 />
311 </div>
312 </div>
313 </div>
314 )
315}
316
317export const Route = createFileRoute('/generations/speech')({
318 component: SpeechGenerationPage,
319})