assemblyai 1.0.0 → 2.0.0-beta

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.
Files changed (81) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +79 -66
  3. package/dist/index.d.ts +2 -0
  4. package/dist/index.esm.js +378 -0
  5. package/dist/index.js +380 -0
  6. package/dist/services/base.d.ts +15 -0
  7. package/dist/services/files/index.d.ts +9 -0
  8. package/dist/services/index.d.ts +31 -0
  9. package/dist/services/lemur/index.d.ts +8 -0
  10. package/dist/services/realtime/index.d.ts +16 -0
  11. package/dist/services/transcripts/index.d.ts +42 -0
  12. package/dist/services/transcripts/redactions.d.ts +14 -0
  13. package/dist/services/transcripts/subtitles.d.ts +12 -0
  14. package/dist/types/core/index.d.ts +2 -0
  15. package/dist/types/core/params.d.ts +2 -0
  16. package/dist/types/core/segments.d.ts +28 -0
  17. package/dist/types/core/transcript.d.ts +113 -0
  18. package/dist/types/index.d.ts +6 -0
  19. package/dist/types/lemur/index.d.ts +79 -0
  20. package/dist/types/models/auto_chapter.d.ts +8 -0
  21. package/dist/types/models/auto_highlights.d.ts +11 -0
  22. package/dist/types/models/content_safety.d.ts +25 -0
  23. package/dist/types/models/entity_detection.d.ts +7 -0
  24. package/dist/types/models/index.d.ts +8 -0
  25. package/dist/types/models/pii.d.ts +3 -0
  26. package/dist/types/models/sentiment_analysis.d.ts +9 -0
  27. package/dist/types/models/shared.d.ts +3 -0
  28. package/dist/types/models/summarization.d.ts +3 -0
  29. package/dist/types/models/topic_detection.d.ts +17 -0
  30. package/dist/types/realtime/index.d.ts +17 -0
  31. package/dist/types/services/abstractions.d.ts +80 -0
  32. package/dist/types/services/index.d.ts +9 -0
  33. package/dist/types/shared/index.d.ts +2 -0
  34. package/dist/types/shared/pagination.d.ts +7 -0
  35. package/dist/types/shared/timestamp.d.ts +5 -0
  36. package/dist/utils/errors/index.d.ts +1 -0
  37. package/dist/utils/errors/realtime.d.ts +26 -0
  38. package/package.json +55 -21
  39. package/src/index.ts +2 -0
  40. package/src/services/base.ts +16 -0
  41. package/src/services/files/index.ts +22 -0
  42. package/src/services/index.ts +66 -0
  43. package/src/services/lemur/index.ts +45 -0
  44. package/src/services/realtime/index.ts +106 -0
  45. package/src/services/transcripts/index.ts +156 -0
  46. package/src/services/transcripts/redactions.ts +27 -0
  47. package/src/services/transcripts/subtitles.ts +26 -0
  48. package/src/types/core/index.ts +2 -0
  49. package/src/types/core/params.ts +3 -0
  50. package/src/types/core/segments.ts +29 -0
  51. package/src/types/core/transcript.ts +159 -0
  52. package/src/types/index.ts +6 -0
  53. package/src/types/lemur/index.ts +97 -0
  54. package/src/types/models/auto_chapter.ts +9 -0
  55. package/src/types/models/auto_highlights.ts +14 -0
  56. package/src/types/models/content_safety.ts +34 -0
  57. package/src/types/models/entity_detection.ts +8 -0
  58. package/src/types/models/index.ts +8 -0
  59. package/src/types/models/pii.ts +32 -0
  60. package/src/types/models/sentiment_analysis.ts +11 -0
  61. package/src/types/models/shared.ts +4 -0
  62. package/src/types/models/summarization.ts +10 -0
  63. package/src/types/models/topic_detection.ts +21 -0
  64. package/src/types/realtime/index.ts +28 -0
  65. package/src/types/services/abstractions.ts +88 -0
  66. package/src/types/services/index.ts +11 -0
  67. package/src/types/shared/index.ts +2 -0
  68. package/src/types/shared/pagination.ts +8 -0
  69. package/src/types/shared/timestamp.ts +6 -0
  70. package/src/utils/.gitkeep +0 -0
  71. package/src/utils/errors/index.ts +5 -0
  72. package/src/utils/errors/realtime.ts +58 -0
  73. package/.eslintrc.json +0 -3
  74. package/index.js +0 -15
  75. package/src/Client.js +0 -28
  76. package/src/api/Http/Request.js +0 -108
  77. package/src/api/Http/Response.js +0 -23
  78. package/src/api/Model.js +0 -17
  79. package/src/api/Transcript.js +0 -16
  80. package/src/api/Upload.js +0 -41
  81. package/src/api/util.js +0 -44
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 AssemblyAI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,112 +1,125 @@
1
- ## Installing the module:
1
+ # AssemblyAI Node.js SDK
2
2
 
