|
| 1 | +import { error, json, text } from '@sveltejs/kit'; |
| 2 | +import OpenAI from 'openai'; |
| 3 | +import type { RequestHandler } from './$types'; |
| 4 | +import { env as envPrivate } from '$env/dynamic/private'; |
| 5 | + |
| 6 | +const openai = envPrivate.OPENAI_API_KEY |
| 7 | + ? new OpenAI({ |
| 8 | + apiKey: envPrivate.OPENAI_API_KEY |
| 9 | + }) |
| 10 | + : undefined; |
| 11 | + |
| 12 | +export const POST: RequestHandler = async ({ request }) => { |
| 13 | + if (!openai) { |
| 14 | + return error(500, 'OpenAI API key not provided'); |
| 15 | + } |
| 16 | + |
| 17 | + try { |
| 18 | + const data = await request.formData(); |
| 19 | + const audioFile = data.get('audio') as File; |
| 20 | + |
| 21 | + if (!audioFile) { |
| 22 | + return json({ error: 'No audio file provided' }, { status: 400 }); |
| 23 | + } |
| 24 | + |
| 25 | + console.log('Audio file details:', audioFile.type, audioFile.size, audioFile.name); |
| 26 | + |
| 27 | + const controller = new AbortController(); |
| 28 | + const timeoutId = setTimeout(() => controller.abort(), 60000); |
| 29 | + |
| 30 | + const transcription = await openai.audio.transcriptions.create({ |
| 31 | + file: audioFile, |
| 32 | + model: 'whisper-1' |
| 33 | + // response_format: 'text' |
| 34 | + }); |
| 35 | + |
| 36 | + clearTimeout(timeoutId); |
| 37 | + |
| 38 | + return json(transcription); |
| 39 | + } catch (err: any) { |
| 40 | + if (err.name === 'AbortError') { |
| 41 | + console.error('Request timed out:', err); |
| 42 | + return error(408, 'Request timed out'); |
| 43 | + } |
| 44 | + |
| 45 | + console.error('Error during transcription:', err); |
| 46 | + return error(500, err.message); |
| 47 | + } |
| 48 | +}; |
0 commit comments