Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

generations.speech.tsx

303 lines9.3 KB

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 }
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: (input: { text?: string; voice?: string }) =>
71 generateSpeechFn({
72 data: { ...input, text: input.text ?? '', provider: config.id },
73 }),
74 persistence: true,
75 onResult: toSpeechOutput,
76 }
77 }
78 return {
79 threadId: `speech:${mode}:${config.id}`,
80 fetcher: (input: { text?: string; voice?: string }) =>
81 generateSpeechStreamFn({
82 data: { ...input, text: input.text ?? '', provider: config.id },
83 }),
84 persistence: true,
85 onResult: toSpeechOutput,
86 }
87 }, [mode, config.id])
88​
89 const hookReturn = useGenerateSpeech(hookOptions)
90​
91 return (
92 <SpeechGenerationUI
93 {...hookReturn}
94 config={config}
95 text={text}
96 setText={setText}
97 voice={voice}
98 setVoice={setVoice}
99 />
100 )
102​
103function SpeechGenerationUI({
104 config,
105 text,
106 setText,
107 voice,
108 setVoice,
109 generate,
110 result,
111 isLoading,
112 error,
113 reset,
114}: UseGenerateSpeechReturn<SpeechOutput> & {
115 config: SpeechProviderConfig
116 text: string
117 setText: (v: string) => void
118 voice: string
119 setVoice: (v: string) => void
120}) {
121 const handleGenerate = () => {
122 if (!text.trim()) return
123 generate({ text: text.trim(), voice })
124 }
125​
126 // Track the last object URL we created so we can revoke it when the
127 // result changes, reset is invoked, or the component unmounts.
128 const lastBlobUrlRef = useRef<string | null>(null)
129 useEffect(() => {
130 const current = result?.audioUrl
131 if (current && current.startsWith('blob:')) {
132 if (lastBlobUrlRef.current && lastBlobUrlRef.current !== current) {
133 URL.revokeObjectURL(lastBlobUrlRef.current)
134 }
135 lastBlobUrlRef.current = current
136 } else if (!current && lastBlobUrlRef.current) {
137 URL.revokeObjectURL(lastBlobUrlRef.current)
138 lastBlobUrlRef.current = null
139 }
140 }, [result?.audioUrl])
141 useEffect(() => {
142 return () => {
143 if (lastBlobUrlRef.current) {
144 URL.revokeObjectURL(lastBlobUrlRef.current)
145 lastBlobUrlRef.current = null
146 }
147 }
148 }, [])
149​
150 return (
151 <div className="space-y-6">
152 <div className="space-y-3">
153 <label className="text-sm text-gray-400">Text</label>
154 <textarea
155 data-testid="speech-text-input"
156 value={text}
157 onChange={(e) => setText(e.target.value)}
158 placeholder={config.placeholder}
159 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"
160 rows={4}
161 disabled={isLoading}
162 />
163 </div>
164​
165 <div className="space-y-3">
166 <label className="text-sm text-gray-400">Voice</label>
167 <div className="flex flex-wrap gap-2">
168 {config.voices.map((v) => (
169 <button
170 key={v.id}
171 onClick={() => setVoice(v.id)}
172 data-testid={`voice-${v.id}`}
173 className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
174 voice === v.id
175 ? 'bg-orange-600 text-white'
176 : 'bg-gray-800 text-gray-300 hover:bg-gray-700'
177 }`}
178 >
179 {v.label}
180 </button>
181 ))}
182 </div>
183 </div>
184​
185 <div className="flex gap-3">
186 <button
187 onClick={handleGenerate}
188 disabled={!text.trim() || isLoading}
189 data-testid="speech-generate-button"
190 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"
191 >
192 {isLoading ? 'Generating...' : 'Generate Speech'}
193 </button>
194 {result && (
195 <button
196 onClick={reset}
197 className="px-6 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg text-sm font-medium transition-colors"
198 >
199 Clear
200 </button>
201 )}
202 </div>
203​
204 {error && (
205 <div
206 data-testid="speech-error"
207 className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg"
208 >
209 <p className="text-red-400 text-sm">{error.message}</p>
210 </div>
211 )}
212​
213 {result && (
214 <div className="p-4 bg-gray-800/50 border border-gray-700 rounded-lg space-y-3">
215 <p className="text-sm text-gray-400">
216 Model: <span className="text-gray-200">{config.model}</span>
217 {result.format != null && ` | Format: ${result.format}`}
218 {result.duration != null && ` | Duration: ${result.duration}s`}
219 </p>
220 <audio
221 data-testid="speech-audio"
222 src={result.audioUrl}
223 controls
224 className="w-full"
225 />
226 </div>
227 )}
228 </div>
229 )
231​
232function SpeechGenerationPage() {
233 const [mode, setMode] = useState<Mode>('streaming')
234 const [provider, setProvider] = useState<SpeechProviderId>('openai')
235​
236 const config = SPEECH_PROVIDERS.find((p) => p.id === provider)!
237​
238 return (
239 <div className="flex flex-col h-[calc(100vh-72px)] bg-gray-900 text-white">
240 <div className="border-b border-orange-500/20 bg-gray-800 px-6 py-4">
241 <div className="flex items-center justify-between">
242 <div>
243 <h2 className="text-xl font-semibold">Text-to-Speech</h2>
244 <p className="text-sm text-gray-400 mt-1">
245 Convert text to spoken audio. Try each provider to compare voices
246 and quality.
247 </p>
248 </div>
249 <div className="flex gap-1 bg-gray-900/50 rounded-lg p-1">
250 {(['streaming', 'direct', 'server-fn'] as const).map((m) => (
251 <button
252 key={m}
253 onClick={() => setMode(m)}
254 className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${
255 mode === m
256 ? 'bg-orange-600 text-white'
257 : 'text-gray-400 hover:text-white'
258 }`}
259 >
260 {m === 'server-fn'
261 ? 'Server Fn'
262 : m[0].toUpperCase() + m.slice(1)}
263 </button>
264 ))}
265 </div>
266 </div>
267 </div>
268​
269 <div className="border-b border-orange-500/20 bg-gray-800/60 px-6 py-3">
270 <div className="flex flex-wrap gap-2">
271 {SPEECH_PROVIDERS.map((p) => (
272 <button
273 key={p.id}
274 data-testid={`provider-tab-${p.id}`}
275 onClick={() => setProvider(p.id)}
276 className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${
277 provider === p.id
278 ? 'bg-orange-500/80 text-white'
279 : 'bg-gray-900 text-gray-300 hover:bg-gray-700'
280 }`}
281 >
282 {p.label}
283 </button>
284 ))}
285 </div>
286 </div>
287​
288 <div className="flex-1 overflow-y-auto p-6">
289 <div className="max-w-2xl mx-auto">
290 <SpeechGenerationForm
291 key={`${mode}-${config.id}`}
292 mode={mode}
293 config={config}
294 />
295 </div>
296 </div>
297 </div>
298 )
300​
301export const Route = createFileRoute('/generations/speech')({
302 component: SpeechGenerationPage,
303})