assemblyai 4.0.0-beta.0 → 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.
package/dist/node.cjs ADDED
@@ -0,0 +1,549 @@
1
+ 'use strict';
2
+
3
+ var isomorphicStreams = require('@swimburger/isomorphic-streams');
4
+ var WebSocket = require('isomorphic-ws');
5
+ var fs = require('fs');
6
+ var stream = require('stream');
7
+
8
+ /**
9
+ * Base class for services that communicate with the API.
10
+ */
11
+ class BaseService {
12
+ /**
13
+ * Create a new service.
14
+ * @param params The parameters to use for the service.
15
+ */
16
+ constructor(params) {
17
+ this.params = params;
18
+ }
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 */
39
+ }
40
+ if (json?.error)
41
+ throw new Error(json.error);
42
+ throw new Error(text);
43
+ }
44
+ throw new Error(`HTTP Error: ${response.status} ${response.statusText}`);
45
+ }
46
+ return response;
47
+ }
48
+ async fetchJson(input, init) {
49
+ const response = await this.fetch(input, init);
50
+ return response.json();
51
+ }
52
+ }
53
+
54
+ class LemurService extends BaseService {
55
+ summary(params) {
56
+ return this.fetchJson("/lemur/v3/generate/summary", {
57
+ method: "POST",
58
+ body: JSON.stringify(params),
59
+ });
60
+ }
61
+ questionAnswer(params) {
62
+ return this.fetchJson("/lemur/v3/generate/question-answer", {
63
+ method: "POST",
64
+ body: JSON.stringify(params),
65
+ });
66
+ }
67
+ actionItems(params) {
68
+ return this.fetchJson("/lemur/v3/generate/action-items", {
69
+ method: "POST",
70
+ body: JSON.stringify(params),
71
+ });
72
+ }
73
+ task(params) {
74
+ return this.fetchJson("/lemur/v3/generate/task", {
75
+ method: "POST",
76
+ body: JSON.stringify(params),
77
+ });
78
+ }
79
+ /**
80
+ * Delete the data for a previously submitted LeMUR request.
81
+ * @param id ID of the LeMUR request
82
+ */
83
+ purgeRequestData(id) {
84
+ return this.fetchJson(`/lemur/v3/${id}`, {
85
+ method: "DELETE",
86
+ });
87
+ }
88
+ }
89
+
90
+ var RealtimeErrorType;
91
+ (function (RealtimeErrorType) {
92
+ RealtimeErrorType[RealtimeErrorType["BadSampleRate"] = 4000] = "BadSampleRate";
93
+ RealtimeErrorType[RealtimeErrorType["AuthFailed"] = 4001] = "AuthFailed";
94
+ // Both InsufficientFunds and FreeAccount error use 4002
95
+ RealtimeErrorType[RealtimeErrorType["InsufficientFundsOrFreeAccount"] = 4002] = "InsufficientFundsOrFreeAccount";
96
+ RealtimeErrorType[RealtimeErrorType["NonexistentSessionId"] = 4004] = "NonexistentSessionId";
97
+ RealtimeErrorType[RealtimeErrorType["SessionExpired"] = 4008] = "SessionExpired";
98
+ RealtimeErrorType[RealtimeErrorType["ClosedSession"] = 4010] = "ClosedSession";
99
+ RealtimeErrorType[RealtimeErrorType["RateLimited"] = 4029] = "RateLimited";
100
+ RealtimeErrorType[RealtimeErrorType["UniqueSessionViolation"] = 4030] = "UniqueSessionViolation";
101
+ RealtimeErrorType[RealtimeErrorType["SessionTimeout"] = 4031] = "SessionTimeout";
102
+ RealtimeErrorType[RealtimeErrorType["AudioTooShort"] = 4032] = "AudioTooShort";
103
+ RealtimeErrorType[RealtimeErrorType["AudioTooLong"] = 4033] = "AudioTooLong";
104
+ RealtimeErrorType[RealtimeErrorType["BadJson"] = 4100] = "BadJson";
105
+ RealtimeErrorType[RealtimeErrorType["BadSchema"] = 4101] = "BadSchema";
106
+ RealtimeErrorType[RealtimeErrorType["TooManyStreams"] = 4102] = "TooManyStreams";
107
+ RealtimeErrorType[RealtimeErrorType["Reconnected"] = 4103] = "Reconnected";
108
+ RealtimeErrorType[RealtimeErrorType["ReconnectAttemptsExhausted"] = 1013] = "ReconnectAttemptsExhausted";
109
+ })(RealtimeErrorType || (RealtimeErrorType = {}));
110
+ const RealtimeErrorMessages = {
111
+ [RealtimeErrorType.BadSampleRate]: "Sample rate must be a positive integer",
112
+ [RealtimeErrorType.AuthFailed]: "Not Authorized",
113
+ [RealtimeErrorType.InsufficientFundsOrFreeAccount]: "Insufficient funds or you are using a free account. This feature is paid-only and requires you to add a credit card. Please visit https://assemblyai.com/dashboard/ to add a credit card to your account.",
114
+ [RealtimeErrorType.NonexistentSessionId]: "Session ID does not exist",
115
+ [RealtimeErrorType.SessionExpired]: "Session has expired",
116
+ [RealtimeErrorType.ClosedSession]: "Session is closed",
117
+ [RealtimeErrorType.RateLimited]: "Rate limited",
118
+ [RealtimeErrorType.UniqueSessionViolation]: "Unique session violation",
119
+ [RealtimeErrorType.SessionTimeout]: "Session Timeout",
120
+ [RealtimeErrorType.AudioTooShort]: "Audio too short",
121
+ [RealtimeErrorType.AudioTooLong]: "Audio too long",
122
+ [RealtimeErrorType.BadJson]: "Bad JSON",
123
+ [RealtimeErrorType.BadSchema]: "Bad schema",
124
+ [RealtimeErrorType.TooManyStreams]: "Too many streams",
125
+ [RealtimeErrorType.Reconnected]: "Reconnected",
126
+ [RealtimeErrorType.ReconnectAttemptsExhausted]: "Reconnect attempts exhausted",
127
+ };
128
+ class RealtimeError extends Error {
129
+ }
130
+
131
+ const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
132
+ class RealtimeService {
133
+ constructor(params) {
134
+ this.listeners = {};
135
+ this.realtimeUrl = params.realtimeUrl ?? defaultRealtimeUrl;
136
+ this.sampleRate = params.sampleRate ?? 16000;
137
+ this.wordBoost = params.wordBoost;
138
+ if ("apiKey" in params && params.apiKey)
139
+ this.apiKey = params.apiKey;
140
+ if ("token" in params && params.token)
141
+ this.token = params.token;
142
+ if (!(this.apiKey || this.token)) {
143
+ throw new Error("API key or temporary token is required.");
144
+ }
145
+ }
146
+ connectionUrl() {
147
+ const url = new URL(this.realtimeUrl);
148
+ if (url.protocol !== "wss:") {
149
+ throw new Error("Invalid protocol, must be wss");
150
+ }
151
+ const searchParams = new URLSearchParams();
152
+ if (this.token) {
153
+ searchParams.set("token", this.token);
154
+ }
155
+ searchParams.set("sample_rate", this.sampleRate.toString());
156
+ if (this.wordBoost && this.wordBoost.length > 0) {
157
+ searchParams.set("word_boost", JSON.stringify(this.wordBoost));
158
+ }
159
+ url.search = searchParams.toString();
160
+ return url;
161
+ }
162
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
163
+ on(event, listener) {
164
+ this.listeners[event] = listener;
165
+ }
166
+ connect() {
167
+ return new Promise((resolve) => {
168
+ if (this.socket) {
169
+ throw new Error("Already connected");
170
+ }
171
+ const url = this.connectionUrl();
172
+ if (this.token) {
173
+ this.socket = new WebSocket(url.toString());
174
+ }
175
+ else {
176
+ this.socket = new WebSocket(url.toString(), {
177
+ headers: { Authorization: this.apiKey },
178
+ });
179
+ }
180
+ this.socket.onclose = ({ code, reason }) => {
181
+ if (!reason) {
182
+ if (code in RealtimeErrorType) {
183
+ reason = RealtimeErrorMessages[code];
184
+ }
185
+ }
186
+ this.listeners.close?.(code, reason);
187
+ };
188
+ this.socket.onerror = (event) => {
189
+ if (event.error)
190
+ this.listeners.error?.(event.error);
191
+ else
192
+ this.listeners.error?.(new Error(event.message));
193
+ };
194
+ this.socket.onmessage = ({ data }) => {
195
+ const message = JSON.parse(data.toString());
196
+ if ("error" in message) {
197
+ this.listeners.error?.(new RealtimeError(message.error));
198
+ return;
199
+ }
200
+ switch (message.message_type) {
201
+ case "SessionBegins": {
202
+ const openObject = {
203
+ sessionId: message.session_id,
204
+ expiresAt: new Date(message.expires_at),
205
+ };
206
+ resolve(openObject);
207
+ this.listeners.open?.(openObject);
208
+ break;
209
+ }
210
+ case "PartialTranscript": {
211
+ // message.created is actually a string when coming from the socket
212
+ message.created = new Date(message.created);
213
+ this.listeners.transcript?.(message);
214
+ this.listeners["transcript.partial"]?.(message);
215
+ break;
216
+ }
217
+ case "FinalTranscript": {
218
+ // message.created is actually a string when coming from the socket
219
+ message.created = new Date(message.created);
220
+ this.listeners.transcript?.(message);
221
+ this.listeners["transcript.final"]?.(message);
222
+ break;
223
+ }
224
+ case "SessionTerminated": {
225
+ this.sessionTerminatedResolve?.();
226
+ break;
227
+ }
228
+ }
229
+ };
230
+ });
231
+ }
232
+ sendAudio(audio) {
233
+ if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
234
+ throw new Error("Socket is not open for communication");
235
+ }
236
+ let audioData;
237
+ if (typeof Buffer !== "undefined") {
238
+ audioData = Buffer.from(audio).toString("base64");
239
+ }
240
+ else {
241
+ // Buffer is not available in the browser by default
242
+ // https://stackoverflow.com/a/42334410/2919731
243
+ audioData = btoa(new Uint8Array(audio).reduce((data, byte) => data + String.fromCharCode(byte), ""));
244
+ }
245
+ const payload = {
246
+ audio_data: audioData,
247
+ };
248
+ this.socket.send(JSON.stringify(payload));
249
+ }
250
+ stream() {
251
+ return new isomorphicStreams.WritableStream({
252
+ write: (chunk) => {
253
+ this.sendAudio(chunk);
254
+ },
255
+ });
256
+ }
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);
270
+ }
271
+ }
272
+ if ("removeAllListeners" in this.socket)
273
+ this.socket.removeAllListeners();
274
+ this.socket.close();
275
+ }
276
+ this.listeners = {};
277
+ this.socket = undefined;
278
+ }
279
+ }
280
+
281
+ class RealtimeServiceFactory extends BaseService {
282
+ constructor(params) {
283
+ super(params);
284
+ this.rtFactoryParams = params;
285
+ }
286
+ createService(params) {
287
+ if (!params)
288
+ params = { apiKey: this.rtFactoryParams.apiKey };
289
+ else if (!("token" in params) && !params.apiKey) {
290
+ params.apiKey = this.rtFactoryParams.apiKey;
291
+ }
292
+ return new RealtimeService(params);
293
+ }
294
+ async createTemporaryToken(params) {
295
+ const data = await this.fetchJson("/v2/realtime/token", {
296
+ method: "POST",
297
+ body: JSON.stringify(params),
298
+ });
299
+ return data.token;
300
+ }
301
+ }
302
+
303
+ class TranscriptService extends BaseService {
304
+ constructor(params, files) {
305
+ super(params);
306
+ this.files = files;
307
+ }
308
+ /**
309
+ * Transcribe an audio file. This will create a transcript and wait until the transcript status is "completed" or "error".
310
+ * @param params The parameters to transcribe an audio file.
311
+ * @param options The options to transcribe an audio file.
312
+ * @returns A promise that resolves to the transcript. The transcript status is "completed" or "error".
313
+ */
314
+ async transcribe(params, options) {
315
+ const transcript = await this.submit(params);
316
+ return await this.waitUntilReady(transcript.id, options);
317
+ }
318
+ /**
319
+ * Submits a transcription job for an audio file. This will not wait until the transcript status is "completed" or "error".
320
+ * @param params The parameters to start the transcription of an audio file.
321
+ * @returns A promise that resolves to the queued transcript.
322
+ */
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);
331
+ }
332
+ else {
333
+ // audio is not a local path, assume it's a URL
334
+ audioUrl = audio;
335
+ }
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 }),
344
+ });
345
+ return data;
346
+ }
347
+ /**
348
+ * Create a transcript.
349
+ * @param params The parameters to create a transcript.
350
+ * @param options The options used for creating the new transcript.
351
+ * @returns A promise that resolves to the transcript.
352
+ * @deprecated Use `transcribe` instead to transcribe a audio file that includes polling, or `submit` to transcribe a audio file without polling.
353
+ */
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),
363
+ });
364
+ if (options?.poll ?? true) {
365
+ return await this.waitUntilReady(data.id, options);
366
+ }
367
+ return data;
368
+ }
369
+ /**
370
+ * Wait until the transcript ready, either the status is "completed" or "error".
371
+ * @param transcriptId The ID of the transcript.
372
+ * @param options The options to wait until the transcript is ready.
373
+ * @returns A promise that resolves to the transcript. The transcript status is "completed" or "error".
374
+ */
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;
384
+ }
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
+ }
393
+ }
394
+ /**
395
+ * Retrieve a transcript.
396
+ * @param id The identifier of the transcript.
397
+ * @returns A promise that resolves to the transcript.
398
+ */
399
+ get(id) {
400
+ return this.fetchJson(`/v2/transcript/${id}`);
401
+ }
402
+ /**
403
+ * Retrieves a page of transcript listings.
404
+ * @param parameters The parameters to filter the transcript list by, or the URL to retrieve the transcript list from.
405
+ */
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);
422
+ }
423
+ }
424
+ return data;
425
+ }
426
+ /**
427
+ * Delete a transcript
428
+ * @param id The identifier of the transcript.
429
+ * @returns A promise that resolves to the transcript.
430
+ */
431
+ delete(id) {
432
+ return this.fetchJson(`/v2/transcript/${id}`, { method: "DELETE" });
433
+ }
434
+ /**
435
+ * Search through the transcript for a specific set of keywords.
436
+ * You can search for individual words, numbers, or phrases containing up to five words or numbers.
437
+ * @param id The identifier of the transcript.
438
+ * @param words Keywords to search for.
439
+ * @return A promise that resolves to the sentences.
440
+ */
441
+ wordSearch(id, words) {
442
+ const params = new URLSearchParams({ words: words.join(",") });
443
+ return this.fetchJson(`/v2/transcript/${id}/word-search?${params.toString()}`);
444
+ }
445
+ /**
446
+ * Retrieve all sentences of a transcript.
447
+ * @param id The identifier of the transcript.
448
+ * @return A promise that resolves to the sentences.
449
+ */
450
+ sentences(id) {
451
+ return this.fetchJson(`/v2/transcript/${id}/sentences`);
452
+ }
453
+ /**
454
+ * Retrieve all paragraphs of a transcript.
455
+ * @param id The identifier of the transcript.
456
+ * @return A promise that resolves to the paragraphs.
457
+ */
458
+ paragraphs(id) {
459
+ return this.fetchJson(`/v2/transcript/${id}/paragraphs`);
460
+ }
461
+ /**
462
+ * Retrieve subtitles of a transcript.
463
+ * @param id The identifier of the transcript.
464
+ * @param format The format of the subtitles.
465
+ * @param chars_per_caption The maximum number of characters per caption.
466
+ * @return A promise that resolves to the subtitles text.
467
+ */
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();
477
+ }
478
+ /**
479
+ * Retrieve redactions of a transcript.
480
+ * @param id The identifier of the transcript.
481
+ * @return A promise that resolves to the subtitles text.
482
+ */
483
+ redactions(id) {
484
+ return this.fetchJson(`/v2/transcript/${id}/redacted-audio`);
485
+ }
486
+ }
487
+ function getPath(path) {
488
+ let url;
489
+ try {
490
+ url = new URL(path);
491
+ if (url.protocol === "file:")
492
+ return url.pathname;
493
+ else
494
+ return null;
495
+ }
496
+ catch {
497
+ return path;
498
+ }
499
+ }
500
+
501
+ const readFile = async (path) => stream.Readable.toWeb(fs.createReadStream(path));
502
+
503
+ class FileService extends BaseService {
504
+ /**
505
+ * Upload a local file to AssemblyAI.
506
+ * @param input The local file path to upload, or a stream or buffer of the file to upload.
507
+ * @return A promise that resolves to the uploaded file URL.
508
+ */
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",
522
+ });
523
+ return data.upload_url;
524
+ }
525
+ }
526
+
527
+ const defaultBaseUrl = "https://api.assemblyai.com";
528
+ class AssemblyAI {
529
+ /**
530
+ * Create a new AssemblyAI client.
531
+ * @param params The parameters for the service, including the API key and base URL, if any.
532
+ */
533
+ constructor(params) {
534
+ params.baseUrl = params.baseUrl || defaultBaseUrl;
535
+ if (params.baseUrl && params.baseUrl.endsWith("/"))
536
+ params.baseUrl = params.baseUrl.slice(0, -1);
537
+ this.files = new FileService(params);
538
+ this.transcripts = new TranscriptService(params, this.files);
539
+ this.lemur = new LemurService(params);
540
+ this.realtime = new RealtimeServiceFactory(params);
541
+ }
542
+ }
543
+
544
+ exports.AssemblyAI = AssemblyAI;
545
+ exports.FileService = FileService;
546
+ exports.LemurService = LemurService;
547
+ exports.RealtimeService = RealtimeService;
548
+ exports.RealtimeServiceFactory = RealtimeServiceFactory;
549
+ exports.TranscriptService = TranscriptService;