assemblyai 4.0.0-beta.1 → 4.0.0-beta.2

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.
@@ -3,50 +3,7 @@
3
3
  var isomorphicStreams = require('@swimburger/isomorphic-streams');
4
4
  var WebSocket = require('isomorphic-ws');
5
5
  var fs = require('fs');
6
-
7
- /******************************************************************************
8
- Copyright (c) Microsoft Corporation.
9
-
10
- Permission to use, copy, modify, and/or distribute this software for any
11
- purpose with or without fee is hereby granted.
12
-
13
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
14
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
16
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
17
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
18
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
19
- PERFORMANCE OF THIS SOFTWARE.
20
- ***************************************************************************** */
21
- /* global Reflect, Promise, SuppressedError, Symbol */
22
-
23
-
24
- function __rest(s, e) {
25
- var t = {};
26
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
27
- t[p] = s[p];
28
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
29
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
30
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
31
- t[p[i]] = s[p[i]];
32
- }
33
- return t;
34
- }
35
-
36
- function __awaiter(thisArg, _arguments, P, generator) {
37
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
38
- return new (P || (P = Promise))(function (resolve, reject) {
39
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
40
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
41
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
42
- step((generator = generator.apply(thisArg, _arguments || [])).next());
43
- });
44
- }
45
-
46
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
47
- var e = new Error(message);
48
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
49
- };
6
+ var stream = require('stream');
50
7
 
51
8
  /**
52
9
  * Base class for services that communicate with the API.
@@ -59,39 +16,38 @@ class BaseService {
59
16
  constructor(params) {
60
17
  this.params = params;
61
18
  }
62
- fetch(input, init) {
63
- var _a;
64
- return __awaiter(this, void 0, void 0, function* () {
65
- init = init !== null && init !== void 0 ? init : {};
66
- init.headers = (_a = init.headers) !== null && _a !== void 0 ? _a : {};
67
- init.headers = Object.assign({ Authorization: this.params.apiKey, "Content-Type": "application/json" }, init.headers);
68
- if (!input.startsWith("http"))
69
- input = this.params.baseUrl + input;
70
- const response = yield fetch(input, init);
71
- if (response.status >= 400) {
72
- let json;
73
- const text = yield response.text();
74
- if (text) {
75
- try {
76
- json = JSON.parse(text);
77
- }
78
- catch (_b) {
79
- /* empty */
80
- }
81
- if (json === null || json === void 0 ? void 0 : json.error)
82
- throw new Error(json.error);
83
- throw new Error(text);
19
+ async fetch(input, init) {
20
+ init = init ?? {};
21
+ init.headers = init.headers ?? {};
22
+ init.headers = {
23
+ Authorization: this.params.apiKey,
24
+ "Content-Type": "application/json",
25
+ ...init.headers,
26
+ };
27
+ if (!input.startsWith("http"))
28
+ input = this.params.baseUrl + input;
29
+ const response = await fetch(input, init);
30
+ if (response.status >= 400) {
31
+ let json;
32
+ const text = await response.text();
33
+ if (text) {
34
+ try {
35
+ json = JSON.parse(text);
36
+ }
37
+ catch {
38
+ /* empty */
84
39
  }
85
- throw new Error(`HTTP Error: ${response.status} ${response.statusText}`);
40
+ if (json?.error)
41
+ throw new Error(json.error);
42
+ throw new Error(text);
86
43
  }
87
- return response;
88
- });
44
+ throw new Error(`HTTP Error: ${response.status} ${response.statusText}`);
45
+ }
46
+ return response;
89
47
  }
90
- fetchJson(input, init) {
91
- return __awaiter(this, void 0, void 0, function* () {
92
- const response = yield this.fetch(input, init);
93
- return response.json();
94
- });
48
+ async fetchJson(input, init) {
49
+ const response = await this.fetch(input, init);
50
+ return response.json();
95
51
  }
96
52
  }
97
53
 
