-
Notifications
You must be signed in to change notification settings - Fork 546
Expand file tree
/
Copy pathbatch.ts
More file actions
192 lines (166 loc) · 4.55 KB
/
batch.ts
File metadata and controls
192 lines (166 loc) · 4.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import { env } from "../../env";
import type {
BatchAlternatives,
BatchChannel,
BatchParams,
BatchResponse,
BatchResults,
BatchWord,
} from "../batch-types";
const ASSEMBLYAI_API_URL = "https://api.assemblyai.com/v2";
const POLL_INTERVAL_MS = 3000;
const MAX_POLL_ATTEMPTS = 200;
type AssemblyAIWord = {
text: string;
start: number;
end: number;
confidence: number;
speaker?: string;
};
type AssemblyAITranscriptResponse = {
id: string;
status: string;
text?: string;
words?: AssemblyAIWord[];
confidence?: number;
audio_duration?: number;
error?: string;
};
const uploadAudio = async (audioData: ArrayBuffer): Promise<string> => {
const response = await fetch(`${ASSEMBLYAI_API_URL}/upload`, {
method: "POST",
headers: {
Authorization: env.ASSEMBLYAI_API_KEY,
"Content-Type": "application/octet-stream",
},
body: audioData,
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(
`AssemblyAI upload failed: ${response.status} - ${errorText}`,
);
}
const result = (await response.json()) as { upload_url: string };
return result.upload_url;
};
const createTranscript = async (
audioUrl: string,
params: BatchParams,
): Promise<string> => {
const languageCode =
params.languages && params.languages.length === 1
? params.languages[0]
: undefined;
const languageDetection =
!params.languages ||
params.languages.length === 0 ||
params.languages.length > 1;
const requestBody: Record<string, unknown> = {
audio_url: audioUrl,
speaker_labels: true,
};
if (languageCode) {
requestBody.language_code = languageCode;
}
if (languageDetection) {
requestBody.language_detection = true;
}
if (params.keywords && params.keywords.length > 0) {
requestBody.keyterms_prompt = params.keywords;
}
if (params.model) {
requestBody.speech_model = params.model;
}
const response = await fetch(`${ASSEMBLYAI_API_URL}/transcript`, {
method: "POST",
headers: {
Authorization: env.ASSEMBLYAI_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(
`AssemblyAI transcript creation failed: ${response.status} - ${errorText}`,
);
}
const result = (await response.json()) as { id: string };
return result.id;
};
const pollTranscript = async (
transcriptId: string,
): Promise<AssemblyAITranscriptResponse> => {
for (let attempt = 0; attempt < MAX_POLL_ATTEMPTS; attempt++) {
const response = await fetch(
`${ASSEMBLYAI_API_URL}/transcript/${transcriptId}`,
{
headers: {
Authorization: env.ASSEMBLYAI_API_KEY,
},
},
);
if (!response.ok) {
const errorText = await response.text();
throw new Error(
`AssemblyAI poll failed: ${response.status} - ${errorText}`,
);
}
const result = (await response.json()) as AssemblyAITranscriptResponse;
if (result.status === "completed") {
return result;
}
if (result.status === "error") {
throw new Error(
`AssemblyAI transcription failed: ${result.error ?? "unknown error"}`,
);
}
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
}
throw new Error("AssemblyAI transcription timed out");
};
const convertToResponse = (
result: AssemblyAITranscriptResponse,
): BatchResponse => {
const words: BatchWord[] = (result.words ?? []).map((w) => {
const speaker = w.speaker
? parseInt(w.speaker.replace(/\D/g, ""), 10)
: undefined;
return {
word: w.text,
start: w.start / 1000,
end: w.end / 1000,
confidence: w.confidence,
speaker: Number.isNaN(speaker) ? undefined : speaker,
punctuated_word: w.text,
};
});
const alternatives: BatchAlternatives = {
transcript: result.text ?? "",
confidence: result.confidence ?? 1.0,
words,
};
const channel: BatchChannel = {
alternatives: [alternatives],
};
const results: BatchResults = {
channels: [channel],
};
return {
metadata: {
audio_duration: result.audio_duration,
},
results,
};
};
export const transcribeWithAssemblyAI = async (
audioData: ArrayBuffer,
_contentType: string,
params: BatchParams,
): Promise<BatchResponse> => {
const uploadUrl = await uploadAudio(audioData);
const transcriptId = await createTranscript(uploadUrl, params);
const result = await pollTranscript(transcriptId);
return convertToResponse(result);
};