|
| 1 | +import { AssemblyAI } from "assemblyai"; |
| 2 | +import { getRequiredEnv } from "@/lib/env"; |
| 3 | +import { NextResponse, type NextRequest } from "next/server"; |
| 4 | + |
| 5 | +export const revalidate = 0; |
| 6 | + |
| 7 | +export async function POST(request: NextRequest) { |
| 8 | + try { |
| 9 | + const apiKey = getRequiredEnv("ASSEMBLYAI_API_KEY"); |
| 10 | + if (!apiKey) { |
| 11 | + return NextResponse.json( |
| 12 | + { error: "AssemblyAI API Key not found" }, |
| 13 | + { status: 500 } |
| 14 | + ); |
| 15 | + } |
| 16 | + |
| 17 | + const assemblyClient = new AssemblyAI({ apiKey }); |
| 18 | + const formData = await request.formData(); |
| 19 | + const audioFile = formData.get("audio") as File; |
| 20 | + |
| 21 | + if (!audioFile) { |
| 22 | + return NextResponse.json( |
| 23 | + { error: "No audio file provided" }, |
| 24 | + { status: 400 } |
| 25 | + ); |
| 26 | + } |
| 27 | + |
| 28 | + // Convert File to Buffer |
| 29 | + const arrayBuffer = await audioFile.arrayBuffer(); |
| 30 | + const buffer = Buffer.from(arrayBuffer); |
| 31 | + |
| 32 | + // Upload the audio file |
| 33 | + const uploadUrl = await assemblyClient.files.upload(buffer); |
| 34 | + |
| 35 | + // Create a transcript |
| 36 | + const transcript = await assemblyClient.transcripts.create({ |
| 37 | + audio_url: uploadUrl, |
| 38 | + language_detection: true, |
| 39 | + }); |
| 40 | + |
| 41 | + // Poll until the transcript is ready |
| 42 | + let result; |
| 43 | + while (true) { |
| 44 | + result = await assemblyClient.transcripts.get(transcript.id); |
| 45 | + if (result.status === "completed" || result.status === "error") break; |
| 46 | + await new Promise((resolve) => setTimeout(resolve, 1000)); |
| 47 | + } |
| 48 | + |
| 49 | + if (result.status === "error") { |
| 50 | + throw new Error(result.error); |
| 51 | + } |
| 52 | + |
| 53 | + const response = NextResponse.json({ |
| 54 | + text: result.text, |
| 55 | + language: result.language_code, |
| 56 | + confidence: result.confidence, |
| 57 | + words: result.words, |
| 58 | + }); |
| 59 | + |
| 60 | + response.headers.set("Surrogate-Control", "no-store"); |
| 61 | + response.headers.set( |
| 62 | + "Cache-Control", |
| 63 | + "s-maxage=0, no-store, no-cache, must-revalidate, proxy-revalidate" |
| 64 | + ); |
| 65 | + response.headers.set("Expires", "0"); |
| 66 | + |
| 67 | + return response; |
| 68 | + } catch (error) { |
| 69 | + console.error("Error transcribing audio:", error); |
| 70 | + return NextResponse.json({ error: String(error) }, { status: 500 }); |
| 71 | + } |
| 72 | +} |
0 commit comments