@@ -175,10 +131,9 @@ class RealtimeError extends Error {
175
131
  const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
176
132
  class RealtimeService {
177
133
  constructor(params) {
178
- var _a, _b;
179
134
  this.listeners = {};
180
- this.realtimeUrl = (_a = params.realtimeUrl) !== null && _a !== void 0 ? _a : defaultRealtimeUrl;
181
- this.sampleRate = (_b = params.sampleRate) !== null && _b !== void 0 ? _b : 16000;
135
+ this.realtimeUrl = params.realtimeUrl ?? defaultRealtimeUrl;
136
+ this.sampleRate = params.sampleRate ?? 16000;
182
137
  this.wordBoost = params.wordBoost;
183
138
  if ("apiKey" in params && params.apiKey)
184
139
  this.apiKey = params.apiKey;
@@ -223,26 +178,23 @@ class RealtimeService {
223
178
  });
224
179
  }
225
180
  this.socket.onclose = ({ code, reason }) => {
226
- var _a, _b;
227
181
  if (!reason) {
228
182
  if (code in RealtimeErrorType) {
229
183
  reason = RealtimeErrorMessages[code];
230
184
  }
231
185
  }
232
- (_b = (_a = this.listeners).close) === null || _b === void 0 ? void 0 : _b.call(_a, code, reason);
186
+ this.listeners.close?.(code, reason);
233
187
  };
234
188
  this.socket.onerror = (event) => {
235
- var _a, _b, _c, _d;
236
189
  if (event.error)
237
- (_b = (_a = this.listeners).error) === null || _b === void 0 ? void 0 : _b.call(_a, event.error);
190
+ this.listeners.error?.(event.error);
238
191
  else
239
- (_d = (_c = this.listeners).error) === null || _d === void 0 ? void 0 : _d.call(_c, new Error(event.message));
192
+ this.listeners.error?.(new Error(event.message));
240
193
  };
241
194
  this.socket.onmessage = ({ data }) => {
242
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
243
195
  const message = JSON.parse(data.toString());
244
196
  if ("error" in message) {
245
- (_b = (_a = this.listeners).error) === null || _b === void 0 ? void 0 : _b.call(_a, new RealtimeError(message.error));
197
+ this.listeners.error?.(new RealtimeError(message.error));
246
198
  return;
247
199
  }
248
200
  switch (message.message_type) {
@@ -252,25 +204,25 @@ class RealtimeService {
252
204
  expiresAt: new Date(message.expires_at),
253
205
  };
254
206
  resolve(openObject);
255
- (_d = (_c = this.listeners).open) === null || _d === void 0 ? void 0 : _d.call(_c, openObject);
207
+ this.listeners.open?.(openObject);
256
208
  break;
257
209
  }
258
210
  case "PartialTranscript": {
259
211
  // message.created is actually a string when coming from the socket
260
212
  message.created = new Date(message.created);
261
- (_f = (_e = this.listeners).transcript) === null || _f === void 0 ? void 0 : _f.call(_e, message);
262
- (_h = (_g = this.listeners)["transcript.partial"]) === null || _h === void 0 ? void 0 : _h.call(_g, message);
213
+ this.listeners.transcript?.(message);
214
+ this.listeners["transcript.partial"]?.(message);
263
215
  break;
264
216
  }
265
217
  case "FinalTranscript": {
266
218
  // message.created is actually a string when coming from the socket
267
219
  message.created = new Date(message.created);
268
- (_k = (_j = this.listeners).transcript) === null || _k === void 0 ? void 0 : _k.call(_j, message);
269
- (_m = (_l = this.listeners)["transcript.final"]) === null || _m === void 0 ? void 0 : _m.call(_l, message);
220
+ this.listeners.transcript?.(message);
221
+ this.listeners["transcript.final"]?.(message);
270
222
  break;
271
223
  }
272
224
  case "SessionTerminated": {
273
- (_o = this.sessionTerminatedResolve) === null || _o === void 0 ? void 0 : _o.call(this);
225
+ this.sessionTerminatedResolve?.();
274
226
  break;
275
227
  }
276
228
  }
@@ -302,29 +254,27 @@ class RealtimeService {
302
254
  },
303
255
  });
304
256
  }
