Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { generateTranscription } from '@tanstack/ai'
3import { openaiTranscription } from '@tanstack/ai-openai'
4
5export const Route = createFileRoute('/api/transcription')({
6 server: {
7 handlers: {
8 POST: async ({ request }) => {
9 const formData = await request.formData()
10 const audioFile = formData.get('audio') as File | null
11 const audioBase64 = formData.get('audioBase64') as string | null
12 const model = (formData.get('model') as string) || 'whisper-1'
13 const language = formData.get('language') as string | null
14 const responseFormat = formData.get('responseFormat') as string | null
15
16 if (!audioFile && !audioBase64) {
17 return new Response(
18 JSON.stringify({
19 error: 'Audio file or base64 data is required',
20 }),
21 {
22 status: 400,
23 headers: { 'Content-Type': 'application/json' },
24 },
25 )
26 }
27
28 try {
29 const adapter = openaiTranscription(model as any)
30
31 // Prepare audio data
32 let audioData: string | File
33 if (audioFile) {
34 audioData = audioFile
35 } else if (audioBase64) {
36 audioData = audioBase64
37 } else {
38 throw new Error('No audio data provided')
39 }
40
41 const result = await generateTranscription({
42 adapter,
43 audio: audioData,
44 language: language || undefined,
45 responseFormat: (responseFormat as any) || 'verbose_json',
46 })
47
48 return new Response(
49 JSON.stringify({
50 id: result.id,
51 model: result.model,
52 text: result.text,
53 language: result.language,
54 duration: result.duration,
55 segments: result.segments,
56 words: result.words,
57 }),
58 {
59 status: 200,
60 headers: { 'Content-Type': 'application/json' },
61 },
62 )
63 } catch (error: any) {
64 return new Response(
65 JSON.stringify({
66 error: error.message || 'An error occurred',
67 }),
68 {
69 status: 500,
70 headers: { 'Content-Type': 'application/json' },
71 },
72 )
73 }
74 },
75 },
76 },
77})