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

api.transcription.ts

78 lines2.4 KB

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 threadId: 'panel-transcription',
43 adapter,
44 audio: audioData,
45 language: language || undefined,
46 responseFormat: (responseFormat as any) || 'verbose_json',
47 })
48​
49 return new Response(
50 JSON.stringify({
51 id: result.id,
52 model: result.model,
53 text: result.text,
54 language: result.language,
55 duration: result.duration,
56 segments: result.segments,
57 words: result.words,
58 }),
59 {
60 status: 200,
61 headers: { 'Content-Type': 'application/json' },
62 },
63 )
64 } catch (error: any) {
65 return new Response(
66 JSON.stringify({
67 error: error.message || 'An error occurred',
68 }),
69 {
70 status: 500,
71 headers: { 'Content-Type': 'application/json' },
72 },
73 )
74 }
75 },
76 },
77 },
78})