305
- close(waitForSessionTermination = true) {
306
- return __awaiter(this, void 0, void 0, function* () {
307
- if (this.socket) {
308
- if (this.socket.readyState === WebSocket.OPEN) {
309
- const terminateSessionMessage = `{"terminate_session": true}`;
310
- if (waitForSessionTermination) {
311
- const sessionTerminatedPromise = new Promise((resolve) => {
312
- this.sessionTerminatedResolve = resolve;
313
- });
314
- this.socket.send(terminateSessionMessage);
315
- yield sessionTerminatedPromise;
316
- }
317
- else {
318
- this.socket.send(terminateSessionMessage);
319
- }
257
+ async close(waitForSessionTermination = true) {
258
+ if (this.socket) {
259
+ if (this.socket.readyState === WebSocket.OPEN) {
260
+ const terminateSessionMessage = `{"terminate_session": true}`;
261
+ if (waitForSessionTermination) {
262
+ const sessionTerminatedPromise = new Promise((resolve) => {
263
+ this.sessionTerminatedResolve = resolve;
264
+ });
265
+ this.socket.send(terminateSessionMessage);
266
+ await sessionTerminatedPromise;
267
+ }
268
+ else {
269
+ this.socket.send(terminateSessionMessage);
320
270
  }
321
- if ("removeAllListeners" in this.socket)
322
- this.socket.removeAllListeners();
323
- this.socket.close();
324
271
  }
325
- this.listeners = {};
326
- this.socket = undefined;
327
- });
272
+ if ("removeAllListeners" in this.socket)
273
+ this.socket.removeAllListeners();
274
+ this.socket.close();
275
+ }
276
+ this.listeners = {};
277
+ this.socket = undefined;
328
278
  }
329
279
  }
330
280
 
@@ -341,14 +291,12 @@ class RealtimeServiceFactory extends BaseService {
341
291
  }
342
292
  return new RealtimeService(params);
343
293
  }
344
- createTemporaryToken(params) {
345
- return __awaiter(this, void 0, void 0, function* () {
346
- const data = yield this.fetchJson("/v2/realtime/token", {
347
- method: "POST",
348
- body: JSON.stringify(params),
349
- });
350
- return data.token;
294
+ async createTemporaryToken(params) {
295
+ const data = await this.fetchJson("/v2/realtime/token", {
296
+ method: "POST",
297
+ body: JSON.stringify(params),
351
298
  });
299
+ return data.token;
352
300
  }
353
301
  }
354
302
 
@@ -363,42 +311,38 @@ class TranscriptService extends BaseService {
363
311
  * @param options The options to transcribe an audio file.
364
312
  * @returns A promise that resolves to the transcript. The transcript status is "completed" or "error".
365
313
  */
366
- transcribe(params, options) {
367
- return __awaiter(this, void 0, void 0, function* () {
368
- const transcript = yield this.submit(params);
369
- return yield this.waitUntilReady(transcript.id, options);
370
- });
314
+ async transcribe(params, options) {
315
+ const transcript = await this.submit(params);
316
+ return await this.waitUntilReady(transcript.id, options);
371
317
  }
372
318
  /**
373
319
  * Submits a transcription job for an audio file. This will not wait until the transcript status is "completed" or "error".
374
320
  * @param params The parameters to start the transcription of an audio file.
375
321
  * @returns A promise that resolves to the queued transcript.
376
322
  */
377
- submit(params) {
378
- return __awaiter(this, void 0, void 0, function* () {
379
- const { audio } = params, createParams = __rest(params, ["audio"]);
380
- let audioUrl;
381
- if (typeof audio === "string") {
382
- const path = getPath(audio);
383
- if (path !== null) {
384
- // audio is local path, upload local file
385
- audioUrl = yield this.files.upload(path);
386
- }
387
- else {
388
- // audio is not a local path, assume it's a URL
389
- audioUrl = audio;
390
- }
323
+ async submit(params) {
324
+ const { audio, ...createParams } = params;
325
+ let audioUrl;
326
+ if (typeof audio === "string") {
327
+ const path = getPath(audio);
328
+ if (path !== null) {
329
+ // audio is local path, upload local file
330
+ audioUrl = await this.files.upload(path);
391
331
  }
392
332
  else {
393
- // audio is of uploadable type
394
- audioUrl = yield this.files.upload(audio);
333
+ // audio is not a local path, assume it's a URL
334
+ audioUrl = audio;
395
335
  }
396
- const data = yield this.fetchJson("/v2/transcript", {
397
- method: "POST",
398
- body: JSON.stringify(Object.assign(Object.assign({}, createParams), { audio_url: audioUrl })),
399
- });
400
- return data;
336
+ }
337
+ else {
338
+ // audio is of uploadable type
339
+ audioUrl = await this.files.upload(audio);
340
+ }
341
+ const data = await this.fetchJson("/v2/transcript", {
342
+ method: "POST",
343
+ body: JSON.stringify({ ...createParams, audio_url: audioUrl }),
401
344
  });
345
+ return data;
402
346
  }
403
347
  /**
404
348
  * Create a transcript.
@@ -407,23 +351,20 @@ class TranscriptService extends BaseService {
407
351
  * @returns A promise that resolves to the transcript.
408
352
  * @deprecated Use `transcribe` instead to transcribe a audio file that includes polling, or `submit` to transcribe a audio file without polling.
409
353
  */
410
- create(params, options) {
411
- var _a;
412
- return __awaiter(this, void 0, void 0, function* () {
413
- const path = getPath(params.audio_url);
414
- if (path !== null) {
415
- const uploadUrl = yield this.files.upload(path);
416
- params.audio_url = uploadUrl;
417
- }
418
- const data = yield this.fetchJson("/v2/transcript", {
419
- method: "POST",
420
- body: JSON.stringify(params),
421
- });
422
- if ((_a = options === null || options === void 0 ? void 0 : options.poll) !== null && _a !== void 0 ? _a : true) {
423
- return yield this.waitUntilReady(data.id, options);
424
- }
425
- return data;
354
+ async create(params, options) {
355
+ const path = getPath(params.audio_url);
356
+ if (path !== null) {
357
+ const uploadUrl = await this.files.upload(path);
358
+ params.audio_url = uploadUrl;
359
+ }
360
+ const data = await this.fetchJson("/v2/transcript", {
361
+ method: "POST",
362
+ body: JSON.stringify(params),
426
363
  });
364
+ if (options?.poll ?? true) {
365
+ return await this.waitUntilReady(data.id, options);
366
+ }
367
+ return data;
427
368
  }
428
369
  /**
429
370
  * Wait until the transcript ready, either the status is "completed" or "error".
@@ -431,27 +372,24 @@ class TranscriptService extends BaseService {
431
372
  * @param options The options to wait until the transcript is ready.
432
373
  * @returns A promise that resolves to the transcript. The transcript status is "completed" or "error".
433
374
  */
434
- waitUntilReady(transcriptId, options) {
435
- var _a, _b;
436
- return __awaiter(this, void 0, void 0, function* () {
437
- const pollingInterval = (_a = options === null || options === void 0 ? void 0 : options.pollingInterval) !== null && _a !== void 0 ? _a : 3000;
438
- const pollingTimeout = (_b = options === null || options === void 0 ? void 0 : options.pollingTimeout) !== null && _b !== void 0 ? _b : -1;
439
- const startTime = Date.now();
440
- // eslint-disable-next-line no-constant-condition
441
- while (true) {
442
- const transcript = yield this.get(transcriptId);
443
- if (transcript.status === "completed" || transcript.status === "error") {
444
- return transcript;
445
- }
446
- else if (pollingTimeout > 0 &&
447
- Date.now() - startTime > pollingTimeout) {
448
- throw new Error("Polling timeout");
449
- }
450
- else {
451
- yield new Promise((resolve) => setTimeout(resolve, pollingInterval));
452
- }
375
+ async waitUntilReady(transcriptId, options) {
376
+ const pollingInterval = options?.pollingInterval ?? 3000;
377
+ const pollingTimeout = options?.pollingTimeout ?? -1;
378
+ const startTime = Date.now();
379
+ // eslint-disable-next-line no-constant-condition
380
+ while (true) {
381
+ const transcript = await this.get(transcriptId);
382
+ if (transcript.status === "completed" || transcript.status === "error") {
383
+ return transcript;
453
384
  }
454
- });
385
+ else if (pollingTimeout > 0 &&
386
+ Date.now() - startTime > pollingTimeout) {
387
+ throw new Error("Polling timeout");
388
+ }
389
+ else {
390
+ await new Promise((resolve) => setTimeout(resolve, pollingInterval));
391
+ }
392
+ }
455
393
  }
456
394
  /**
457
395
  * Retrieve a transcript.
@@ -465,30 +403,25 @@ class TranscriptService extends BaseService {
465
403
  * Retrieves a page of transcript listings.
466
404
  * @param parameters The parameters to filter the transcript list by, or the URL to retrieve the transcript list from.
467
405
  */
468
- list(parameters) {
469
- return __awaiter(this, void 0, void 0, function* () {
470
- let url = "/v2/transcript";
471
- if (typeof parameters === "string") {
472
- url = parameters;
473
- }
474
- else if (parameters) {
475
- url = `${url}?${new URLSearchParams(Object.keys(parameters).map((key) => {
476
- var _a;
477
- return [
478
- key,
479
- ((_a = parameters[key]) === null || _a === void 0 ? void 0 : _a.toString()) || "",
480
- ];
481
- }))}`;
482
- }
483
- const data = yield this.fetchJson(url);
484
- for (const transcriptListItem of data.transcripts) {
485
- transcriptListItem.created = new Date(transcriptListItem.created);
486
- if (transcriptListItem.completed) {
487
- transcriptListItem.completed = new Date(transcriptListItem.completed);
488
- }
406
+ async list(parameters) {
407
+ let url = "/v2/transcript";
408
+ if (typeof parameters === "string") {
409
+ url = parameters;
410
+ }
411
+ else if (parameters) {
412
+ url = `${url}?${new URLSearchParams(Object.keys(parameters).map((key) => [
413
+ key,
414
+ parameters[key]?.toString() || "",
415
+ ]))}`;
416
+ }
417
+ const data = await this.fetchJson(url);
418
+ for (const transcriptListItem of data.transcripts) {
419
+ transcriptListItem.created = new Date(transcriptListItem.created);
420
+ if (transcriptListItem.completed) {
421
+ transcriptListItem.completed = new Date(transcriptListItem.completed);
489
422
  }
490
- return data;
491
- });
423
+ }
424
+ return data;
492
425
  }
493
426
  /**
494
427
  * Delete a transcript
@@ -532,17 +465,15 @@ class TranscriptService extends BaseService {
532
465
  * @param chars_per_caption The maximum number of characters per caption.
533
466
  * @return A promise that resolves to the subtitles text.
534
467
  */
535
- subtitles(id, format = "srt", chars_per_caption) {
536
- return __awaiter(this, void 0, void 0, function* () {
537
- let url = `/v2/transcript/${id}/${format}`;
538
- if (chars_per_caption) {
539
- const params = new URLSearchParams();
540
- params.set("chars_per_caption", chars_per_caption.toString());
541
- url += `?${params.toString()}`;
542
- }
543
- const response = yield this.fetch(url);
544
- return yield response.text();
545
- });
468
+ async subtitles(id, format = "srt", chars_per_caption) {
469
+ let url = `/v2/transcript/${id}/${format}`;
470
+ if (chars_per_caption) {
471
+ const params = new URLSearchParams();
472
+ params.set("chars_per_caption", chars_per_caption.toString());
473
+ url += `?${params.toString()}`;
474
+ }
475
+ const response = await this.fetch(url);
476
+ return await response.text();
546
477
  }
547
478
  /**
548
479
  * Retrieve redactions of a transcript.
@@ -562,34 +493,34 @@ function getPath(path) {
562
493
  else
563
494
  return null;
564
495
  }
565
- catch (_a) {
496
+ catch {
566
497
  return path;
567
498
  }
568
499
  }
569
500
 
501
+ const readFile = async (path) => stream.Readable.toWeb(fs.createReadStream(path));
502
+
570
503
  class FileService extends BaseService {
571
504
  /**
572
505
  * Upload a local file to AssemblyAI.
573
506
  * @param input The local file path to upload, or a stream or buffer of the file to upload.
574
507
  * @return A promise that resolves to the uploaded file URL.
575
508
  */
576
- upload(input) {
577
- return __awaiter(this, void 0, void 0, function* () {
578
- let fileData;
579
- if (typeof input === "string")
580
- fileData = fs.createReadStream(input);
581
- else
582
- fileData = input;
583
- const data = yield this.fetchJson("/v2/upload", {
584
- method: "POST",
585
- body: fileData,
586
- headers: {
587
- "Content-Type": "application/octet-stream",
588
- },
589
- duplex: "half",
590
- });
591
- return data.upload_url;
509
+ async upload(input) {
510
+ let fileData;
511
+ if (typeof input === "string")
512
+ fileData = await readFile(input);
513
+ else
514
+ fileData = input;
515
+ const data = await this.fetchJson("/v2/upload", {
516
+ method: "POST",
517
+ body: fileData,
518
+ headers: {
519
+ "Content-Type": "application/octet-stream",
520
+ },
521
+ duplex: "half",
592
522
  });
523
+ return data.upload_url;
593
524
  }
594
525
  }
595
526