3
- `npm i assemblyai`
3
+ The AssemblyAI Node.js SDK provides an easy-to-use interface for interacting with the AssemblyAI API,
4
+ which supports async and real-time transcription, as well as the latest LeMUR models.
4
5
 
5
- ## Authenticating with the API
6
+ ## Installation
6
7
 
7
- ### Using Environment Variables
8
+ Use [npm](https://www.npmjs.com/) to install AssemblyAI:
8
9
 
9
- If you have the `ASSEMBLYAI_API_KEY` environment variable set, then the application
10
- will attempt to read it and use this value to authenticate with the API.
10
+ ```bash
11
+ npm install assemblyai
12
+ ```
11
13
 
12
- ### Setting the value manually
14
+ # Usage
13
15
 
14
- Here is what the code would look like if you were to set the API token manually.
16
+ Import the AssemblyAI package and create an AssemblyAI object with your API token:
15
17
 
16
18
  ```javascript
17
- const assemblyai = require('assemblyai')
18
- assemblyai.setAPIKey("ENTER YOUR KEY HERE")
19
- ```
20
-
21
- ## Usage
19
+ import AssemblyAI from 'assemblyai'
22
20
 
23
- ```javascript
24
- const assemblyai = require('assemblyai')
25
- assemblyai.setAPIKey() // Note that the value is loaded from an environment variable.
21
+ const assembly = new AssemblyAI({
22
+ token: process.env.ASSEMBLYAI_API_KEY,
23
+ })
26
24
  ```
27
25
 
28
- ### Transcript
26
+ You can now use the `assembly` object to interact with the AssemblyAI API.
27
+
28
+ ## Create a Transcript
29
29
 
30
- Transcribing audio from a URL
30
+ When you create a transcript, you can either pass in a URL to an audio file, or upload a file directly.
31
31
 
32
32
  ```javascript
33
- const transcript = new assemblyai.Transcript()
33
+ // Using a remote URL
34
+ const created = await assembly.transcripts.create({
35
+ audio_url: 'https://storage.googleapis.com/aai-web-samples/espn-bears.m4a',
36
+ })
34
37
  ```
35
38
 
36
- #### Creating a job
39
+ ```javascript
40
+ // Uploading a file
41
+ const created = await assembly.transcripts.create({
42
+ audio_url: './news.mp4',
43
+ })
44
+ ```
37
45
 
38
- When creating a job, you are required to pass in the audio source.
46
+ ## Retrieve a Transcript
39
47
 
40
- An example with all of the options available is below, but the only required param would be `audio_src_url`.
48
+ This will return the transcript object in its current state. If the transcript is still processing, the `status` field will be `queued` or `processing`. Once the transcript is complete, the `status` field will be `completed`.
41
49
 
42
50
  ```javascript
43
- const response = await transcript.create({
44
- audio_src_url: "https://example.com/example.wav",
45
- model_id: 123,
46
- options: {
47
- format_text: true || false
48
- }
49
- })
51
+ const transcript = await assembly.transcripts.retrieve(created.id)
50
52
  ```
51
-
52
- #### Polling until job is complete
53
53
 
54
- Now that we have created a job, we can start polling for it.
54
+ ## Poll a Transcript
55
+
56
+ This will poll the transcript until it is complete. Once the transcript is complete, the `status` field will be `completed`.
55
57
 
56
58
  ```javascript
57
- const { id } = response.get()
58
- const complete = await transcript.poll(id)
59
+ const transcript = await assembly.transcripts.poll({
60
+ transcript_id: created.id,
61
+ })
59
62
  ```
60
63
 
61
- This ^ will wait until the job is complete or errors out until returning.
62
- If the job were to error out, an exception would be thrown.
63
-
64
- ### Models
64
+ ## List Transcripts
65
65
 
66
- Create a custom model to boost accuracy for phrases/keywords, or to add custom vocabulary.
66
+ This will return a list of all transcripts that you have created.
67
67
 
68
68
  ```javascript
69
- const model = new assemblyai.Model()
69
+ const page = await assembly.transcripts.list()
70
70
  ```
71
-
72
- #### Creating A Model
73
71
 
74
- Creating a model is very simple and is almost identical to creating a job.
75
-
72
+ ## Delete a Transcript
73
+
76
74
  ```javascript
77
- const response = await model.create({
78
- name: "foobar",
79
- phrases: ["foo", "bar"]
80
- })
75
+ const res = await assembly.transcripts.delete(transcript.id)
81
76
  ```
82
-
83
- #### Polling until the model has finished training
84
77
 
85
- This API is identical to the Transcript method which is used like so:
78
+ ## LeMUR
79
+
80
+ The SDK supports the latest LeMUR models. You can specify which model you would like to use when creating a transcript.
86
81
 
87
82
  ```javascript
88
- const { id } = response.get()
89
- await model.poll(id)
83
+ // Ask a question about the transcript
84
+ const { response } = await assembly.lemur.create({
85
+ type: 'question',
86
+ model: 'basic',
87
+ transcript_id: '0d295578-8c75-421a-885a-2c487f188927',
88
+ questions: [
89
+ {
90
+ question: 'What are they discussing?',
91
+ answer_format: 'text',
92
+ },
93
+ ],
94
+ })
90
95
  ```
91
96
 
92
- ### Uploading audio files for transcription
93
-
94
97
  ```javascript
95
- const upload = new assemblyai.Upload('/path/to/some/file.wav')
98
+ // Summarize the transcript
99
+ const { response } = await assembly.lemur.create({
100
+ type: 'summary',
101
+ model: 'basic',
102
+ transcript_id: '0d295578-8c75-421a-885a-2c487f188927',
103
+ context: {
104
+ speakers: ['Alex', 'Bob'],
105
+ },
106
+ })
96
107
  ```
97
108
 
98
109
  ```javascript
99
- const response = await upload.create()
100
- const { text } = response.get()
101
- console.log(text)
110
+ // AI Coach
111
+ const { response } = await assembly.lemur.create({
112
+ type: 'coach',
113
+ model: 'basic',
114
+ transcript_id: '0d295578-8c75-421a-885a-2c487f188927',
115
+ })
102
116
  ```
103
-
104
- ## The Response Object
105
117
 
106
- When using the `Response` object, you will find a couple of methods:
118
+ # Tests
107
119
 
108
- - `get()`
109
- - `toString()`
110
- - `stringify()`
120
+ To run the test suite, first install the dependencies, then run `npm test`:
111
121
 
112
- The method that you will most likely want to use will be `get()` which returns the full JSON object from the API, one level down.
122
+ ```bash
123
+ npm install
124
+ npm test
125
+ ```
@@ -0,0 +1,2 @@
1
+ import AssemblyAI from "./services";
2
+ export default AssemblyAI;
@@ -0,0 +1,378 @@
1
+ import axios, { isAxiosError } from 'axios';
2
+ import WebSocket from 'ws';
3
+ import fs from 'fs/promises';
4
+
5
+ /******************************************************************************
6
+ Copyright (c) Microsoft Corporation.
7
+
8
+ Permission to use, copy, modify, and/or distribute this software for any
9
+ purpose with or without fee is hereby granted.
10
+
11
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
12
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
14
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
16
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17
+ PERFORMANCE OF THIS SOFTWARE.
18
+ ***************************************************************************** */
19
+ /* global Reflect, Promise, SuppressedError, Symbol */
20
+
21
+
22
+ function __awaiter(thisArg, _arguments, P, generator) {
23
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
24
+ return new (P || (P = Promise))(function (resolve, reject) {
25
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
26
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
27
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
28
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
29
+ });
30
+ }
31
+
32
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
33
+ var e = new Error(message);
34
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
35
+ };
36
+
37
+ /**
38
+ * Base class for services that communicate with the API.
39
+ */
40
+ class BaseService {
41
+ /**
42
+ * Create a new service.
43
+ * @param params The AxiosInstance to send HTTP requests to the API.
44
+ */
45
+ constructor(client) {
46
+ this.client = client;
47
+ }
48
+ }
49
+
50
+ class LeMURService extends BaseService {
51
+ summary(params) {
52
+ return __awaiter(this, void 0, void 0, function* () {
53
+ const { data } = yield this.client.post("/lemur/v3/generate/summary", params);
54
+ return data;
55
+ });
56
+ }
57
+ questionAnswer(params) {
58
+ return __awaiter(this, void 0, void 0, function* () {
59
+ const { data } = yield this.client.post("/lemur/v3/generate/question-answer", params);
60
+ return data;
61
+ });
62
+ }
63
+ actionItems(params) {
64
+ return __awaiter(this, void 0, void 0, function* () {
65
+ const { data } = yield this.client.post("/lemur/v3/generate/action-items", params);
66
+ return data;
67
+ });
68
+ }
69
+ task(params) {
70
+ return __awaiter(this, void 0, void 0, function* () {
71
+ const { data } = yield this.client.post("/lemur/v3/generate/task", params);
72
+ return data;
73
+ });
74
+ }
75
+ }
76
+
77
+ var RealtimeErrorType;
78
+ (function (RealtimeErrorType) {
79
+ RealtimeErrorType[RealtimeErrorType["BadSampleRate"] = 4000] = "BadSampleRate";
80
+ RealtimeErrorType[RealtimeErrorType["AuthFailed"] = 4001] = "AuthFailed";
81
+ RealtimeErrorType[RealtimeErrorType["InsufficientFunds"] = 4002] = "InsufficientFunds";
82
+ RealtimeErrorType[RealtimeErrorType["FreeAccount"] = 4003] = "FreeAccount";
83
+ RealtimeErrorType[RealtimeErrorType["NonexistentSessionId"] = 4004] = "NonexistentSessionId";
84
+ RealtimeErrorType[RealtimeErrorType["SessionExpired"] = 4008] = "SessionExpired";
85
+ RealtimeErrorType[RealtimeErrorType["ClosedSession"] = 4010] = "ClosedSession";
86
+ RealtimeErrorType[RealtimeErrorType["RateLimited"] = 4029] = "RateLimited";
87
+ RealtimeErrorType[RealtimeErrorType["UniqueSessionViolation"] = 4030] = "UniqueSessionViolation";
88
+ RealtimeErrorType[RealtimeErrorType["SessionTimeout"] = 4031] = "SessionTimeout";
89
+ RealtimeErrorType[RealtimeErrorType["AudioTooShort"] = 4032] = "AudioTooShort";
90
+ RealtimeErrorType[RealtimeErrorType["AudioTooLong"] = 4033] = "AudioTooLong";
91
+ RealtimeErrorType[RealtimeErrorType["BadJson"] = 4100] = "BadJson";
92
+ RealtimeErrorType[RealtimeErrorType["BadSchema"] = 4101] = "BadSchema";
93
+ RealtimeErrorType[RealtimeErrorType["TooManyStreams"] = 4102] = "TooManyStreams";
94
+ RealtimeErrorType[RealtimeErrorType["Reconnected"] = 4103] = "Reconnected";
95
+ RealtimeErrorType[RealtimeErrorType["ReconnectAttemptsExhausted"] = 1013] = "ReconnectAttemptsExhausted";
96
+ })(RealtimeErrorType || (RealtimeErrorType = {}));
97
+ const RealtimeErrorMessages = {
98
+ [RealtimeErrorType.BadSampleRate]: "Sample rate must be a positive integer",
99
+ [RealtimeErrorType.AuthFailed]: "Not Authorized",
100
+ [RealtimeErrorType.InsufficientFunds]: "Insufficient funds",
101
+ [RealtimeErrorType.FreeAccount]: "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",
102
+ [RealtimeErrorType.NonexistentSessionId]: "Session ID does not exist",
103
+ [RealtimeErrorType.SessionExpired]: "Session has expired",
104
+ [RealtimeErrorType.ClosedSession]: "Session is closed",
105
+ [RealtimeErrorType.RateLimited]: "Rate limited",
106
+ [RealtimeErrorType.UniqueSessionViolation]: "Unique session violation",
107
+ [RealtimeErrorType.SessionTimeout]: "Session Timeout",
108
+ [RealtimeErrorType.AudioTooShort]: "Audio too short",
109
+ [RealtimeErrorType.AudioTooLong]: "Audio too long",
110
+ [RealtimeErrorType.BadJson]: "Bad JSON",
111
+ [RealtimeErrorType.BadSchema]: "Bad schema",
112
+ [RealtimeErrorType.TooManyStreams]: "Too many streams",
113
+ [RealtimeErrorType.Reconnected]: "Reconnected",
114
+ [RealtimeErrorType.ReconnectAttemptsExhausted]: "Reconnect attempts exhausted",
115
+ };
116
+ class RealtimeError extends Error {
117
+ constructor(code) {
118
+ const message = RealtimeErrorMessages[code];
119
+ super(message);
120
+ this.name = this.constructor.name;
121
+ this.code = code;
122
+ Error.captureStackTrace(this, this.constructor);
123
+ }
124
+ }
125
+
126
+ class RealtimeService {
127
+ constructor(params) {
128
+ this.listeners = {};
129
+ this.params = params;
130
+ }
131
+ connectionUrl(connectionParams) {
132
+ if (!this.params.baseUrl) {
133
+ throw new Error("Missing base URL");
134
+ }
135
+ const url = new URL(this.params.baseUrl);
136
+ if (url.protocol !== "wss:") {
137
+ throw new Error("Invalid protocol, must be wss");
138
+ }
139
+ const searchParams = new URLSearchParams();
140
+ searchParams.set("sample_rate", connectionParams.sampleRate.toString());
141
+ searchParams.set("word_boost", connectionParams.wordBoost.join(","));
142
+ url.search = searchParams.toString();
143
+ return url;
144
+ }
145
+ on(event, listener) {
146
+ this.listeners[event] = listener;
147
+ }
148
+ connect(connectionParams) {
149
+ if (this.socket) {
150
+ throw new Error("Already connected");
151
+ }
152
+ const url = this.connectionUrl(Object.assign(Object.assign({}, connectionParams), { sampleRate: connectionParams.sampleRate || 16000, wordBoost: connectionParams.wordBoost || [] }));
153
+ this.socket = new WebSocket(url.toString(), {
154
+ headers: {
155
+ Authorization: this.params.token,
156
+ },
157
+ });
158
+ this.socket.onopen = () => { var _a, _b; return (_b = (_a = this.listeners).open) === null || _b === void 0 ? void 0 : _b.call(_a); };
159
+ this.socket.onclose = ({ code, reason }) => { var _a, _b; return (_b = (_a = this.listeners).close) === null || _b === void 0 ? void 0 : _b.call(_a, code, reason); };
160
+ this.socket.onerror = (error) => {
161
+ var _a, _b;
162
+ const code = error.message;
163
+ const realtimeError = new RealtimeError(code);
164
+ (_b = (_a = this.listeners).error) === null || _b === void 0 ? void 0 : _b.call(_a, realtimeError);
165
+ };
166
+ this.socket.onmessage = ({ data }) => {
167
+ var _a, _b;
168
+ const message = JSON.parse(data.toString());
169
+ (_b = (_a = this.listeners).data) === null || _b === void 0 ? void 0 : _b.call(_a, message);
170
+ };
171
+ }
172
+ send(data) {
173
+ if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
174
+ throw new Error("Socket is not open for communication");
175
+ }
176
+ const payload = {
177
+ audio_data: Buffer.from(data).toString("base64"),
178
+ };
179
+ this.socket.send(JSON.stringify(payload));
180
+ }
181
+ disconnect() {
182
+ if (this.socket) {
183
+ this.socket.removeAllListeners();
184
+ this.socket.close();
185
+ }
186
+ this.listeners = {};
187
+ this.socket = undefined;
188
+ }
189
+ }
190
+
191
+ class TranscriptSubtitleService extends BaseService {
192
+ retrieve({ transcript_id, format, }) {
193
+ return __awaiter(this, void 0, void 0, function* () {
194
+ const { data } = yield this.client.get(`/v2/transcript/${transcript_id}/${format}`);
195
+ return data;
196
+ });
197
+ }
198
+ }
199
+
200
+ class TranscriptRedactionService extends BaseService {
201
+ retrieve(params) {
202
+ return __awaiter(this, void 0, void 0, function* () {
203
+ const { data } = yield this.client.get(`/v2/transcript/${params.transcript_id}/redacted-audio`);
204
+ return data;
205
+ });
206
+ }
207
+ }
208
+
209
+ class TranscriptService extends BaseService {
210
+ constructor(client, files) {
211
+ super(client);
212
+ this.files = files;
213
+ this.subtitles = new TranscriptSubtitleService(client);
214
+ this.redactions = new TranscriptRedactionService(client);
215
+ }
216
+ create(params, settings = {
217
+ pollingInterval: 3000,
218
+ pollingTimeout: 180000,
219
+ }) {
220
+ return __awaiter(this, void 0, void 0, function* () {
221
+ const path = getPath(params.audio_url);
222
+ if (path !== null) {
223
+ const uploadUrl = yield this.files.upload(path);
224
+ params.audio_url = uploadUrl;
225
+ }
226
+ const res = yield this.client.post("/v2/transcript", params);
227
+ if (settings && settings.pollingInterval) {
228
+ return yield this.poll(res.data.id, settings);
229
+ }
230
+ return res.data;
231
+ });
232
+ }
233
+ poll(transcriptId, settings) {
234
+ return __awaiter(this, void 0, void 0, function* () {
235
+ const { pollingInterval, pollingTimeout, resolver = (t) => t.status === "completed" || t.status === "error", } = settings;
236
+ const startTime = Date.now();
237
+ while (true) {
238
+ const transcript = yield this.retrieve(transcriptId);
239
+ if (resolver(transcript)) {
240
+ return transcript;
241
+ }
242
+ else if (Date.now() - startTime < pollingTimeout) {
243
+ yield new Promise((resolve) => setTimeout(resolve, pollingInterval));
244
+ }
245
+ else {
246
+ throw new Error("Polling timeout");
247
+ }
248
+ }
249
+ });
250
+ }
251
+ retrieve(id) {
252
+ return __awaiter(this, void 0, void 0, function* () {
253
+ const res = yield this.client.get(`/v2/transcript/${id}`);
254
+ return res.data;
255
+ });
256
+ }
257
+ list(nextUrl) {
258
+ return __awaiter(this, void 0, void 0, function* () {
259
+ const { data } = yield this.client.get(nextUrl || "/v2/transcript");
260
+ for (const transcriptListItem of data.transcripts) {
261
+ transcriptListItem.created = new Date(transcriptListItem.created);
262
+ transcriptListItem.completed = new Date(transcriptListItem.completed);
263
+ }
264
+ return data;
265
+ });
266
+ }
267
+ delete(id) {
268
+ return __awaiter(this, void 0, void 0, function* () {
269
+ const res = yield this.client.delete(`/v2/transcript/${id}`);
270
+ return res.data;
271
+ });
272
+ }
273
+ /**
274
+ * Retrieve all segments of a transcript.
275
+ * @param id The identifier of the transcript.
276
+ * @param type The type of segment to retrieve.
277
+ * @return A promise that resolves to the retrieved resource.
278
+ */
279
+ segments(id, type) {
280
+ return __awaiter(this, void 0, void 0, function* () {
281
+ const { data } = yield this.client.get(`/v2/transcript/${id}/${type}`);
282
+ return data;
283
+ });
284
+ }
285
+ /**
286
+ * Retrieve all sentences of a transcript.
287
+ * @param id The identifier of the transcript.
288
+ * @return A promise that resolves to the sentences.
289
+ */
290
+ sentences(id) {
291
+ return __awaiter(this, void 0, void 0, function* () {
292
+ return this.segments(id, "sentences");
293
+ });
294
+ }
295
+ /**
296
+ * Retrieve all paragraphs of a transcript.
297
+ * @param id The identifier of the transcript.
298
+ * @return A promise that resolves to the paragraphs.
299
+ */
300
+ paragraphs(id) {
301
+ return __awaiter(this, void 0, void 0, function* () {
302
+ return this.segments(id, "paragraphs");
303
+ });
304
+ }
305
+ }
306
+ function getPath(path) {
307
+ let url;
308
+ try {
309
+ url = new URL(path);
310
+ if (url.protocol === "file:")
311
+ return url.pathname;
312
+ else
313
+ return null;
314
+ }
315
+ catch (_a) {
316
+ return path;
317
+ }
318
+ }
319
+
320
+ class FileService extends BaseService {
321
+ /**
322
+ * Upload a local file to AssemblyAI.
323
+ * @param path The local file to upload.
324
+ * @return A promise that resolves to the uploaded file URL.
325
+ */
326
+ upload(path) {
327
+ return __awaiter(this, void 0, void 0, function* () {
328
+ const file = yield fs.readFile(path);
329
+ const { data } = yield this.client.post("/v2/upload", file, {
330
+ headers: {
331
+ "Content-Type": "application/octet-stream",
332
+ },
333
+ });
334
+ return data.upload_url;
335
+ });
336
+ }
337
+ }
338
+
339
+ class AssemblyAI {
340
+ /**
341
+ * Create a new AssemblyAI client.
342
+ * @param params The parameters for the service, including the API token and base URL, if any.
343
+ */
344
+ constructor(params) {
345
+ params.baseUrl = params.baseUrl || "https://api.assemblyai.com";
346
+ const client = this.createClient(params);
347
+ this.files = new FileService(client);
348
+ this.transcripts = new TranscriptService(client, this.files);
349
+ this.lemur = new LeMURService(client);
350
+ this.realtime = ({ baseUrl } = { baseUrl: "" }) => {
351
+ if (!baseUrl) {
352
+ const url = new URL(params.baseUrl);
353
+ url.protocol = "wss:";
354
+ baseUrl = url.toString();
355
+ }
356
+ return new RealtimeService({
357
+ token: params.token,
358
+ baseUrl,
359
+ });
360
+ };
361
+ }
362
+ createClient(params) {
363
+ const client = axios.create({
364
+ baseURL: params.baseUrl,
365
+ headers: { Authorization: params.token },
366
+ });
367
+ client.interceptors.response.use(null, (error) => {
368
+ var _a, _b;
369
+ if (isAxiosError(error) && ((_b = (_a = error.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.error)) {
370
+ return Promise.reject(new Error(error.response.data.error));
371
+ }
372
+ return Promise.reject(error);
373
+ });
374
+ return client;
375
+ }
376
+ }
377
+
378
+ export { AssemblyAI as default };