assemblyai 4.35.4 → 4.36.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/README.md +98 -0
- package/dist/assemblyai.streaming.umd.js +28 -11
- package/dist/assemblyai.streaming.umd.min.js +1 -1
- package/dist/assemblyai.umd.js +488 -83
- package/dist/assemblyai.umd.min.js +1 -1
- package/dist/browser.mjs +430 -78
- package/dist/bun.mjs +420 -67
- package/dist/deno.mjs +420 -67
- package/dist/index.cjs +481 -76
- package/dist/index.mjs +479 -77
- package/dist/node.cjs +418 -62
- package/dist/node.mjs +416 -63
- package/dist/services/base.d.ts +1 -0
- package/dist/services/index.d.ts +7 -1
- package/dist/services/streaming/service.d.ts +2 -1
- package/dist/services/sync/index.d.ts +1 -0
- package/dist/services/sync/service.d.ts +48 -0
- package/dist/streaming.browser.mjs +24 -9
- package/dist/streaming.cjs +27 -10
- package/dist/streaming.mjs +27 -10
- package/dist/types/asyncapi.generated.d.ts +1 -1
- package/dist/types/index.d.ts +1 -0
- package/dist/types/services/index.d.ts +1 -0
- package/dist/types/streaming/index.d.ts +14 -4
- package/dist/types/sync/index.d.ts +133 -0
- package/dist/utils/errors/index.d.ts +1 -0
- package/dist/utils/errors/sync.d.ts +20 -0
- package/dist/workerd.mjs +424 -71
- package/package.json +1 -1
- package/src/services/base.ts +18 -8
- package/src/services/index.ts +19 -0
- package/src/services/streaming/service.ts +22 -3
- package/src/services/sync/index.ts +1 -0
- package/src/services/sync/service.ts +369 -0
- package/src/types/asyncapi.generated.ts +6 -1
- package/src/types/index.ts +1 -0
- package/src/types/services/index.ts +1 -0
- package/src/types/streaming/index.ts +16 -3
- package/src/types/sync/index.ts +145 -0
- package/src/utils/errors/index.ts +2 -0
- package/src/utils/errors/sync.ts +25 -0
package/dist/deno.mjs
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import ws from 'ws';
|
|
2
2
|
|
|
3
|
+
/**
|
|
4
|
+
* The default speech model for synchronous transcription.
|
|
5
|
+
*/
|
|
6
|
+
const defaultSyncSpeechModel = "universal-3-5-pro";
|
|
7
|
+
|
|
3
8
|
/**
|
|
4
9
|
* Thrown when `DualChannelCapture` is constructed in a non-browser environment
|
|
5
10
|
* (no `globalThis.AudioContext`). The helper is intentionally surfaced from the
|
|
@@ -13,6 +18,8 @@ class BrowserOnlyError extends Error {
|
|
|
13
18
|
}
|
|
14
19
|
}
|
|
15
20
|
|
|
21
|
+
const readFile = async (path) => (await Deno.open(path)).readable;
|
|
22
|
+
|
|
16
23
|
const DEFAULT_FETCH_INIT = {
|
|
17
24
|
cache: "no-store",
|
|
18
25
|
};
|
|
@@ -30,7 +37,7 @@ if (typeof navigator !== "undefined" && navigator.userAgent) {
|
|
|
30
37
|
defaultUserAgentString += navigator.userAgent;
|
|
31
38
|
}
|
|
32
39
|
const defaultUserAgent = {
|
|
33
|
-
sdk: { name: "JavaScript", version: "4.
|
|
40
|
+
sdk: { name: "JavaScript", version: "4.36.4" },
|
|
34
41
|
};
|
|
35
42
|
if (typeof process !== "undefined") {
|
|
36
43
|
if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
|
|
@@ -69,12 +76,15 @@ class BaseService {
|
|
|
69
76
|
this.userAgent = buildUserAgent(params.userAgent || {});
|
|
70
77
|
}
|
|
71
78
|
}
|
|
72
|
-
async
|
|
79
|
+
async fetchResponse(input, init) {
|
|
73
80
|
init = { ...DEFAULT_FETCH_INIT, ...init };
|
|
74
81
|
let headers = {
|
|
75
82
|
Authorization: this.params.apiKey,
|
|
76
|
-
"Content-Type": "application/json",
|
|
77
83
|
};
|
|
84
|
+
// FormData bodies must let fetch set the multipart boundary itself.
|
|
85
|
+
if (!(init.body instanceof FormData)) {
|
|
86
|
+
headers["Content-Type"] = "application/json";
|
|
87
|
+
}
|
|
78
88
|
if (DEFAULT_FETCH_INIT?.headers)
|
|
79
89
|
headers = { ...headers, ...DEFAULT_FETCH_INIT.headers };
|
|
80
90
|
if (init?.headers)
|
|
@@ -85,7 +95,10 @@ class BaseService {
|
|
|
85
95
|
init.headers = headers;
|
|
86
96
|
if (!input.startsWith("http"))
|
|
87
97
|
input = this.params.baseUrl + input;
|
|
88
|
-
|
|
98
|
+
return await fetch(input, init);
|
|
99
|
+
}
|
|
100
|
+
async fetch(input, init) {
|
|
101
|
+
const response = await this.fetchResponse(input, init);
|
|
89
102
|
if (response.status >= 400) {
|
|
90
103
|
let json;
|
|
91
104
|
const text = await response.text();
|
|
@@ -110,58 +123,342 @@ class BaseService {
|
|
|
110
123
|
}
|
|
111
124
|
}
|
|
112
125
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
126
|
+
/**
|
|
127
|
+
* Error thrown when a synchronous transcription request fails.
|
|
128
|
+
*/
|
|
129
|
+
class SyncTranscriptError extends Error {
|
|
130
|
+
/**
|
|
131
|
+
* Create a new SyncTranscriptError.
|
|
132
|
+
* @param message - The human-readable error message.
|
|
133
|
+
* @param status - The HTTP status code of the failed request.
|
|
134
|
+
* @param errorCode - Machine-readable code — the snake_cased
|
|
135
|
+
* problem-details `title` from the server (e.g. `bad_audio`,
|
|
136
|
+
* `audio_too_large`, `capacity_exceeded`, `inference_timeout`).
|
|
137
|
+
* @param retryAfter - Seconds to wait before retrying, from the
|
|
138
|
+
* `Retry-After` header on 429/503 responses.
|
|
139
|
+
*/
|
|
140
|
+
constructor(message, status, errorCode, retryAfter) {
|
|
141
|
+
super(message);
|
|
142
|
+
this.status = status;
|
|
143
|
+
this.errorCode = errorCode;
|
|
144
|
+
this.retryAfter = retryAfter;
|
|
145
|
+
this.name = "SyncTranscriptError";
|
|
127
146
|
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function getPath(path) {
|
|
150
|
+
if (path.startsWith("http"))
|
|
151
|
+
return null;
|
|
152
|
+
if (path.startsWith("https"))
|
|
153
|
+
return null;
|
|
154
|
+
if (path.startsWith("data:"))
|
|
155
|
+
return null;
|
|
156
|
+
if (path.startsWith("file://"))
|
|
157
|
+
return path.substring(7);
|
|
158
|
+
if (path.startsWith("file:"))
|
|
159
|
+
return path.substring(5);
|
|
160
|
+
return path;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Canonical paths since the sync API gained a /v1 prefix (#18103); the
|
|
164
|
+
// unprefixed routes remain served for SDK versions that predate it.
|
|
165
|
+
const transcribeEndpoint = "/v1/transcribe";
|
|
166
|
+
const warmEndpoint = "/v1/warm";
|
|
167
|
+
const modelHeader = "X-AAI-Model";
|
|
168
|
+
// Kept above the server's 30 s deadline so the client doesn't race it.
|
|
169
|
+
const defaultTimeoutMs = 60_000;
|
|
170
|
+
const warmTimeoutMs = 10_000;
|
|
171
|
+
const maxPromptLength = 4096;
|
|
172
|
+
const maxKeytermsPromptLength = 2048;
|
|
173
|
+
const maxContextTurns = 100;
|
|
174
|
+
const maxContextLength = 4096;
|
|
175
|
+
// Extensions that signal raw S16LE PCM rather than a WAV container.
|
|
176
|
+
const pcmSuffixes = [".pcm", ".raw"];
|
|
177
|
+
/**
|
|
178
|
+
* The synchronous transcription service: audio in, transcript out,
|
|
179
|
+
* one request.
|
|
180
|
+
*
|
|
181
|
+
* Unlike `client.transcripts` (which submits a job to the async API and
|
|
182
|
+
* polls for completion), `SyncTranscriber` posts the audio to the sync
|
|
183
|
+
* API and returns the finished transcript in the HTTP response. There is no
|
|
184
|
+
* job id or status to poll. Accepts a local file path, raw audio bytes, a
|
|
185
|
+
* Blob, or a readable stream — but not a URL.
|
|
186
|
+
*/
|
|
187
|
+
class SyncTranscriber extends BaseService {
|
|
188
|
+
/**
|
|
189
|
+
* Create a new synchronous transcription service.
|
|
190
|
+
* @param params - The parameters to use for the service.
|
|
191
|
+
*/
|
|
192
|
+
constructor(params) {
|
|
193
|
+
super(params);
|
|
134
194
|
}
|
|
135
|
-
|
|
136
|
-
|
|
195
|
+
/**
|
|
196
|
+
* Transcribe audio and return the finished transcript in one request.
|
|
197
|
+
* @param audio - A local file path, raw audio bytes, a Blob, or a readable
|
|
198
|
+
* stream. Raw PCM also requires `sample_rate` and `channels` on the config.
|
|
199
|
+
* @param config - Options for this transcription request.
|
|
200
|
+
* @param options - Client-side options, such as the request timeout.
|
|
201
|
+
* @returns A promise that resolves to the finished transcript.
|
|
202
|
+
* @throws SyncTranscriptError when the request fails.
|
|
203
|
+
*/
|
|
204
|
+
async transcribe(audio, config = {}, options = {}) {
|
|
205
|
+
const { bytes, filename, contentType } = await resolveAudio(audio, config);
|
|
206
|
+
const body = new FormData();
|
|
207
|
+
body.append("audio", new Blob([bytes], { type: contentType }), filename);
|
|
208
|
+
const configJson = buildConfigJson(config);
|
|
209
|
+
if (configJson) {
|
|
210
|
+
body.append("config", new Blob([JSON.stringify(configJson)], { type: "application/json" }));
|
|
211
|
+
}
|
|
212
|
+
const response = await this.fetchResponse(transcribeEndpoint, {
|
|
137
213
|
method: "POST",
|
|
138
|
-
body
|
|
139
|
-
|
|
214
|
+
body,
|
|
215
|
+
headers: { [modelHeader]: config.model ?? defaultSyncSpeechModel },
|
|
216
|
+
signal: AbortSignal.timeout(options.timeout ?? defaultTimeoutMs),
|
|
140
217
|
});
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
return
|
|
218
|
+
if (response.status !== 200)
|
|
219
|
+
throw await errorFromResponse(response);
|
|
220
|
+
return (await response.json());
|
|
144
221
|
}
|
|
145
222
|
/**
|
|
146
|
-
*
|
|
147
|
-
*
|
|
148
|
-
*
|
|
223
|
+
* Open the connection to the sync API ahead of time.
|
|
224
|
+
*
|
|
225
|
+
* The sync API is a single request/response, so a `transcribe()` that
|
|
226
|
+
* opens its connection on demand pays the full DNS + TCP + TLS handshake
|
|
227
|
+
* on the critical path. Call `warm()` as soon as you know audio is coming —
|
|
228
|
+
* typically while the clip is still being recorded — so the next
|
|
229
|
+
* `transcribe()` reuses the already-open connection. `warm()` is idempotent
|
|
230
|
+
* and cheap; call it shortly before `transcribe()` so the pooled connection
|
|
231
|
+
* hasn't idled out.
|
|
232
|
+
* @param params - Optionally the model to route the probe to, so the warmed
|
|
233
|
+
* connection lands on the same backend as the eventual transcription.
|
|
234
|
+
* @returns A promise that resolves to `true` once the connection is open
|
|
235
|
+
* (any HTTP response — even a non-200 — means the socket is
|
|
236
|
+
* established), or `false` if the connection could not be opened.
|
|
149
237
|
*/
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
238
|
+
async warm(params) {
|
|
239
|
+
try {
|
|
240
|
+
await this.fetchResponse(warmEndpoint, {
|
|
241
|
+
method: "GET",
|
|
242
|
+
headers: { [modelHeader]: params?.model ?? defaultSyncSpeechModel },
|
|
243
|
+
signal: AbortSignal.timeout(warmTimeoutMs),
|
|
244
|
+
});
|
|
245
|
+
return true;
|
|
246
|
+
}
|
|
247
|
+
catch {
|
|
248
|
+
return false;
|
|
249
|
+
}
|
|
155
250
|
}
|
|
156
251
|
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
252
|
+
/**
|
|
253
|
+
* Read the audio input into bytes and decide its multipart content type.
|
|
254
|
+
*
|
|
255
|
+
* PCM is selected when the source has a `.pcm`/`.raw` extension or when
|
|
256
|
+
* `sample_rate`/`channels` are set on the config (the fields the sync API
|
|
257
|
+
* requires only for raw PCM) — and both must then be present. Everything
|
|
258
|
+
* else is treated as a WAV container. URLs are rejected — the sync API has
|
|
259
|
+
* no URL ingestion.
|
|
260
|
+
*/
|
|
261
|
+
async function resolveAudio(input, config) {
|
|
262
|
+
let bytes;
|
|
263
|
+
let filename;
|
|
264
|
+
let suffix = "";
|
|
265
|
+
if (typeof input === "string") {
|
|
266
|
+
if (/^https?:\/\//i.test(input)) {
|
|
267
|
+
throw new Error("SyncTranscriber does not accept URLs. Pass a local file path or " +
|
|
268
|
+
"audio bytes, or use client.transcripts for URL/async transcription.");
|
|
269
|
+
}
|
|
270
|
+
if (input.startsWith("data:")) {
|
|
271
|
+
bytes = dataUrlToBytes(input);
|
|
272
|
+
}
|
|
273
|
+
else {
|
|
274
|
+
const path = getPath(input) ?? input;
|
|
275
|
+
bytes = await readStream(await readFile(path));
|
|
276
|
+
filename = basename(path);
|
|
277
|
+
suffix = extname(filename);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
else if (input instanceof Uint8Array) {
|
|
281
|
+
bytes = input;
|
|
282
|
+
}
|
|
283
|
+
else if (input instanceof ArrayBuffer) {
|
|
284
|
+
bytes = new Uint8Array(input);
|
|
285
|
+
}
|
|
286
|
+
else if (input instanceof Blob) {
|
|
287
|
+
bytes = new Uint8Array(await input.arrayBuffer());
|
|
288
|
+
// File instances carry a name; the File global itself needs Node >= 20.
|
|
289
|
+
const name = input.name;
|
|
290
|
+
if (name) {
|
|
291
|
+
filename = basename(name);
|
|
292
|
+
suffix = extname(filename);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
else if (isWebReadableStream(input)) {
|
|
296
|
+
bytes = await readStream(input);
|
|
297
|
+
}
|
|
298
|
+
else if (isAsyncIterable(input)) {
|
|
299
|
+
bytes = await readAsyncIterable(input);
|
|
300
|
+
// fs.ReadStream carries the path it was opened from.
|
|
301
|
+
const path = input.path;
|
|
302
|
+
if (typeof path === "string") {
|
|
303
|
+
filename = basename(path);
|
|
304
|
+
suffix = extname(filename);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
else {
|
|
308
|
+
throw new TypeError("unsupported audio input type");
|
|
309
|
+
}
|
|
310
|
+
const wantsPcm = config.sample_rate !== undefined || config.channels !== undefined;
|
|
311
|
+
const isPcm = pcmSuffixes.includes(suffix) || wantsPcm;
|
|
312
|
+
if (isPcm &&
|
|
313
|
+
(config.sample_rate === undefined || config.channels === undefined)) {
|
|
314
|
+
throw new Error("raw PCM audio requires both sample_rate and channels in the config");
|
|
315
|
+
}
|
|
316
|
+
const contentType = isPcm ? "audio/pcm" : "audio/wav";
|
|
317
|
+
if (!filename)
|
|
318
|
+
filename = isPcm ? "audio.pcm" : "audio.wav";
|
|
319
|
+
return { bytes, filename, contentType };
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Serialize the config to the JSON `config` part, validating and normalizing
|
|
323
|
+
* field values to match the server's caps. The routing `model` is never
|
|
324
|
+
* included — it travels in the `X-AAI-Model` header. Returns `undefined`
|
|
325
|
+
* when there is nothing to send, so the part can be omitted entirely.
|
|
326
|
+
*/
|
|
327
|
+
function buildConfigJson(config) {
|
|
328
|
+
if (config.prompt !== undefined && config.prompt.length > maxPromptLength) {
|
|
329
|
+
throw new Error(`prompt exceeds ${maxPromptLength} characters (got ${config.prompt.length})`);
|
|
330
|
+
}
|
|
331
|
+
const json = {};
|
|
332
|
+
if (config.prompt !== undefined)
|
|
333
|
+
json["prompt"] = config.prompt;
|
|
334
|
+
const keytermsPrompt = normalizeKeytermsPrompt(config.keyterms_prompt);
|
|
335
|
+
if (keytermsPrompt)
|
|
336
|
+
json["keyterms_prompt"] = keytermsPrompt;
|
|
337
|
+
const context = normalizeConversationContext(config.conversation_context);
|
|
338
|
+
if (context)
|
|
339
|
+
json["conversation_context"] = context;
|
|
340
|
+
if (config.language_codes !== undefined)
|
|
341
|
+
json["language_codes"] = config.language_codes;
|
|
342
|
+
if (config.sample_rate !== undefined)
|
|
343
|
+
json["sample_rate"] = config.sample_rate;
|
|
344
|
+
if (config.channels !== undefined)
|
|
345
|
+
json["channels"] = config.channels;
|
|
346
|
+
if (config.timestamps !== undefined)
|
|
347
|
+
json["timestamps"] = config.timestamps;
|
|
348
|
+
return Object.keys(json).length > 0 ? json : undefined;
|
|
349
|
+
}
|
|
350
|
+
function normalizeKeytermsPrompt(keytermsPrompt) {
|
|
351
|
+
if (!keytermsPrompt)
|
|
352
|
+
return undefined;
|
|
353
|
+
const terms = keytermsPrompt
|
|
354
|
+
.map((term) => term.trim())
|
|
355
|
+
.filter((term) => term.length > 0);
|
|
356
|
+
const total = terms.reduce((sum, term) => sum + term.length, 0);
|
|
357
|
+
if (total > maxKeytermsPromptLength) {
|
|
358
|
+
throw new Error(`keyterms_prompt exceeds ${maxKeytermsPromptLength} characters (got ${total})`);
|
|
359
|
+
}
|
|
360
|
+
return terms.length > 0 ? terms : undefined;
|
|
361
|
+
}
|
|
362
|
+
function normalizeConversationContext(context) {
|
|
363
|
+
if (context === undefined)
|
|
364
|
+
return undefined;
|
|
365
|
+
let turns = (typeof context === "string" ? [context] : context)
|
|
366
|
+
.map((turn) => turn.trim())
|
|
367
|
+
.filter((turn) => turn.length > 0);
|
|
368
|
+
let total = turns.reduce((sum, turn) => sum + turn.length, 0);
|
|
369
|
+
// Over-cap context is trimmed oldest-first, never rejected.
|
|
370
|
+
while (turns.length > 0 &&
|
|
371
|
+
(turns.length > maxContextTurns || total > maxContextLength)) {
|
|
372
|
+
total -= turns[0].length;
|
|
373
|
+
turns = turns.slice(1);
|
|
374
|
+
}
|
|
375
|
+
return turns.length > 0 ? turns : undefined;
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Build a SyncTranscriptError from a non-200 response. The primary format
|
|
379
|
+
* is an RFC 9457 problem-details body (`status`/`title`/`detail`); legacy
|
|
380
|
+
* `{error_code, message}` and `{detail}`-only bodies are also accepted.
|
|
381
|
+
*/
|
|
382
|
+
async function errorFromResponse(response) {
|
|
383
|
+
let errorCode;
|
|
384
|
+
let message;
|
|
385
|
+
const text = await response.text();
|
|
386
|
+
try {
|
|
387
|
+
const body = JSON.parse(text);
|
|
388
|
+
if (body && typeof body === "object" && !Array.isArray(body)) {
|
|
389
|
+
if (typeof body.error_code === "string")
|
|
390
|
+
errorCode = body.error_code;
|
|
391
|
+
if (errorCode === undefined && typeof body.title === "string") {
|
|
392
|
+
errorCode = body.title.toLowerCase().replace(/ /g, "_");
|
|
393
|
+
}
|
|
394
|
+
if (typeof body.detail === "string")
|
|
395
|
+
message = body.detail;
|
|
396
|
+
else if (typeof body.message === "string")
|
|
397
|
+
message = body.message;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
catch {
|
|
401
|
+
if (text)
|
|
402
|
+
message = text;
|
|
403
|
+
}
|
|
404
|
+
if (!message) {
|
|
405
|
+
message = `sync transcription failed with status ${response.status}`;
|
|
406
|
+
}
|
|
407
|
+
const retryHeader = response.headers.get("retry-after");
|
|
408
|
+
const retryAfter = retryHeader && /^\d+$/.test(retryHeader)
|
|
409
|
+
? parseInt(retryHeader, 10)
|
|
410
|
+
: undefined;
|
|
411
|
+
return new SyncTranscriptError(message, response.status, errorCode, retryAfter);
|
|
412
|
+
}
|
|
413
|
+
function basename(path) {
|
|
414
|
+
return path.split(/[\\/]/).pop() ?? path;
|
|
415
|
+
}
|
|
416
|
+
function extname(filename) {
|
|
417
|
+
const dotIndex = filename.lastIndexOf(".");
|
|
418
|
+
return dotIndex > 0 ? filename.slice(dotIndex).toLowerCase() : "";
|
|
419
|
+
}
|
|
420
|
+
function dataUrlToBytes(dataUrl) {
|
|
421
|
+
const base64 = dataUrl.split(",")[1];
|
|
422
|
+
const binary = atob(base64);
|
|
423
|
+
const bytes = new Uint8Array(binary.length);
|
|
424
|
+
for (let i = 0; i < binary.length; i++)
|
|
425
|
+
bytes[i] = binary.charCodeAt(i);
|
|
426
|
+
return bytes;
|
|
427
|
+
}
|
|
428
|
+
function isWebReadableStream(input) {
|
|
429
|
+
return typeof input?.getReader === "function";
|
|
430
|
+
}
|
|
431
|
+
function isAsyncIterable(input) {
|
|
432
|
+
return (typeof input?.[Symbol.asyncIterator] ===
|
|
433
|
+
"function");
|
|
434
|
+
}
|
|
435
|
+
async function readStream(stream) {
|
|
436
|
+
const chunks = [];
|
|
437
|
+
const reader = stream.getReader();
|
|
438
|
+
for (;;) {
|
|
439
|
+
const { done, value } = await reader.read();
|
|
440
|
+
if (done)
|
|
441
|
+
break;
|
|
442
|
+
chunks.push(value);
|
|
443
|
+
}
|
|
444
|
+
return concatChunks(chunks);
|
|
445
|
+
}
|
|
446
|
+
async function readAsyncIterable(iterable) {
|
|
447
|
+
const chunks = [];
|
|
448
|
+
for await (const chunk of iterable)
|
|
449
|
+
chunks.push(chunk);
|
|
450
|
+
return concatChunks(chunks);
|
|
451
|
+
}
|
|
452
|
+
function concatChunks(chunks) {
|
|
453
|
+
const total = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
|
|
454
|
+
const bytes = new Uint8Array(total);
|
|
455
|
+
let offset = 0;
|
|
456
|
+
for (const chunk of chunks) {
|
|
457
|
+
bytes.set(chunk, offset);
|
|
458
|
+
offset += chunk.length;
|
|
459
|
+
}
|
|
460
|
+
return bytes;
|
|
461
|
+
}
|
|
165
462
|
|
|
166
463
|
const RealtimeErrorType = {
|
|
167
464
|
BadSampleRate: 4000,
|
|
@@ -267,6 +564,59 @@ const StreamingErrorMessages = {
|
|
|
267
564
|
class StreamingError extends Error {
|
|
268
565
|
}
|
|
269
566
|
|
|
567
|
+
class LemurService extends BaseService {
|
|
568
|
+
summary(params, signal) {
|
|
569
|
+
return this.fetchJson("/lemur/v3/generate/summary", {
|
|
570
|
+
method: "POST",
|
|
571
|
+
body: JSON.stringify(params),
|
|
572
|
+
signal,
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
questionAnswer(params, signal) {
|
|
576
|
+
return this.fetchJson("/lemur/v3/generate/question-answer", {
|
|
577
|
+
method: "POST",
|
|
578
|
+
body: JSON.stringify(params),
|
|
579
|
+
signal,
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
actionItems(params, signal) {
|
|
583
|
+
return this.fetchJson("/lemur/v3/generate/action-items", {
|
|
584
|
+
method: "POST",
|
|
585
|
+
body: JSON.stringify(params),
|
|
586
|
+
signal,
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
task(params, signal) {
|
|
590
|
+
return this.fetchJson("/lemur/v3/generate/task", {
|
|
591
|
+
method: "POST",
|
|
592
|
+
body: JSON.stringify(params),
|
|
593
|
+
signal,
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
getResponse(id, signal) {
|
|
597
|
+
return this.fetchJson(`/lemur/v3/${id}`, { signal });
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* Delete the data for a previously submitted LeMUR request.
|
|
601
|
+
* @param id - ID of the LeMUR request
|
|
602
|
+
* @param signal - Optional AbortSignal to cancel the request
|
|
603
|
+
*/
|
|
604
|
+
purgeRequestData(id, signal) {
|
|
605
|
+
return this.fetchJson(`/lemur/v3/${id}`, {
|
|
606
|
+
method: "DELETE",
|
|
607
|
+
signal,
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
const { WritableStream } = typeof window !== "undefined"
|
|
613
|
+
? window
|
|
614
|
+
: typeof global !== "undefined"
|
|
615
|
+
? global
|
|
616
|
+
: globalThis;
|
|
617
|
+
|
|
618
|
+
const factory = (url, params) => new ws(url, params);
|
|
619
|
+
|
|
270
620
|
const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
|
|
271
621
|
const forceEndOfUtteranceMessage = `{"force_end_utterance":true}`;
|
|
272
622
|
const terminateSessionMessage$1 = `{"terminate_session":true}`;
|
|
@@ -511,20 +861,6 @@ class RealtimeTranscriberFactory extends BaseService {
|
|
|
511
861
|
class RealtimeServiceFactory extends RealtimeTranscriberFactory {
|
|
512
862
|
}
|
|
513
863
|
|
|
514
|
-
function getPath(path) {
|
|
515
|
-
if (path.startsWith("http"))
|
|
516
|
-
return null;
|
|
517
|
-
if (path.startsWith("https"))
|
|
518
|
-
return null;
|
|
519
|
-
if (path.startsWith("data:"))
|
|
520
|
-
return null;
|
|
521
|
-
if (path.startsWith("file://"))
|
|
522
|
-
return path.substring(7);
|
|
523
|
-
if (path.startsWith("file:"))
|
|
524
|
-
return path.substring(5);
|
|
525
|
-
return path;
|
|
526
|
-
}
|
|
527
|
-
|
|
528
864
|
class TranscriptService extends BaseService {
|
|
529
865
|
constructor(params, files) {
|
|
530
866
|
super(params);
|
|
@@ -752,8 +1088,6 @@ class TranscriptService extends BaseService {
|
|
|
752
1088
|
}
|
|
753
1089
|
}
|
|
754
1090
|
|
|
755
|
-
const readFile = async (path) => (await Deno.open(path)).readable;
|
|
756
|
-
|
|
757
1091
|
class FileService extends BaseService {
|
|
758
1092
|
/**
|
|
759
1093
|
* Upload a local file to AssemblyAI.
|
|
@@ -1034,9 +1368,12 @@ class StreamingTranscriber {
|
|
|
1034
1368
|
if (!(this.token || this.apiKey)) {
|
|
1035
1369
|
throw new Error("API key or temporary token is required.");
|
|
1036
1370
|
}
|
|
1037
|
-
const
|
|
1038
|
-
|
|
1039
|
-
|
|
1371
|
+
const isSelfDescribing = params.encoding === "opus" ||
|
|
1372
|
+
params.encoding === "ogg_opus" ||
|
|
1373
|
+
params.encoding === "aac";
|
|
1374
|
+
if (params.sampleRate === undefined &&
|
|
1375
|
+
(!isSelfDescribing || params.channels)) {
|
|
1376
|
+
throw new Error('`sampleRate` is required; it may only be omitted when `encoding` is "opus", "ogg_opus", or "aac" (these streams are self-describing) and dual-channel mode is not used.');
|
|
1040
1377
|
}
|
|
1041
1378
|
if (params.channels) {
|
|
1042
1379
|
if (params.channels.length !== 2) {
|
|
@@ -1114,6 +1451,9 @@ class StreamingTranscriber {
|
|
|
1114
1451
|
if (this.params.formatTurns) {
|
|
1115
1452
|
searchParams.set("format_turns", this.params.formatTurns.toString());
|
|
1116
1453
|
}
|
|
1454
|
+
if (this.params.sessionHeartbeat !== undefined) {
|
|
1455
|
+
searchParams.set("session_heartbeat", this.params.sessionHeartbeat.toString());
|
|
1456
|
+
}
|
|
1117
1457
|
if (this.params.encoding) {
|
|
1118
1458
|
searchParams.set("encoding", this.params.encoding.toString());
|
|
1119
1459
|
}
|
|
@@ -1398,6 +1738,10 @@ class StreamingTranscriber {
|
|
|
1398
1738
|
this.listeners.warning?.(warning);
|
|
1399
1739
|
break;
|
|
1400
1740
|
}
|
|
1741
|
+
case "Heartbeat": {
|
|
1742
|
+
this.listeners.heartbeat?.(message);
|
|
1743
|
+
break;
|
|
1744
|
+
}
|
|
1401
1745
|
case "Termination": {
|
|
1402
1746
|
this.sessionTerminatedResolve?.();
|
|
1403
1747
|
break;
|
|
@@ -2015,6 +2359,7 @@ function float32ToPcm16(input) {
|
|
|
2015
2359
|
|
|
2016
2360
|
const defaultBaseUrl = "https://api.assemblyai.com";
|
|
2017
2361
|
const defaultStreamingUrl = "https://streaming.assemblyai.com";
|
|
2362
|
+
const defaultSyncUrl = "https://sync.assemblyai.com";
|
|
2018
2363
|
class AssemblyAI {
|
|
2019
2364
|
/**
|
|
2020
2365
|
* Create a new AssemblyAI client.
|
|
@@ -2033,7 +2378,15 @@ class AssemblyAI {
|
|
|
2033
2378
|
...params,
|
|
2034
2379
|
baseUrl: params.streamingBaseUrl || defaultStreamingUrl,
|
|
2035
2380
|
});
|
|
2381
|
+
let syncBaseUrl = params.syncBaseUrl || defaultSyncUrl;
|
|
2382
|
+
if (syncBaseUrl.endsWith("/")) {
|
|
2383
|
+
syncBaseUrl = syncBaseUrl.slice(0, -1);
|
|
2384
|
+
}
|
|
2385
|
+
this.sync = new SyncTranscriber({
|
|
2386
|
+
...params,
|
|
2387
|
+
baseUrl: syncBaseUrl,
|
|
2388
|
+
});
|
|
2036
2389
|
}
|
|
2037
2390
|
}
|
|
2038
2391
|
|
|
2039
|
-
export { AssemblyAI, BrowserOnlyError, DualChannelCapture, EnergyVad, FileService, LemurService, LinearResampler, RealtimeService, RealtimeServiceFactory, RealtimeTranscriber, RealtimeTranscriberFactory, StreamingTranscriber, TranscriptService, VadTimeline, attributeTurn, attributeWord, float32ToPcm16, rollUpTurnChannel };
|
|
2392
|
+
export { AssemblyAI, BrowserOnlyError, DualChannelCapture, EnergyVad, FileService, LemurService, LinearResampler, RealtimeService, RealtimeServiceFactory, RealtimeTranscriber, RealtimeTranscriberFactory, StreamingTranscriber, SyncTranscriber, SyncTranscriptError, TranscriptService, VadTimeline, attributeTurn, attributeWord, defaultSyncSpeechModel, float32ToPcm16, rollUpTurnChannel };
|