assemblyai 4.5.0 → 4.6.1
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 +12 -0
- package/dist/assemblyai.streaming.umd.js +29 -0
- package/dist/assemblyai.umd.js +30 -11
- package/dist/assemblyai.umd.min.js +1 -1
- package/dist/browser.mjs +30 -11
- package/dist/bun.mjs +30 -11
- package/dist/deno.mjs +30 -11
- package/dist/index.cjs +30 -11
- package/dist/index.mjs +30 -11
- package/dist/node.cjs +30 -11
- package/dist/node.mjs +30 -11
- package/dist/services/realtime/service.d.ts +60 -0
- package/dist/streaming.browser.mjs +29 -0
- package/dist/streaming.cjs +29 -0
- package/dist/streaming.mjs +29 -0
- package/dist/types/openapi.generated.d.ts +41 -28
- package/dist/workerd.mjs +30 -11
- package/package.json +27 -15
- package/src/services/realtime/service.ts +65 -0
- package/src/services/transcripts/index.ts +0 -13
- package/src/types/openapi.generated.ts +53 -33
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [4.6.1]
|
|
4
|
+
|
|
5
|
+
- Remove `conformer-2` from `SpeechModel` union type.
|
|
6
|
+
- Remove conformer-2 deprecation warning
|
|
7
|
+
|
|
8
|
+
## [4.6.0]
|
|
9
|
+
|
|
10
|
+
- Add more TSDoc comments for `RealtimeService` documentation
|
|
11
|
+
- Add new LeMUR models
|
|
12
|
+
- Add `TranscriptWebhookNotification` which is a union of `TranscriptReadyNotification` or `RedactedAudioNotification`
|
|
13
|
+
- Add `RedactedAudioNotification` which represents the body of the PII redacted audio webhook notification.
|
|
14
|
+
|
|
3
15
|
## [4.5.0]
|
|
4
16
|
|
|
5
17
|
- You can now retrieve previous LeMUR responses using `client.lemur.getResponse<LemurTask>("YOUR_REQUEST_ID")`.
|
|
@@ -95,7 +95,14 @@
|
|
|
95
95
|
const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
|
|
96
96
|
const forceEndOfUtteranceMessage = `{"force_end_utterance":true}`;
|
|
97
97
|
const terminateSessionMessage = `{"terminate_session":true}`;
|
|
98
|
+
/**
|
|
99
|
+
* RealtimeTranscriber connects to the Streaming Speech-to-Text API and lets you transcribe audio in real-time.
|
|
100
|
+
*/
|
|
98
101
|
class RealtimeTranscriber {
|
|
102
|
+
/**
|
|
103
|
+
* Create a new RealtimeTranscriber.
|
|
104
|
+
* @param params - Parameters to configure the RealtimeTranscriber
|
|
105
|
+
*/
|
|
99
106
|
constructor(params) {
|
|
100
107
|
var _a, _b;
|
|
101
108
|
this.listeners = {};
|
|
@@ -136,10 +143,19 @@
|
|
|
136
143
|
url.search = searchParams.toString();
|
|
137
144
|
return url;
|
|
138
145
|
}
|
|
146
|
+
/**
|
|
147
|
+
* Add a listener for an event.
|
|
148
|
+
* @param event - The event to listen for.
|
|
149
|
+
* @param listener - The function to call when the event is emitted.
|
|
150
|
+
*/
|
|
139
151
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
140
152
|
on(event, listener) {
|
|
141
153
|
this.listeners[event] = listener;
|
|
142
154
|
}
|
|
155
|
+
/**
|
|
156
|
+
* Connect to the server and begin a new session.
|
|
157
|
+
* @returns A promise that resolves when the connection is established and the session begins.
|
|
158
|
+
*/
|
|
143
159
|
connect() {
|
|
144
160
|
return new Promise((resolve) => {
|
|
145
161
|
if (this.socket) {
|
|
@@ -221,9 +237,17 @@
|
|
|
221
237
|
};
|
|
222
238
|
});
|
|
223
239
|
}
|
|
240
|
+
/**
|
|
241
|
+
* Send audio data to the server.
|
|
242
|
+
* @param audio - The audio data to send to the server.
|
|
243
|
+
*/
|
|
224
244
|
sendAudio(audio) {
|
|
225
245
|
this.send(audio);
|
|
226
246
|
}
|
|
247
|
+
/**
|
|
248
|
+
* Create a writable stream that can be used to send audio data to the server.
|
|
249
|
+
* @returns A writable stream that can be used to send audio data to the server.
|
|
250
|
+
*/
|
|
227
251
|
stream() {
|
|
228
252
|
return new WritableStream({
|
|
229
253
|
write: (chunk) => {
|
|
@@ -251,6 +275,11 @@
|
|
|
251
275
|
}
|
|
252
276
|
this.socket.send(data);
|
|
253
277
|
}
|
|
278
|
+
/**
|
|
279
|
+
* Close the connection to the server.
|
|
280
|
+
* @param waitForSessionTermination - If true, the method will wait for the session to be terminated before closing the connection.
|
|
281
|
+
* While waiting for the session to be terminated, you will receive the final transcript and session information.
|
|
282
|
+
*/
|
|
254
283
|
close() {
|
|
255
284
|
return __awaiter(this, arguments, void 0, function* (waitForSessionTermination = true) {
|
|
256
285
|
var _a;
|
package/dist/assemblyai.umd.js
CHANGED
|
@@ -65,7 +65,7 @@
|
|
|
65
65
|
defaultUserAgentString += navigator.userAgent;
|
|
66
66
|
}
|
|
67
67
|
const defaultUserAgent = {
|
|
68
|
-
sdk: { name: "JavaScript", version: "4.
|
|
68
|
+
sdk: { name: "JavaScript", version: "4.6.1" },
|
|
69
69
|
};
|
|
70
70
|
if (typeof process !== "undefined") {
|
|
71
71
|
if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
|
|
@@ -252,7 +252,14 @@
|
|
|
252
252
|
const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
|
|
253
253
|
const forceEndOfUtteranceMessage = `{"force_end_utterance":true}`;
|
|
254
254
|
const terminateSessionMessage = `{"terminate_session":true}`;
|
|
255
|
+
/**
|
|
256
|
+
* RealtimeTranscriber connects to the Streaming Speech-to-Text API and lets you transcribe audio in real-time.
|
|
257
|
+
*/
|
|
255
258
|
class RealtimeTranscriber {
|
|
259
|
+
/**
|
|
260
|
+
* Create a new RealtimeTranscriber.
|
|
261
|
+
* @param params - Parameters to configure the RealtimeTranscriber
|
|
262
|
+
*/
|
|
256
263
|
constructor(params) {
|
|
257
264
|
var _a, _b;
|
|
258
265
|
this.listeners = {};
|
|
@@ -293,10 +300,19 @@
|
|
|
293
300
|
url.search = searchParams.toString();
|
|
294
301
|
return url;
|
|
295
302
|
}
|
|
303
|
+
/**
|
|
304
|
+
* Add a listener for an event.
|
|
305
|
+
* @param event - The event to listen for.
|
|
306
|
+
* @param listener - The function to call when the event is emitted.
|
|
307
|
+
*/
|
|
296
308
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
297
309
|
on(event, listener) {
|
|
298
310
|
this.listeners[event] = listener;
|
|
299
311
|
}
|
|
312
|
+
/**
|
|
313
|
+
* Connect to the server and begin a new session.
|
|
314
|
+
* @returns A promise that resolves when the connection is established and the session begins.
|
|
315
|
+
*/
|
|
300
316
|
connect() {
|
|
301
317
|
return new Promise((resolve) => {
|
|
302
318
|
if (this.socket) {
|
|
@@ -378,9 +394,17 @@
|
|
|
378
394
|
};
|
|
379
395
|
});
|
|
380
396
|
}
|
|
397
|
+
/**
|
|
398
|
+
* Send audio data to the server.
|
|
399
|
+
* @param audio - The audio data to send to the server.
|
|
400
|
+
*/
|
|
381
401
|
sendAudio(audio) {
|
|
382
402
|
this.send(audio);
|
|
383
403
|
}
|
|
404
|
+
/**
|
|
405
|
+
* Create a writable stream that can be used to send audio data to the server.
|
|
406
|
+
* @returns A writable stream that can be used to send audio data to the server.
|
|
407
|
+
*/
|
|
384
408
|
stream() {
|
|
385
409
|
return new WritableStream({
|
|
386
410
|
write: (chunk) => {
|
|
@@ -408,6 +432,11 @@
|
|
|
408
432
|
}
|
|
409
433
|
this.socket.send(data);
|
|
410
434
|
}
|
|
435
|
+
/**
|
|
436
|
+
* Close the connection to the server.
|
|
437
|
+
* @param waitForSessionTermination - If true, the method will wait for the session to be terminated before closing the connection.
|
|
438
|
+
* While waiting for the session to be terminated, you will receive the final transcript and session information.
|
|
439
|
+
*/
|
|
411
440
|
close() {
|
|
412
441
|
return __awaiter(this, arguments, void 0, function* (waitForSessionTermination = true) {
|
|
413
442
|
var _a;
|
|
@@ -500,7 +529,6 @@
|
|
|
500
529
|
*/
|
|
501
530
|
transcribe(params, options) {
|
|
502
531
|
return __awaiter(this, void 0, void 0, function* () {
|
|
503
|
-
deprecateConformer2(params);
|
|
504
532
|
const transcript = yield this.submit(params);
|
|
505
533
|
return yield this.waitUntilReady(transcript.id, options);
|
|
506
534
|
});
|
|
@@ -512,7 +540,6 @@
|
|
|
512
540
|
*/
|
|
513
541
|
submit(params) {
|
|
514
542
|
return __awaiter(this, void 0, void 0, function* () {
|
|
515
|
-
deprecateConformer2(params);
|
|
516
543
|
let audioUrl;
|
|
517
544
|
let transcriptParams = undefined;
|
|
518
545
|
if ("audio" in params) {
|
|
@@ -559,7 +586,6 @@
|
|
|
559
586
|
create(params, options) {
|
|
560
587
|
return __awaiter(this, void 0, void 0, function* () {
|
|
561
588
|
var _a;
|
|
562
|
-
deprecateConformer2(params);
|
|
563
589
|
const path = getPath(params.audio_url);
|
|
564
590
|
if (path !== null) {
|
|
565
591
|
const uploadUrl = yield this.files.upload(path);
|
|
@@ -735,13 +761,6 @@
|
|
|
735
761
|
});
|
|
736
762
|
}
|
|
737
763
|
}
|
|
738
|
-
function deprecateConformer2(params) {
|
|
739
|
-
if (!params)
|
|
740
|
-
return;
|
|
741
|
-
if (params.speech_model === "conformer-2") {
|
|
742
|
-
console.warn("The speech_model conformer-2 option is deprecated and will stop working in the near future. Use best or nano instead.");
|
|
743
|
-
}
|
|
744
|
-
}
|
|
745
764
|
|
|
746
765
|
const readFile = function (
|
|
747
766
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).assemblyai={})}(this,(function(e){"use strict";function t(e,t,s,i){return new(s||(s=Promise))((function(n,o){function r(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}c((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const s={cache:"no-store"};let i="";"undefined"!=typeof navigator&&navigator.userAgent&&(i+=navigator.userAgent);const n={sdk:{name:"JavaScript",version:"4.5.0"}};"undefined"!=typeof process&&(process.versions.node&&-1===i.indexOf("Node")&&(n.runtime_env={name:"Node",version:process.versions.node}),process.versions.bun&&-1===i.indexOf("Bun")&&(n.runtime_env={name:"Bun",version:process.versions.bun})),"undefined"!=typeof Deno&&process.versions.bun&&-1===i.indexOf("Deno")&&(n.runtime_env={name:"Deno",version:Deno.version.deno});class o{constructor(e){var t;this.params=e,!1===e.userAgent?this.userAgent=void 0:this.userAgent=(t=e.userAgent||{},i+(!1===t?"":" AssemblyAI/1.0 ("+Object.entries(Object.assign(Object.assign({},n),t)).map((([e,t])=>t?`${e}=${t.name}/${t.version}`:"")).join(" ")+")"))}fetch(e,i){return t(this,void 0,void 0,(function*(){i=Object.assign(Object.assign({},s),i);let t={Authorization:this.params.apiKey,"Content-Type":"application/json"};(null==s?void 0:s.headers)&&(t=Object.assign(Object.assign({},t),s.headers)),(null==i?void 0:i.headers)&&(t=Object.assign(Object.assign({},t),i.headers)),this.userAgent&&(t["User-Agent"]=this.userAgent,"undefined"!=typeof window&&"chrome"in window&&(t["AssemblyAI-Agent"]=this.userAgent)),i.headers=t,e.startsWith("http")||(e=this.params.baseUrl+e);const n=yield fetch(e,i);if(n.status>=400){let e;const t=yield n.text();if(t){try{e=JSON.parse(t)}catch(e){}if(null==e?void 0:e.error)throw new Error(e.error);throw new Error(t)}throw new Error(`HTTP Error: ${n.status} ${n.statusText}`)}return n}))}fetchJson(e,s){return t(this,void 0,void 0,(function*(){return(yield this.fetch(e,s)).json()}))}}class r extends o{summary(e){return this.fetchJson("/lemur/v3/generate/summary",{method:"POST",body:JSON.stringify(e)})}questionAnswer(e){return this.fetchJson("/lemur/v3/generate/question-answer",{method:"POST",body:JSON.stringify(e)})}actionItems(e){return this.fetchJson("/lemur/v3/generate/action-items",{method:"POST",body:JSON.stringify(e)})}task(e){return this.fetchJson("/lemur/v3/generate/task",{method:"POST",body:JSON.stringify(e)})}getResponse(e){return this.fetchJson(`/lemur/v3/${e}`)}purgeRequestData(e){return this.fetchJson(`/lemur/v3/${e}`,{method:"DELETE"})}}const{WritableStream:a}="undefined"!=typeof window?window:"undefined"!=typeof global?global:globalThis;var c,d;const l=null!==(d=null!==(c=null!==WebSocket&&void 0!==WebSocket?WebSocket:null===global||void 0===global?void 0:global.WebSocket)&&void 0!==c?c:null===window||void 0===window?void 0:window.WebSocket)&&void 0!==d?d:null===self||void 0===self?void 0:self.WebSocket,u=(e,t)=>t?new l(e,t):new l(e);var h;!function(e){e[e.BadSampleRate=4e3]="BadSampleRate",e[e.AuthFailed=4001]="AuthFailed",e[e.InsufficientFundsOrFreeAccount=4002]="InsufficientFundsOrFreeAccount",e[e.NonexistentSessionId=4004]="NonexistentSessionId",e[e.SessionExpired=4008]="SessionExpired",e[e.ClosedSession=4010]="ClosedSession",e[e.RateLimited=4029]="RateLimited",e[e.UniqueSessionViolation=4030]="UniqueSessionViolation",e[e.SessionTimeout=4031]="SessionTimeout",e[e.AudioTooShort=4032]="AudioTooShort",e[e.AudioTooLong=4033]="AudioTooLong",e[e.BadJson=4100]="BadJson",e[e.BadSchema=4101]="BadSchema",e[e.TooManyStreams=4102]="TooManyStreams",e[e.Reconnected=4103]="Reconnected",e[e.ReconnectAttemptsExhausted=1013]="ReconnectAttemptsExhausted"}(h||(h={}));const f={[h.BadSampleRate]:"Sample rate must be a positive integer",[h.AuthFailed]:"Not Authorized",[h.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.",[h.NonexistentSessionId]:"Session ID does not exist",[h.SessionExpired]:"Session has expired",[h.ClosedSession]:"Session is closed",[h.RateLimited]:"Rate limited",[h.UniqueSessionViolation]:"Unique session violation",[h.SessionTimeout]:"Session Timeout",[h.AudioTooShort]:"Audio too short",[h.AudioTooLong]:"Audio too long",[h.BadJson]:"Bad JSON",[h.BadSchema]:"Bad schema",[h.TooManyStreams]:"Too many streams",[h.Reconnected]:"Reconnected",[h.ReconnectAttemptsExhausted]:"Reconnect attempts exhausted"};class p extends Error{}const m='{"terminate_session":true}';class v{constructor(e){var t,s;if(this.listeners={},this.realtimeUrl=null!==(t=e.realtimeUrl)&&void 0!==t?t:"wss://api.assemblyai.com/v2/realtime/ws",this.sampleRate=null!==(s=e.sampleRate)&&void 0!==s?s:16e3,this.wordBoost=e.wordBoost,this.encoding=e.encoding,this.endUtteranceSilenceThreshold=e.endUtteranceSilenceThreshold,this.disablePartialTranscripts=e.disablePartialTranscripts,"token"in e&&e.token&&(this.token=e.token),"apiKey"in e&&e.apiKey&&(this.apiKey=e.apiKey),!this.token&&!this.apiKey)throw new Error("API key or temporary token is required.")}connectionUrl(){const e=new URL(this.realtimeUrl);if("wss:"!==e.protocol)throw new Error("Invalid protocol, must be wss");const t=new URLSearchParams;return this.token&&t.set("token",this.token),t.set("sample_rate",this.sampleRate.toString()),this.wordBoost&&this.wordBoost.length>0&&t.set("word_boost",JSON.stringify(this.wordBoost)),this.encoding&&t.set("encoding",this.encoding),t.set("enable_extra_session_information","true"),this.disablePartialTranscripts&&t.set("disable_partial_transcripts",this.disablePartialTranscripts.toString()),e.search=t.toString(),e}on(e,t){this.listeners[e]=t}connect(){return new Promise((e=>{if(this.socket)throw new Error("Already connected");const t=this.connectionUrl();this.token?this.socket=u(t.toString()):this.socket=u(t.toString(),{headers:{Authorization:this.apiKey}}),this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{void 0!==this.endUtteranceSilenceThreshold&&null!==this.endUtteranceSilenceThreshold&&this.configureEndUtteranceSilenceThreshold(this.endUtteranceSilenceThreshold)},this.socket.onclose=({code:e,reason:t})=>{var s,i;t||e in h&&(t=f[e]),null===(i=(s=this.listeners).close)||void 0===i||i.call(s,e,t)},this.socket.onerror=e=>{var t,s,i,n;e.error?null===(s=(t=this.listeners).error)||void 0===s||s.call(t,e.error):null===(n=(i=this.listeners).error)||void 0===n||n.call(i,new Error(e.message))},this.socket.onmessage=({data:t})=>{var s,i,n,o,r,a,c,d,l,u,h,f,m,v,y;const b=JSON.parse(t.toString());if("error"in b)null===(i=(s=this.listeners).error)||void 0===i||i.call(s,new p(b.error));else switch(b.message_type){case"SessionBegins":{const t={sessionId:b.session_id,expiresAt:new Date(b.expires_at)};e(t),null===(o=(n=this.listeners).open)||void 0===o||o.call(n,t);break}case"PartialTranscript":b.created=new Date(b.created),null===(a=(r=this.listeners).transcript)||void 0===a||a.call(r,b),null===(d=(c=this.listeners)["transcript.partial"])||void 0===d||d.call(c,b);break;case"FinalTranscript":b.created=new Date(b.created),null===(u=(l=this.listeners).transcript)||void 0===u||u.call(l,b),null===(f=(h=this.listeners)["transcript.final"])||void 0===f||f.call(h,b);break;case"SessionInformation":null===(v=(m=this.listeners).session_information)||void 0===v||v.call(m,b);break;case"SessionTerminated":null===(y=this.sessionTerminatedResolve)||void 0===y||y.call(this)}}}))}sendAudio(e){this.send(e)}stream(){return new a({write:e=>{this.sendAudio(e)}})}forceEndUtterance(){this.send('{"force_end_utterance":true}')}configureEndUtteranceSilenceThreshold(e){this.send(`{"end_utterance_silence_threshold":${e}}`)}send(e){if(!this.socket||this.socket.readyState!==this.socket.OPEN)throw new Error("Socket is not open for communication");this.socket.send(e)}close(){return t(this,arguments,void 0,(function*(e=!0){var t;if(this.socket){if(this.socket.readyState===this.socket.OPEN)if(e){const e=new Promise((e=>{this.sessionTerminatedResolve=e}));this.socket.send(m),yield e}else this.socket.send(m);(null===(t=this.socket)||void 0===t?void 0:t.removeAllListeners)&&this.socket.removeAllListeners(),this.socket.close()}this.listeners={},this.socket=void 0}))}}class y extends o{constructor(e){super(e),this.rtFactoryParams=e}createService(e){return this.transcriber(e)}transcriber(e){const t=Object.assign({},e);return t.token||t.apiKey||(t.apiKey=this.rtFactoryParams.apiKey),new v(t)}createTemporaryToken(e){return t(this,void 0,void 0,(function*(){return(yield this.fetchJson("/v2/realtime/token",{method:"POST",body:JSON.stringify(e)})).token}))}}function b(e){return e.startsWith("http")||e.startsWith("https")||e.startsWith("data:")?null:e.startsWith("file://")?e.substring(7):e.startsWith("file:")?e.substring(5):e}class S extends o{constructor(e,t){super(e),this.files=t}transcribe(e,s){return t(this,void 0,void 0,(function*(){g(e);const t=yield this.submit(e);return yield this.waitUntilReady(t.id,s)}))}submit(e){return t(this,void 0,void 0,(function*(){let t,s;if(g(e),"audio"in e){const{audio:i}=e,n=function(e,t){var s={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(s[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(s[i[n]]=e[i[n]])}return s}(e,["audio"]);if("string"==typeof i){const e=b(i);t=null!==e?yield this.files.upload(e):i.startsWith("data:")?yield this.files.upload(i):i}else t=yield this.files.upload(i);s=Object.assign(Object.assign({},n),{audio_url:t})}else s=e;return yield this.fetchJson("/v2/transcript",{method:"POST",body:JSON.stringify(s)})}))}create(e,s){return t(this,void 0,void 0,(function*(){var t;g(e);const i=b(e.audio_url);if(null!==i){const t=yield this.files.upload(i);e.audio_url=t}const n=yield this.fetchJson("/v2/transcript",{method:"POST",body:JSON.stringify(e)});return null===(t=null==s?void 0:s.poll)||void 0===t||t?yield this.waitUntilReady(n.id,s):n}))}waitUntilReady(e,s){return t(this,void 0,void 0,(function*(){var t,i;const n=null!==(t=null==s?void 0:s.pollingInterval)&&void 0!==t?t:3e3,o=null!==(i=null==s?void 0:s.pollingTimeout)&&void 0!==i?i:-1,r=Date.now();for(;;){const t=yield this.get(e);if("completed"===t.status||"error"===t.status)return t;if(o>0&&Date.now()-r>o)throw new Error("Polling timeout");yield new Promise((e=>setTimeout(e,n)))}}))}get(e){return this.fetchJson(`/v2/transcript/${e}`)}list(e){return t(this,void 0,void 0,(function*(){let t="/v2/transcript";"string"==typeof e?t=e:e&&(t=`${t}?${new URLSearchParams(Object.keys(e).map((t=>{var s;return[t,(null===(s=e[t])||void 0===s?void 0:s.toString())||""]})))}`);const s=yield this.fetchJson(t);for(const e of s.transcripts)e.created=new Date(e.created),e.completed&&(e.completed=new Date(e.completed));return s}))}delete(e){return this.fetchJson(`/v2/transcript/${e}`,{method:"DELETE"})}wordSearch(e,t){const s=new URLSearchParams({words:t.join(",")});return this.fetchJson(`/v2/transcript/${e}/word-search?${s.toString()}`)}sentences(e){return this.fetchJson(`/v2/transcript/${e}/sentences`)}paragraphs(e){return this.fetchJson(`/v2/transcript/${e}/paragraphs`)}subtitles(e){return t(this,arguments,void 0,(function*(e,t="srt",s){let i=`/v2/transcript/${e}/${t}`;if(s){const e=new URLSearchParams;e.set("chars_per_caption",s.toString()),i+=`?${e.toString()}`}const n=yield this.fetch(i);return yield n.text()}))}redactions(e){return this.redactedAudio(e)}redactedAudio(e){return this.fetchJson(`/v2/transcript/${e}/redacted-audio`)}redactedAudioFile(e){return t(this,void 0,void 0,(function*(){const{redacted_audio_url:t,status:s}=yield this.redactedAudio(e);if("redacted_audio_ready"!==s)throw new Error(`Redacted audio status is ${s}`);const i=yield fetch(t);if(!i.ok)throw new Error(`Failed to fetch redacted audio: ${i.statusText}`);return{arrayBuffer:i.arrayBuffer.bind(i),blob:i.blob.bind(i),body:i.body,bodyUsed:i.bodyUsed}}))}}function g(e){e&&"conformer-2"===e.speech_model&&console.warn("The speech_model conformer-2 option is deprecated and will stop working in the near future. Use best or nano instead.")}class w extends o{upload(e){return t(this,void 0,void 0,(function*(){let s;s="string"==typeof e?e.startsWith("data:")?function(e){const t=e.split(","),s=t[0].match(/:(.*?);/)[1],i=atob(t[1]);let n=i.length;const o=new Uint8Array(n);for(;n--;)o[n]=i.charCodeAt(n);return new Blob([o],{type:s})}(e):yield function(e){return t(this,void 0,void 0,(function*(){throw new Error("Interacting with the file system is not supported in this environment.")}))}():e;return(yield this.fetchJson("/v2/upload",{method:"POST",body:s,headers:{"Content-Type":"application/octet-stream"},duplex:"half"})).upload_url}))}}e.AssemblyAI=class{constructor(e){e.baseUrl=e.baseUrl||"https://api.assemblyai.com",e.baseUrl&&e.baseUrl.endsWith("/")&&(e.baseUrl=e.baseUrl.slice(0,-1)),this.files=new w(e),this.transcripts=new S(e,this.files),this.lemur=new r(e),this.realtime=new y(e)}},e.FileService=w,e.LemurService=r,e.RealtimeService=class extends v{},e.RealtimeServiceFactory=class extends y{},e.RealtimeTranscriber=v,e.RealtimeTranscriberFactory=y,e.TranscriptService=S}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).assemblyai={})}(this,(function(e){"use strict";function t(e,t,s,i){return new(s||(s=Promise))((function(n,o){function r(e){try{d(i.next(e))}catch(e){o(e)}}function a(e){try{d(i.throw(e))}catch(e){o(e)}}function d(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}d((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const s={cache:"no-store"};let i="";"undefined"!=typeof navigator&&navigator.userAgent&&(i+=navigator.userAgent);const n={sdk:{name:"JavaScript",version:"4.6.1"}};"undefined"!=typeof process&&(process.versions.node&&-1===i.indexOf("Node")&&(n.runtime_env={name:"Node",version:process.versions.node}),process.versions.bun&&-1===i.indexOf("Bun")&&(n.runtime_env={name:"Bun",version:process.versions.bun})),"undefined"!=typeof Deno&&process.versions.bun&&-1===i.indexOf("Deno")&&(n.runtime_env={name:"Deno",version:Deno.version.deno});class o{constructor(e){var t;this.params=e,!1===e.userAgent?this.userAgent=void 0:this.userAgent=(t=e.userAgent||{},i+(!1===t?"":" AssemblyAI/1.0 ("+Object.entries(Object.assign(Object.assign({},n),t)).map((([e,t])=>t?`${e}=${t.name}/${t.version}`:"")).join(" ")+")"))}fetch(e,i){return t(this,void 0,void 0,(function*(){i=Object.assign(Object.assign({},s),i);let t={Authorization:this.params.apiKey,"Content-Type":"application/json"};(null==s?void 0:s.headers)&&(t=Object.assign(Object.assign({},t),s.headers)),(null==i?void 0:i.headers)&&(t=Object.assign(Object.assign({},t),i.headers)),this.userAgent&&(t["User-Agent"]=this.userAgent,"undefined"!=typeof window&&"chrome"in window&&(t["AssemblyAI-Agent"]=this.userAgent)),i.headers=t,e.startsWith("http")||(e=this.params.baseUrl+e);const n=yield fetch(e,i);if(n.status>=400){let e;const t=yield n.text();if(t){try{e=JSON.parse(t)}catch(e){}if(null==e?void 0:e.error)throw new Error(e.error);throw new Error(t)}throw new Error(`HTTP Error: ${n.status} ${n.statusText}`)}return n}))}fetchJson(e,s){return t(this,void 0,void 0,(function*(){return(yield this.fetch(e,s)).json()}))}}class r extends o{summary(e){return this.fetchJson("/lemur/v3/generate/summary",{method:"POST",body:JSON.stringify(e)})}questionAnswer(e){return this.fetchJson("/lemur/v3/generate/question-answer",{method:"POST",body:JSON.stringify(e)})}actionItems(e){return this.fetchJson("/lemur/v3/generate/action-items",{method:"POST",body:JSON.stringify(e)})}task(e){return this.fetchJson("/lemur/v3/generate/task",{method:"POST",body:JSON.stringify(e)})}getResponse(e){return this.fetchJson(`/lemur/v3/${e}`)}purgeRequestData(e){return this.fetchJson(`/lemur/v3/${e}`,{method:"DELETE"})}}const{WritableStream:a}="undefined"!=typeof window?window:"undefined"!=typeof global?global:globalThis;var d,c;const l=null!==(c=null!==(d=null!==WebSocket&&void 0!==WebSocket?WebSocket:null===global||void 0===global?void 0:global.WebSocket)&&void 0!==d?d:null===window||void 0===window?void 0:window.WebSocket)&&void 0!==c?c:null===self||void 0===self?void 0:self.WebSocket,u=(e,t)=>t?new l(e,t):new l(e);var h;!function(e){e[e.BadSampleRate=4e3]="BadSampleRate",e[e.AuthFailed=4001]="AuthFailed",e[e.InsufficientFundsOrFreeAccount=4002]="InsufficientFundsOrFreeAccount",e[e.NonexistentSessionId=4004]="NonexistentSessionId",e[e.SessionExpired=4008]="SessionExpired",e[e.ClosedSession=4010]="ClosedSession",e[e.RateLimited=4029]="RateLimited",e[e.UniqueSessionViolation=4030]="UniqueSessionViolation",e[e.SessionTimeout=4031]="SessionTimeout",e[e.AudioTooShort=4032]="AudioTooShort",e[e.AudioTooLong=4033]="AudioTooLong",e[e.BadJson=4100]="BadJson",e[e.BadSchema=4101]="BadSchema",e[e.TooManyStreams=4102]="TooManyStreams",e[e.Reconnected=4103]="Reconnected",e[e.ReconnectAttemptsExhausted=1013]="ReconnectAttemptsExhausted"}(h||(h={}));const f={[h.BadSampleRate]:"Sample rate must be a positive integer",[h.AuthFailed]:"Not Authorized",[h.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.",[h.NonexistentSessionId]:"Session ID does not exist",[h.SessionExpired]:"Session has expired",[h.ClosedSession]:"Session is closed",[h.RateLimited]:"Rate limited",[h.UniqueSessionViolation]:"Unique session violation",[h.SessionTimeout]:"Session Timeout",[h.AudioTooShort]:"Audio too short",[h.AudioTooLong]:"Audio too long",[h.BadJson]:"Bad JSON",[h.BadSchema]:"Bad schema",[h.TooManyStreams]:"Too many streams",[h.Reconnected]:"Reconnected",[h.ReconnectAttemptsExhausted]:"Reconnect attempts exhausted"};class p extends Error{}const m='{"terminate_session":true}';class v{constructor(e){var t,s;if(this.listeners={},this.realtimeUrl=null!==(t=e.realtimeUrl)&&void 0!==t?t:"wss://api.assemblyai.com/v2/realtime/ws",this.sampleRate=null!==(s=e.sampleRate)&&void 0!==s?s:16e3,this.wordBoost=e.wordBoost,this.encoding=e.encoding,this.endUtteranceSilenceThreshold=e.endUtteranceSilenceThreshold,this.disablePartialTranscripts=e.disablePartialTranscripts,"token"in e&&e.token&&(this.token=e.token),"apiKey"in e&&e.apiKey&&(this.apiKey=e.apiKey),!this.token&&!this.apiKey)throw new Error("API key or temporary token is required.")}connectionUrl(){const e=new URL(this.realtimeUrl);if("wss:"!==e.protocol)throw new Error("Invalid protocol, must be wss");const t=new URLSearchParams;return this.token&&t.set("token",this.token),t.set("sample_rate",this.sampleRate.toString()),this.wordBoost&&this.wordBoost.length>0&&t.set("word_boost",JSON.stringify(this.wordBoost)),this.encoding&&t.set("encoding",this.encoding),t.set("enable_extra_session_information","true"),this.disablePartialTranscripts&&t.set("disable_partial_transcripts",this.disablePartialTranscripts.toString()),e.search=t.toString(),e}on(e,t){this.listeners[e]=t}connect(){return new Promise((e=>{if(this.socket)throw new Error("Already connected");const t=this.connectionUrl();this.token?this.socket=u(t.toString()):this.socket=u(t.toString(),{headers:{Authorization:this.apiKey}}),this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{void 0!==this.endUtteranceSilenceThreshold&&null!==this.endUtteranceSilenceThreshold&&this.configureEndUtteranceSilenceThreshold(this.endUtteranceSilenceThreshold)},this.socket.onclose=({code:e,reason:t})=>{var s,i;t||e in h&&(t=f[e]),null===(i=(s=this.listeners).close)||void 0===i||i.call(s,e,t)},this.socket.onerror=e=>{var t,s,i,n;e.error?null===(s=(t=this.listeners).error)||void 0===s||s.call(t,e.error):null===(n=(i=this.listeners).error)||void 0===n||n.call(i,new Error(e.message))},this.socket.onmessage=({data:t})=>{var s,i,n,o,r,a,d,c,l,u,h,f,m,v,y;const b=JSON.parse(t.toString());if("error"in b)null===(i=(s=this.listeners).error)||void 0===i||i.call(s,new p(b.error));else switch(b.message_type){case"SessionBegins":{const t={sessionId:b.session_id,expiresAt:new Date(b.expires_at)};e(t),null===(o=(n=this.listeners).open)||void 0===o||o.call(n,t);break}case"PartialTranscript":b.created=new Date(b.created),null===(a=(r=this.listeners).transcript)||void 0===a||a.call(r,b),null===(c=(d=this.listeners)["transcript.partial"])||void 0===c||c.call(d,b);break;case"FinalTranscript":b.created=new Date(b.created),null===(u=(l=this.listeners).transcript)||void 0===u||u.call(l,b),null===(f=(h=this.listeners)["transcript.final"])||void 0===f||f.call(h,b);break;case"SessionInformation":null===(v=(m=this.listeners).session_information)||void 0===v||v.call(m,b);break;case"SessionTerminated":null===(y=this.sessionTerminatedResolve)||void 0===y||y.call(this)}}}))}sendAudio(e){this.send(e)}stream(){return new a({write:e=>{this.sendAudio(e)}})}forceEndUtterance(){this.send('{"force_end_utterance":true}')}configureEndUtteranceSilenceThreshold(e){this.send(`{"end_utterance_silence_threshold":${e}}`)}send(e){if(!this.socket||this.socket.readyState!==this.socket.OPEN)throw new Error("Socket is not open for communication");this.socket.send(e)}close(){return t(this,arguments,void 0,(function*(e=!0){var t;if(this.socket){if(this.socket.readyState===this.socket.OPEN)if(e){const e=new Promise((e=>{this.sessionTerminatedResolve=e}));this.socket.send(m),yield e}else this.socket.send(m);(null===(t=this.socket)||void 0===t?void 0:t.removeAllListeners)&&this.socket.removeAllListeners(),this.socket.close()}this.listeners={},this.socket=void 0}))}}class y extends o{constructor(e){super(e),this.rtFactoryParams=e}createService(e){return this.transcriber(e)}transcriber(e){const t=Object.assign({},e);return t.token||t.apiKey||(t.apiKey=this.rtFactoryParams.apiKey),new v(t)}createTemporaryToken(e){return t(this,void 0,void 0,(function*(){return(yield this.fetchJson("/v2/realtime/token",{method:"POST",body:JSON.stringify(e)})).token}))}}function b(e){return e.startsWith("http")||e.startsWith("https")||e.startsWith("data:")?null:e.startsWith("file://")?e.substring(7):e.startsWith("file:")?e.substring(5):e}class S extends o{constructor(e,t){super(e),this.files=t}transcribe(e,s){return t(this,void 0,void 0,(function*(){const t=yield this.submit(e);return yield this.waitUntilReady(t.id,s)}))}submit(e){return t(this,void 0,void 0,(function*(){let t,s;if("audio"in e){const{audio:i}=e,n=function(e,t){var s={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(s[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(s[i[n]]=e[i[n]])}return s}(e,["audio"]);if("string"==typeof i){const e=b(i);t=null!==e?yield this.files.upload(e):i.startsWith("data:")?yield this.files.upload(i):i}else t=yield this.files.upload(i);s=Object.assign(Object.assign({},n),{audio_url:t})}else s=e;return yield this.fetchJson("/v2/transcript",{method:"POST",body:JSON.stringify(s)})}))}create(e,s){return t(this,void 0,void 0,(function*(){var t;const i=b(e.audio_url);if(null!==i){const t=yield this.files.upload(i);e.audio_url=t}const n=yield this.fetchJson("/v2/transcript",{method:"POST",body:JSON.stringify(e)});return null===(t=null==s?void 0:s.poll)||void 0===t||t?yield this.waitUntilReady(n.id,s):n}))}waitUntilReady(e,s){return t(this,void 0,void 0,(function*(){var t,i;const n=null!==(t=null==s?void 0:s.pollingInterval)&&void 0!==t?t:3e3,o=null!==(i=null==s?void 0:s.pollingTimeout)&&void 0!==i?i:-1,r=Date.now();for(;;){const t=yield this.get(e);if("completed"===t.status||"error"===t.status)return t;if(o>0&&Date.now()-r>o)throw new Error("Polling timeout");yield new Promise((e=>setTimeout(e,n)))}}))}get(e){return this.fetchJson(`/v2/transcript/${e}`)}list(e){return t(this,void 0,void 0,(function*(){let t="/v2/transcript";"string"==typeof e?t=e:e&&(t=`${t}?${new URLSearchParams(Object.keys(e).map((t=>{var s;return[t,(null===(s=e[t])||void 0===s?void 0:s.toString())||""]})))}`);const s=yield this.fetchJson(t);for(const e of s.transcripts)e.created=new Date(e.created),e.completed&&(e.completed=new Date(e.completed));return s}))}delete(e){return this.fetchJson(`/v2/transcript/${e}`,{method:"DELETE"})}wordSearch(e,t){const s=new URLSearchParams({words:t.join(",")});return this.fetchJson(`/v2/transcript/${e}/word-search?${s.toString()}`)}sentences(e){return this.fetchJson(`/v2/transcript/${e}/sentences`)}paragraphs(e){return this.fetchJson(`/v2/transcript/${e}/paragraphs`)}subtitles(e){return t(this,arguments,void 0,(function*(e,t="srt",s){let i=`/v2/transcript/${e}/${t}`;if(s){const e=new URLSearchParams;e.set("chars_per_caption",s.toString()),i+=`?${e.toString()}`}const n=yield this.fetch(i);return yield n.text()}))}redactions(e){return this.redactedAudio(e)}redactedAudio(e){return this.fetchJson(`/v2/transcript/${e}/redacted-audio`)}redactedAudioFile(e){return t(this,void 0,void 0,(function*(){const{redacted_audio_url:t,status:s}=yield this.redactedAudio(e);if("redacted_audio_ready"!==s)throw new Error(`Redacted audio status is ${s}`);const i=yield fetch(t);if(!i.ok)throw new Error(`Failed to fetch redacted audio: ${i.statusText}`);return{arrayBuffer:i.arrayBuffer.bind(i),blob:i.blob.bind(i),body:i.body,bodyUsed:i.bodyUsed}}))}}class g extends o{upload(e){return t(this,void 0,void 0,(function*(){let s;s="string"==typeof e?e.startsWith("data:")?function(e){const t=e.split(","),s=t[0].match(/:(.*?);/)[1],i=atob(t[1]);let n=i.length;const o=new Uint8Array(n);for(;n--;)o[n]=i.charCodeAt(n);return new Blob([o],{type:s})}(e):yield function(e){return t(this,void 0,void 0,(function*(){throw new Error("Interacting with the file system is not supported in this environment.")}))}():e;return(yield this.fetchJson("/v2/upload",{method:"POST",body:s,headers:{"Content-Type":"application/octet-stream"},duplex:"half"})).upload_url}))}}e.AssemblyAI=class{constructor(e){e.baseUrl=e.baseUrl||"https://api.assemblyai.com",e.baseUrl&&e.baseUrl.endsWith("/")&&(e.baseUrl=e.baseUrl.slice(0,-1)),this.files=new g(e),this.transcripts=new S(e,this.files),this.lemur=new r(e),this.realtime=new y(e)}},e.FileService=g,e.LemurService=r,e.RealtimeService=class extends v{},e.RealtimeServiceFactory=class extends y{},e.RealtimeTranscriber=v,e.RealtimeTranscriberFactory=y,e.TranscriptService=S}));
|
package/dist/browser.mjs
CHANGED
|
@@ -15,7 +15,7 @@ if (typeof navigator !== "undefined" && navigator.userAgent) {
|
|
|
15
15
|
defaultUserAgentString += navigator.userAgent;
|
|
16
16
|
}
|
|
17
17
|
const defaultUserAgent = {
|
|
18
|
-
sdk: { name: "JavaScript", version: "4.
|
|
18
|
+
sdk: { name: "JavaScript", version: "4.6.1" },
|
|
19
19
|
};
|
|
20
20
|
if (typeof process !== "undefined") {
|
|
21
21
|
if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
|
|
@@ -197,7 +197,14 @@ class RealtimeError extends Error {
|
|
|
197
197
|
const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
|
|
198
198
|
const forceEndOfUtteranceMessage = `{"force_end_utterance":true}`;
|
|
199
199
|
const terminateSessionMessage = `{"terminate_session":true}`;
|
|
200
|
+
/**
|
|
201
|
+
* RealtimeTranscriber connects to the Streaming Speech-to-Text API and lets you transcribe audio in real-time.
|
|
202
|
+
*/
|
|
200
203
|
class RealtimeTranscriber {
|
|
204
|
+
/**
|
|
205
|
+
* Create a new RealtimeTranscriber.
|
|
206
|
+
* @param params - Parameters to configure the RealtimeTranscriber
|
|
207
|
+
*/
|
|
201
208
|
constructor(params) {
|
|
202
209
|
this.listeners = {};
|
|
203
210
|
this.realtimeUrl = params.realtimeUrl ?? defaultRealtimeUrl;
|
|
@@ -237,10 +244,19 @@ class RealtimeTranscriber {
|
|
|
237
244
|
url.search = searchParams.toString();
|
|
238
245
|
return url;
|
|
239
246
|
}
|
|
247
|
+
/**
|
|
248
|
+
* Add a listener for an event.
|
|
249
|
+
* @param event - The event to listen for.
|
|
250
|
+
* @param listener - The function to call when the event is emitted.
|
|
251
|
+
*/
|
|
240
252
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
241
253
|
on(event, listener) {
|
|
242
254
|
this.listeners[event] = listener;
|
|
243
255
|
}
|
|
256
|
+
/**
|
|
257
|
+
* Connect to the server and begin a new session.
|
|
258
|
+
* @returns A promise that resolves when the connection is established and the session begins.
|
|
259
|
+
*/
|
|
244
260
|
connect() {
|
|
245
261
|
return new Promise((resolve) => {
|
|
246
262
|
if (this.socket) {
|
|
@@ -319,9 +335,17 @@ class RealtimeTranscriber {
|
|
|
319
335
|
};
|
|
320
336
|
});
|
|
321
337
|
}
|
|
338
|
+
/**
|
|
339
|
+
* Send audio data to the server.
|
|
340
|
+
* @param audio - The audio data to send to the server.
|
|
341
|
+
*/
|
|
322
342
|
sendAudio(audio) {
|
|
323
343
|
this.send(audio);
|
|
324
344
|
}
|
|
345
|
+
/**
|
|
346
|
+
* Create a writable stream that can be used to send audio data to the server.
|
|
347
|
+
* @returns A writable stream that can be used to send audio data to the server.
|
|
348
|
+
*/
|
|
325
349
|
stream() {
|
|
326
350
|
return new WritableStream({
|
|
327
351
|
write: (chunk) => {
|
|
@@ -349,6 +373,11 @@ class RealtimeTranscriber {
|
|
|
349
373
|
}
|
|
350
374
|
this.socket.send(data);
|
|
351
375
|
}
|
|
376
|
+
/**
|
|
377
|
+
* Close the connection to the server.
|
|
378
|
+
* @param waitForSessionTermination - If true, the method will wait for the session to be terminated before closing the connection.
|
|
379
|
+
* While waiting for the session to be terminated, you will receive the final transcript and session information.
|
|
380
|
+
*/
|
|
352
381
|
async close(waitForSessionTermination = true) {
|
|
353
382
|
if (this.socket) {
|
|
354
383
|
if (this.socket.readyState === this.socket.OPEN) {
|
|
@@ -435,7 +464,6 @@ class TranscriptService extends BaseService {
|
|
|
435
464
|
* @returns A promise that resolves to the transcript. The transcript status is "completed" or "error".
|
|
436
465
|
*/
|
|
437
466
|
async transcribe(params, options) {
|
|
438
|
-
deprecateConformer2(params);
|
|
439
467
|
const transcript = await this.submit(params);
|
|
440
468
|
return await this.waitUntilReady(transcript.id, options);
|
|
441
469
|
}
|
|
@@ -445,7 +473,6 @@ class TranscriptService extends BaseService {
|
|
|
445
473
|
* @returns A promise that resolves to the queued transcript.
|
|
446
474
|
*/
|
|
447
475
|
async submit(params) {
|
|
448
|
-
deprecateConformer2(params);
|
|
449
476
|
let audioUrl;
|
|
450
477
|
let transcriptParams = undefined;
|
|
451
478
|
if ("audio" in params) {
|
|
@@ -489,7 +516,6 @@ class TranscriptService extends BaseService {
|
|
|
489
516
|
* @deprecated Use `transcribe` instead to transcribe a audio file that includes polling, or `submit` to transcribe a audio file without polling.
|
|
490
517
|
*/
|
|
491
518
|
async create(params, options) {
|
|
492
|
-
deprecateConformer2(params);
|
|
493
519
|
const path = getPath(params.audio_url);
|
|
494
520
|
if (path !== null) {
|
|
495
521
|
const uploadUrl = await this.files.upload(path);
|
|
@@ -652,13 +678,6 @@ class TranscriptService extends BaseService {
|
|
|
652
678
|
};
|
|
653
679
|
}
|
|
654
680
|
}
|
|
655
|
-
function deprecateConformer2(params) {
|
|
656
|
-
if (!params)
|
|
657
|
-
return;
|
|
658
|
-
if (params.speech_model === "conformer-2") {
|
|
659
|
-
console.warn("The speech_model conformer-2 option is deprecated and will stop working in the near future. Use best or nano instead.");
|
|
660
|
-
}
|
|
661
|
-
}
|
|
662
681
|
|
|
663
682
|
const readFile = async function (
|
|
664
683
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
package/dist/bun.mjs
CHANGED
|
@@ -17,7 +17,7 @@ if (typeof navigator !== "undefined" && navigator.userAgent) {
|
|
|
17
17
|
defaultUserAgentString += navigator.userAgent;
|
|
18
18
|
}
|
|
19
19
|
const defaultUserAgent = {
|
|
20
|
-
sdk: { name: "JavaScript", version: "4.
|
|
20
|
+
sdk: { name: "JavaScript", version: "4.6.1" },
|
|
21
21
|
};
|
|
22
22
|
if (typeof process !== "undefined") {
|
|
23
23
|
if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
|
|
@@ -193,7 +193,14 @@ class RealtimeError extends Error {
|
|
|
193
193
|
const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
|
|
194
194
|
const forceEndOfUtteranceMessage = `{"force_end_utterance":true}`;
|
|
195
195
|
const terminateSessionMessage = `{"terminate_session":true}`;
|
|
196
|
+
/**
|
|
197
|
+
* RealtimeTranscriber connects to the Streaming Speech-to-Text API and lets you transcribe audio in real-time.
|
|
198
|
+
*/
|
|
196
199
|
class RealtimeTranscriber {
|
|
200
|
+
/**
|
|
201
|
+
* Create a new RealtimeTranscriber.
|
|
202
|
+
* @param params - Parameters to configure the RealtimeTranscriber
|
|
203
|
+
*/
|
|
197
204
|
constructor(params) {
|
|
198
205
|
this.listeners = {};
|
|
199
206
|
this.realtimeUrl = params.realtimeUrl ?? defaultRealtimeUrl;
|
|
@@ -233,10 +240,19 @@ class RealtimeTranscriber {
|
|
|
233
240
|
url.search = searchParams.toString();
|
|
234
241
|
return url;
|
|
235
242
|
}
|
|
243
|
+
/**
|
|
244
|
+
* Add a listener for an event.
|
|
245
|
+
* @param event - The event to listen for.
|
|
246
|
+
* @param listener - The function to call when the event is emitted.
|
|
247
|
+
*/
|
|
236
248
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
237
249
|
on(event, listener) {
|
|
238
250
|
this.listeners[event] = listener;
|
|
239
251
|
}
|
|
252
|
+
/**
|
|
253
|
+
* Connect to the server and begin a new session.
|
|
254
|
+
* @returns A promise that resolves when the connection is established and the session begins.
|
|
255
|
+
*/
|
|
240
256
|
connect() {
|
|
241
257
|
return new Promise((resolve) => {
|
|
242
258
|
if (this.socket) {
|
|
@@ -315,9 +331,17 @@ class RealtimeTranscriber {
|
|
|
315
331
|
};
|
|
316
332
|
});
|
|
317
333
|
}
|
|
334
|
+
/**
|
|
335
|
+
* Send audio data to the server.
|
|
336
|
+
* @param audio - The audio data to send to the server.
|
|
337
|
+
*/
|
|
318
338
|
sendAudio(audio) {
|
|
319
339
|
this.send(audio);
|
|
320
340
|
}
|
|
341
|
+
/**
|
|
342
|
+
* Create a writable stream that can be used to send audio data to the server.
|
|
343
|
+
* @returns A writable stream that can be used to send audio data to the server.
|
|
344
|
+
*/
|
|
321
345
|
stream() {
|
|
322
346
|
return new WritableStream({
|
|
323
347
|
write: (chunk) => {
|
|
@@ -345,6 +369,11 @@ class RealtimeTranscriber {
|
|
|
345
369
|
}
|
|
346
370
|
this.socket.send(data);
|
|
347
371
|
}
|
|
372
|
+
/**
|
|
373
|
+
* Close the connection to the server.
|
|
374
|
+
* @param waitForSessionTermination - If true, the method will wait for the session to be terminated before closing the connection.
|
|
375
|
+
* While waiting for the session to be terminated, you will receive the final transcript and session information.
|
|
376
|
+
*/
|
|
348
377
|
async close(waitForSessionTermination = true) {
|
|
349
378
|
if (this.socket) {
|
|
350
379
|
if (this.socket.readyState === this.socket.OPEN) {
|
|
@@ -431,7 +460,6 @@ class TranscriptService extends BaseService {
|
|
|
431
460
|
* @returns A promise that resolves to the transcript. The transcript status is "completed" or "error".
|
|
432
461
|
*/
|
|
433
462
|
async transcribe(params, options) {
|
|
434
|
-
deprecateConformer2(params);
|
|
435
463
|
const transcript = await this.submit(params);
|
|
436
464
|
return await this.waitUntilReady(transcript.id, options);
|
|
437
465
|
}
|
|
@@ -441,7 +469,6 @@ class TranscriptService extends BaseService {
|
|
|
441
469
|
* @returns A promise that resolves to the queued transcript.
|
|
442
470
|
*/
|
|
443
471
|
async submit(params) {
|
|
444
|
-
deprecateConformer2(params);
|
|
445
472
|
let audioUrl;
|
|
446
473
|
let transcriptParams = undefined;
|
|
447
474
|
if ("audio" in params) {
|
|
@@ -485,7 +512,6 @@ class TranscriptService extends BaseService {
|
|
|
485
512
|
* @deprecated Use `transcribe` instead to transcribe a audio file that includes polling, or `submit` to transcribe a audio file without polling.
|
|
486
513
|
*/
|
|
487
514
|
async create(params, options) {
|
|
488
|
-
deprecateConformer2(params);
|
|
489
515
|
const path = getPath(params.audio_url);
|
|
490
516
|
if (path !== null) {
|
|
491
517
|
const uploadUrl = await this.files.upload(path);
|
|
@@ -648,13 +674,6 @@ class TranscriptService extends BaseService {
|
|
|
648
674
|
};
|
|
649
675
|
}
|
|
650
676
|
}
|
|
651
|
-
function deprecateConformer2(params) {
|
|
652
|
-
if (!params)
|
|
653
|
-
return;
|
|
654
|
-
if (params.speech_model === "conformer-2") {
|
|
655
|
-
console.warn("The speech_model conformer-2 option is deprecated and will stop working in the near future. Use best or nano instead.");
|
|
656
|
-
}
|
|
657
|
-
}
|
|
658
677
|
|
|
659
678
|
const readFile = async (path) => Bun.file(path).stream();
|
|
660
679
|
|
package/dist/deno.mjs
CHANGED
|
@@ -17,7 +17,7 @@ if (typeof navigator !== "undefined" && navigator.userAgent) {
|
|
|
17
17
|
defaultUserAgentString += navigator.userAgent;
|
|
18
18
|
}
|
|
19
19
|
const defaultUserAgent = {
|
|
20
|
-
sdk: { name: "JavaScript", version: "4.
|
|
20
|
+
sdk: { name: "JavaScript", version: "4.6.1" },
|
|
21
21
|
};
|
|
22
22
|
if (typeof process !== "undefined") {
|
|
23
23
|
if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
|
|
@@ -193,7 +193,14 @@ class RealtimeError extends Error {
|
|
|
193
193
|
const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
|
|
194
194
|
const forceEndOfUtteranceMessage = `{"force_end_utterance":true}`;
|
|
195
195
|
const terminateSessionMessage = `{"terminate_session":true}`;
|
|
196
|
+
/**
|
|
197
|
+
* RealtimeTranscriber connects to the Streaming Speech-to-Text API and lets you transcribe audio in real-time.
|
|
198
|
+
*/
|
|
196
199
|
class RealtimeTranscriber {
|
|
200
|
+
/**
|
|
201
|
+
* Create a new RealtimeTranscriber.
|
|
202
|
+
* @param params - Parameters to configure the RealtimeTranscriber
|
|
203
|
+
*/
|
|
197
204
|
constructor(params) {
|
|
198
205
|
this.listeners = {};
|
|
199
206
|
this.realtimeUrl = params.realtimeUrl ?? defaultRealtimeUrl;
|
|
@@ -233,10 +240,19 @@ class RealtimeTranscriber {
|
|
|
233
240
|
url.search = searchParams.toString();
|
|
234
241
|
return url;
|
|
235
242
|
}
|
|
243
|
+
/**
|
|
244
|
+
* Add a listener for an event.
|
|
245
|
+
* @param event - The event to listen for.
|
|
246
|
+
* @param listener - The function to call when the event is emitted.
|
|
247
|
+
*/
|
|
236
248
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
237
249
|
on(event, listener) {
|
|
238
250
|
this.listeners[event] = listener;
|
|
239
251
|
}
|
|
252
|
+
/**
|
|
253
|
+
* Connect to the server and begin a new session.
|
|
254
|
+
* @returns A promise that resolves when the connection is established and the session begins.
|
|
255
|
+
*/
|
|
240
256
|
connect() {
|
|
241
257
|
return new Promise((resolve) => {
|
|
242
258
|
if (this.socket) {
|
|
@@ -315,9 +331,17 @@ class RealtimeTranscriber {
|
|
|
315
331
|
};
|
|
316
332
|
});
|
|
317
333
|
}
|
|
334
|
+
/**
|
|
335
|
+
* Send audio data to the server.
|
|
336
|
+
* @param audio - The audio data to send to the server.
|
|
337
|
+
*/
|
|
318
338
|
sendAudio(audio) {
|
|
319
339
|
this.send(audio);
|
|
320
340
|
}
|
|
341
|
+
/**
|
|
342
|
+
* Create a writable stream that can be used to send audio data to the server.
|
|
343
|
+
* @returns A writable stream that can be used to send audio data to the server.
|
|
344
|
+
*/
|
|
321
345
|
stream() {
|
|
322
346
|
return new WritableStream({
|
|
323
347
|
write: (chunk) => {
|
|
@@ -345,6 +369,11 @@ class RealtimeTranscriber {
|
|
|
345
369
|
}
|
|
346
370
|
this.socket.send(data);
|
|
347
371
|
}
|
|
372
|
+
/**
|
|
373
|
+
* Close the connection to the server.
|
|
374
|
+
* @param waitForSessionTermination - If true, the method will wait for the session to be terminated before closing the connection.
|
|
375
|
+
* While waiting for the session to be terminated, you will receive the final transcript and session information.
|
|
376
|
+
*/
|
|
348
377
|
async close(waitForSessionTermination = true) {
|
|
349
378
|
if (this.socket) {
|
|
350
379
|
if (this.socket.readyState === this.socket.OPEN) {
|
|
@@ -431,7 +460,6 @@ class TranscriptService extends BaseService {
|
|
|
431
460
|
* @returns A promise that resolves to the transcript. The transcript status is "completed" or "error".
|
|
432
461
|
*/
|
|
433
462
|
async transcribe(params, options) {
|
|
434
|
-
deprecateConformer2(params);
|
|
435
463
|
const transcript = await this.submit(params);
|
|
436
464
|
return await this.waitUntilReady(transcript.id, options);
|
|
437
465
|
}
|
|
@@ -441,7 +469,6 @@ class TranscriptService extends BaseService {
|
|
|
441
469
|
* @returns A promise that resolves to the queued transcript.
|
|
442
470
|
*/
|
|
443
471
|
async submit(params) {
|
|
444
|
-
deprecateConformer2(params);
|
|
445
472
|
let audioUrl;
|
|
446
473
|
let transcriptParams = undefined;
|
|
447
474
|
if ("audio" in params) {
|
|
@@ -485,7 +512,6 @@ class TranscriptService extends BaseService {
|
|
|
485
512
|
* @deprecated Use `transcribe` instead to transcribe a audio file that includes polling, or `submit` to transcribe a audio file without polling.
|
|
486
513
|
*/
|
|
487
514
|
async create(params, options) {
|
|
488
|
-
deprecateConformer2(params);
|
|
489
515
|
const path = getPath(params.audio_url);
|
|
490
516
|
if (path !== null) {
|
|
491
517
|
const uploadUrl = await this.files.upload(path);
|
|
@@ -648,13 +674,6 @@ class TranscriptService extends BaseService {
|
|
|
648
674
|
};
|
|
649
675
|
}
|
|
650
676
|
}
|
|
651
|
-
function deprecateConformer2(params) {
|
|
652
|
-
if (!params)
|
|
653
|
-
return;
|
|
654
|
-
if (params.speech_model === "conformer-2") {
|
|
655
|
-
console.warn("The speech_model conformer-2 option is deprecated and will stop working in the near future. Use best or nano instead.");
|
|
656
|
-
}
|
|
657
|
-
}
|
|
658
677
|
|
|
659
678
|
const readFile = async (path) => (await Deno.open(path)).readable;
|
|
660
679
|
|