assemblyai 4.1.0 → 4.2.0

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 CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## [4.2.0] - 2024-01-11
4
+
5
+ ### Added
6
+
7
+ - Add `content_safety_confidence` to `TranscriptParams` & `TranscriptOptionalParams`.
8
+
9
+ ### Changed
10
+
11
+ - The `RealtimeService` now sends audio as binary instead of a base64-encoded JSON object.
12
+
3
13
  ## [4.1.0] - 2023-12-22
4
14
 
5
15
  ### Added
@@ -248,6 +248,7 @@
248
248
  headers: { Authorization: this.apiKey },
249
249
  });
250
250
  }
251
+ this.socket.binaryType = "arraybuffer";
251
252
  this.socket.onclose = ({ code, reason }) => {
252
253
  var _a, _b;
253
254
  if (!reason) {
@@ -307,19 +308,7 @@
307
308
  if (!this.socket || this.socket.readyState !== WebSocket$1.OPEN) {
308
309
  throw new Error("Socket is not open for communication");
309
310
  }
310
- let audioData;
311
- if (typeof Buffer !== "undefined") {
312
- audioData = Buffer.from(audio).toString("base64");
313
- }
314
- else {
315
- // Buffer is not available in the browser by default
316
- // https://stackoverflow.com/a/42334410/2919731
317
- audioData = btoa(new Uint8Array(audio).reduce((data, byte) => data + String.fromCharCode(byte), ""));
318
- }
319
- const payload = {
320
- audio_data: audioData,
321
- };
322
- this.socket.send(JSON.stringify(payload));
311
+ this.socket.send(audio);
323
312
  }
324
313
  stream() {
325
314
  return new WritableStream({
@@ -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,o){return new(s||(s=Promise))((function(i,n){function r(e){try{c(o.next(e))}catch(e){n(e)}}function a(e){try{c(o.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}c((o=o.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class s{constructor(e){this.params=e}fetch(e,s){var o;return t(this,void 0,void 0,(function*(){(s=null!=s?s:{}).headers=null!==(o=s.headers)&&void 0!==o?o:{},s.headers=Object.assign({Authorization:this.params.apiKey,"Content-Type":"application/json"},s.headers),e.startsWith("http")||(e=this.params.baseUrl+e);const t=yield fetch(e,s);if(t.status>=400){let e;const s=yield t.text();if(s){try{e=JSON.parse(s)}catch(e){}if(null==e?void 0:e.error)throw new Error(e.error);throw new Error(s)}throw new Error(`HTTP Error: ${t.status} ${t.statusText}`)}return t}))}fetchJson(e,s){return t(this,void 0,void 0,(function*(){return(yield this.fetch(e,s)).json()}))}}class o extends s{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)})}purgeRequestData(e){return this.fetchJson(`/lemur/v3/${e}`,{method:"DELETE"})}}const{WritableStream:i}="undefined"!=typeof window?window:"undefined"!=typeof global?global:globalThis;var n=null;"undefined"!=typeof WebSocket?n=WebSocket:"undefined"!=typeof MozWebSocket?n=MozWebSocket:"undefined"!=typeof global?n=global.WebSocket||global.MozWebSocket:"undefined"!=typeof window?n=window.WebSocket||window.MozWebSocket:"undefined"!=typeof self&&(n=self.WebSocket||self.MozWebSocket);var r,a=n;!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"}(r||(r={}));const c={[r.BadSampleRate]:"Sample rate must be a positive integer",[r.AuthFailed]:"Not Authorized",[r.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.",[r.NonexistentSessionId]:"Session ID does not exist",[r.SessionExpired]:"Session has expired",[r.ClosedSession]:"Session is closed",[r.RateLimited]:"Rate limited",[r.UniqueSessionViolation]:"Unique session violation",[r.SessionTimeout]:"Session Timeout",[r.AudioTooShort]:"Audio too short",[r.AudioTooLong]:"Audio too long",[r.BadJson]:"Bad JSON",[r.BadSchema]:"Bad schema",[r.TooManyStreams]:"Too many streams",[r.Reconnected]:"Reconnected",[r.ReconnectAttemptsExhausted]:"Reconnect attempts exhausted"};class l extends Error{}class d{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,"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),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=new a(t.toString()):this.socket=new a(t.toString(),{headers:{Authorization:this.apiKey}}),this.socket.onclose=({code:e,reason:t})=>{var s,o;t||e in r&&(t=c[e]),null===(o=(s=this.listeners).close)||void 0===o||o.call(s,e,t)},this.socket.onerror=e=>{var t,s,o,i;e.error?null===(s=(t=this.listeners).error)||void 0===s||s.call(t,e.error):null===(i=(o=this.listeners).error)||void 0===i||i.call(o,new Error(e.message))},this.socket.onmessage=({data:t})=>{var s,o,i,n,r,a,c,d,u,h,f,p,m;const y=JSON.parse(t.toString());if("error"in y)null===(o=(s=this.listeners).error)||void 0===o||o.call(s,new l(y.error));else switch(y.message_type){case"SessionBegins":{const t={sessionId:y.session_id,expiresAt:new Date(y.expires_at)};e(t),null===(n=(i=this.listeners).open)||void 0===n||n.call(i,t);break}case"PartialTranscript":y.created=new Date(y.created),null===(a=(r=this.listeners).transcript)||void 0===a||a.call(r,y),null===(d=(c=this.listeners)["transcript.partial"])||void 0===d||d.call(c,y);break;case"FinalTranscript":y.created=new Date(y.created),null===(h=(u=this.listeners).transcript)||void 0===h||h.call(u,y),null===(p=(f=this.listeners)["transcript.final"])||void 0===p||p.call(f,y);break;case"SessionTerminated":null===(m=this.sessionTerminatedResolve)||void 0===m||m.call(this)}}}))}sendAudio(e){if(!this.socket||this.socket.readyState!==a.OPEN)throw new Error("Socket is not open for communication");let t;t="undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):btoa(new Uint8Array(e).reduce(((e,t)=>e+String.fromCharCode(t)),""));const s={audio_data:t};this.socket.send(JSON.stringify(s))}stream(){return new i({write:e=>{this.sendAudio(e)}})}close(e=!0){return t(this,void 0,void 0,(function*(){if(this.socket){if(this.socket.readyState===a.OPEN){const t='{"terminate_session": true}';if(e){const e=new Promise((e=>{this.sessionTerminatedResolve=e}));this.socket.send(t),yield e}else this.socket.send(t)}"removeAllListeners"in this.socket&&this.socket.removeAllListeners(),this.socket.close()}this.listeners={},this.socket=void 0}))}}class u extends s{constructor(e){super(e),this.rtFactoryParams=e}createService(e){const t=Object.assign({},e);return t.token||t.apiKey||(t.apiKey=this.rtFactoryParams.apiKey),new d(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}))}}class h extends s{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*(){const{audio:t}=e,s=function(e,t){var s={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(s[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(o=Object.getOwnPropertySymbols(e);i<o.length;i++)t.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(e,o[i])&&(s[o[i]]=e[o[i]])}return s}(e,["audio"]);let o;if("string"==typeof t){const e=f(t);o=null!==e?yield this.files.upload(e):t}else o=yield this.files.upload(t);return yield this.fetchJson("/v2/transcript",{method:"POST",body:JSON.stringify(Object.assign(Object.assign({},s),{audio_url:o}))})}))}create(e,s){var o;return t(this,void 0,void 0,(function*(){const t=f(e.audio_url);if(null!==t){const s=yield this.files.upload(t);e.audio_url=s}const i=yield this.fetchJson("/v2/transcript",{method:"POST",body:JSON.stringify(e)});return null===(o=null==s?void 0:s.poll)||void 0===o||o?yield this.waitUntilReady(i.id,s):i}))}waitUntilReady(e,s){var o,i;return t(this,void 0,void 0,(function*(){const t=null!==(o=null==s?void 0:s.pollingInterval)&&void 0!==o?o:3e3,n=null!==(i=null==s?void 0:s.pollingTimeout)&&void 0!==i?i:-1,r=Date.now();for(;;){const s=yield this.get(e);if("completed"===s.status||"error"===s.status)return s;if(n>0&&Date.now()-r>n)throw new Error("Polling timeout");yield new Promise((e=>setTimeout(e,t)))}}))}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,s="srt",o){return t(this,void 0,void 0,(function*(){let t=`/v2/transcript/${e}/${s}`;if(o){const e=new URLSearchParams;e.set("chars_per_caption",o.toString()),t+=`?${e.toString()}`}const i=yield this.fetch(t);return yield i.text()}))}redactions(e){return this.fetchJson(`/v2/transcript/${e}/redacted-audio`)}}function f(e){let t;try{return t=new URL(e),"file:"===t.protocol?t.pathname:null}catch(t){return e}}class p extends s{upload(e){return t(this,void 0,void 0,(function*(){let s;s="string"==typeof 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 p(e),this.transcripts=new h(e,this.files),this.lemur=new o(e),this.realtime=new u(e)}},e.FileService=p,e.LemurService=o,e.RealtimeService=d,e.RealtimeServiceFactory=u,e.TranscriptService=h}));
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(o,n){function r(e){try{c(i.next(e))}catch(e){n(e)}}function a(e){try{c(i.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?o(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;class s{constructor(e){this.params=e}fetch(e,s){var i;return t(this,void 0,void 0,(function*(){(s=null!=s?s:{}).headers=null!==(i=s.headers)&&void 0!==i?i:{},s.headers=Object.assign({Authorization:this.params.apiKey,"Content-Type":"application/json"},s.headers),e.startsWith("http")||(e=this.params.baseUrl+e);const t=yield fetch(e,s);if(t.status>=400){let e;const s=yield t.text();if(s){try{e=JSON.parse(s)}catch(e){}if(null==e?void 0:e.error)throw new Error(e.error);throw new Error(s)}throw new Error(`HTTP Error: ${t.status} ${t.statusText}`)}return t}))}fetchJson(e,s){return t(this,void 0,void 0,(function*(){return(yield this.fetch(e,s)).json()}))}}class i extends s{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)})}purgeRequestData(e){return this.fetchJson(`/lemur/v3/${e}`,{method:"DELETE"})}}const{WritableStream:o}="undefined"!=typeof window?window:"undefined"!=typeof global?global:globalThis;var n=null;"undefined"!=typeof WebSocket?n=WebSocket:"undefined"!=typeof MozWebSocket?n=MozWebSocket:"undefined"!=typeof global?n=global.WebSocket||global.MozWebSocket:"undefined"!=typeof window?n=window.WebSocket||window.MozWebSocket:"undefined"!=typeof self&&(n=self.WebSocket||self.MozWebSocket);var r,a=n;!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"}(r||(r={}));const c={[r.BadSampleRate]:"Sample rate must be a positive integer",[r.AuthFailed]:"Not Authorized",[r.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.",[r.NonexistentSessionId]:"Session ID does not exist",[r.SessionExpired]:"Session has expired",[r.ClosedSession]:"Session is closed",[r.RateLimited]:"Rate limited",[r.UniqueSessionViolation]:"Unique session violation",[r.SessionTimeout]:"Session Timeout",[r.AudioTooShort]:"Audio too short",[r.AudioTooLong]:"Audio too long",[r.BadJson]:"Bad JSON",[r.BadSchema]:"Bad schema",[r.TooManyStreams]:"Too many streams",[r.Reconnected]:"Reconnected",[r.ReconnectAttemptsExhausted]:"Reconnect attempts exhausted"};class l extends Error{}class d{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,"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),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=new a(t.toString()):this.socket=new a(t.toString(),{headers:{Authorization:this.apiKey}}),this.socket.binaryType="arraybuffer",this.socket.onclose=({code:e,reason:t})=>{var s,i;t||e in r&&(t=c[e]),null===(i=(s=this.listeners).close)||void 0===i||i.call(s,e,t)},this.socket.onerror=e=>{var t,s,i,o;e.error?null===(s=(t=this.listeners).error)||void 0===s||s.call(t,e.error):null===(o=(i=this.listeners).error)||void 0===o||o.call(i,new Error(e.message))},this.socket.onmessage=({data:t})=>{var s,i,o,n,r,a,c,d,u,h,f,p,m;const y=JSON.parse(t.toString());if("error"in y)null===(i=(s=this.listeners).error)||void 0===i||i.call(s,new l(y.error));else switch(y.message_type){case"SessionBegins":{const t={sessionId:y.session_id,expiresAt:new Date(y.expires_at)};e(t),null===(n=(o=this.listeners).open)||void 0===n||n.call(o,t);break}case"PartialTranscript":y.created=new Date(y.created),null===(a=(r=this.listeners).transcript)||void 0===a||a.call(r,y),null===(d=(c=this.listeners)["transcript.partial"])||void 0===d||d.call(c,y);break;case"FinalTranscript":y.created=new Date(y.created),null===(h=(u=this.listeners).transcript)||void 0===h||h.call(u,y),null===(p=(f=this.listeners)["transcript.final"])||void 0===p||p.call(f,y);break;case"SessionTerminated":null===(m=this.sessionTerminatedResolve)||void 0===m||m.call(this)}}}))}sendAudio(e){if(!this.socket||this.socket.readyState!==a.OPEN)throw new Error("Socket is not open for communication");this.socket.send(e)}stream(){return new o({write:e=>{this.sendAudio(e)}})}close(e=!0){return t(this,void 0,void 0,(function*(){if(this.socket){if(this.socket.readyState===a.OPEN){const t='{"terminate_session": true}';if(e){const e=new Promise((e=>{this.sessionTerminatedResolve=e}));this.socket.send(t),yield e}else this.socket.send(t)}"removeAllListeners"in this.socket&&this.socket.removeAllListeners(),this.socket.close()}this.listeners={},this.socket=void 0}))}}class u extends s{constructor(e){super(e),this.rtFactoryParams=e}createService(e){const t=Object.assign({},e);return t.token||t.apiKey||(t.apiKey=this.rtFactoryParams.apiKey),new d(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}))}}class h extends s{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*(){const{audio:t}=e,s=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 o=0;for(i=Object.getOwnPropertySymbols(e);o<i.length;o++)t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(s[i[o]]=e[i[o]])}return s}(e,["audio"]);let i;if("string"==typeof t){const e=f(t);i=null!==e?yield this.files.upload(e):t}else i=yield this.files.upload(t);return yield this.fetchJson("/v2/transcript",{method:"POST",body:JSON.stringify(Object.assign(Object.assign({},s),{audio_url:i}))})}))}create(e,s){var i;return t(this,void 0,void 0,(function*(){const t=f(e.audio_url);if(null!==t){const s=yield this.files.upload(t);e.audio_url=s}const o=yield this.fetchJson("/v2/transcript",{method:"POST",body:JSON.stringify(e)});return null===(i=null==s?void 0:s.poll)||void 0===i||i?yield this.waitUntilReady(o.id,s):o}))}waitUntilReady(e,s){var i,o;return t(this,void 0,void 0,(function*(){const t=null!==(i=null==s?void 0:s.pollingInterval)&&void 0!==i?i:3e3,n=null!==(o=null==s?void 0:s.pollingTimeout)&&void 0!==o?o:-1,r=Date.now();for(;;){const s=yield this.get(e);if("completed"===s.status||"error"===s.status)return s;if(n>0&&Date.now()-r>n)throw new Error("Polling timeout");yield new Promise((e=>setTimeout(e,t)))}}))}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,s="srt",i){return t(this,void 0,void 0,(function*(){let t=`/v2/transcript/${e}/${s}`;if(i){const e=new URLSearchParams;e.set("chars_per_caption",i.toString()),t+=`?${e.toString()}`}const o=yield this.fetch(t);return yield o.text()}))}redactions(e){return this.fetchJson(`/v2/transcript/${e}/redacted-audio`)}}function f(e){let t;try{return t=new URL(e),"file:"===t.protocol?t.pathname:null}catch(t){return e}}class p extends s{upload(e){return t(this,void 0,void 0,(function*(){let s;s="string"==typeof 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 p(e),this.transcripts=new h(e,this.files),this.lemur=new i(e),this.realtime=new u(e)}},e.FileService=p,e.LemurService=i,e.RealtimeService=d,e.RealtimeServiceFactory=u,e.TranscriptService=h}));
package/dist/bun.mjs CHANGED
@@ -182,6 +182,7 @@ class RealtimeService {
182
182
  headers: { Authorization: this.apiKey },
183
183
  });
184
184
  }
185
+ this.socket.binaryType = "arraybuffer";
185
186
  this.socket.onclose = ({ code, reason }) => {
186
187
  if (!reason) {
187
188
  if (code in RealtimeErrorType) {
@@ -238,19 +239,7 @@ class RealtimeService {
238
239
  if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
239
240
  throw new Error("Socket is not open for communication");
240
241
  }
241
- let audioData;
242
- if (typeof Buffer !== "undefined") {
243
- audioData = Buffer.from(audio).toString("base64");
244
- }
245
- else {
246
- // Buffer is not available in the browser by default
247
- // https://stackoverflow.com/a/42334410/2919731
248
- audioData = btoa(new Uint8Array(audio).reduce((data, byte) => data + String.fromCharCode(byte), ""));
249
- }
250
- const payload = {
251
- audio_data: audioData,
252
- };
253
- this.socket.send(JSON.stringify(payload));
242
+ this.socket.send(audio);
254
243
  }
255
244
  stream() {
256
245
  return new WritableStream({
package/dist/deno.mjs CHANGED
@@ -182,6 +182,7 @@ class RealtimeService {
182
182
  headers: { Authorization: this.apiKey },
183
183
  });
184
184
  }
185
+ this.socket.binaryType = "arraybuffer";
185
186
  this.socket.onclose = ({ code, reason }) => {
186
187
  if (!reason) {
187
188
  if (code in RealtimeErrorType) {
@@ -238,19 +239,7 @@ class RealtimeService {
238
239
  if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
239
240
  throw new Error("Socket is not open for communication");
240
241
  }
241
- let audioData;
242
- if (typeof Buffer !== "undefined") {
243
- audioData = Buffer.from(audio).toString("base64");
244
- }
245
- else {
246
- // Buffer is not available in the browser by default
247
- // https://stackoverflow.com/a/42334410/2919731
248
- audioData = btoa(new Uint8Array(audio).reduce((data, byte) => data + String.fromCharCode(byte), ""));
249
- }
250
- const payload = {
251
- audio_data: audioData,
252
- };
253
- this.socket.send(JSON.stringify(payload));
242
+ this.socket.send(audio);
254
243
  }
255
244
  stream() {
256
245
  return new WritableStream({
package/dist/index.cjs CHANGED
@@ -230,6 +230,7 @@ class RealtimeService {
230
230
  headers: { Authorization: this.apiKey },
231
231
  });
232
232
  }
233
+ this.socket.binaryType = "arraybuffer";
233
234
  this.socket.onclose = ({ code, reason }) => {
234
235
  var _a, _b;
235
236
  if (!reason) {
@@ -289,19 +290,7 @@ class RealtimeService {
289
290
  if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
290
291
  throw new Error("Socket is not open for communication");
291
292
  }
292
- let audioData;
293
- if (typeof Buffer !== "undefined") {
294
- audioData = Buffer.from(audio).toString("base64");
295
- }
296
- else {
297
- // Buffer is not available in the browser by default
298
- // https://stackoverflow.com/a/42334410/2919731
299
- audioData = btoa(new Uint8Array(audio).reduce((data, byte) => data + String.fromCharCode(byte), ""));
300
- }
301
- const payload = {
302
- audio_data: audioData,
303
- };
304
- this.socket.send(JSON.stringify(payload));
293
+ this.socket.send(audio);
305
294
  }
306
295
  stream() {
307
296
  return new WritableStream({
package/dist/index.mjs CHANGED
@@ -228,6 +228,7 @@ class RealtimeService {
228
228
  headers: { Authorization: this.apiKey },
229
229
  });
230
230
  }
231
+ this.socket.binaryType = "arraybuffer";
231
232
  this.socket.onclose = ({ code, reason }) => {
232
233
  var _a, _b;
233
234
  if (!reason) {
@@ -287,19 +288,7 @@ class RealtimeService {
287
288
  if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
288
289
  throw new Error("Socket is not open for communication");
289
290
  }
290
- let audioData;
291
- if (typeof Buffer !== "undefined") {
292
- audioData = Buffer.from(audio).toString("base64");
293
- }
294
- else {
295
- // Buffer is not available in the browser by default
296
- // https://stackoverflow.com/a/42334410/2919731
297
- audioData = btoa(new Uint8Array(audio).reduce((data, byte) => data + String.fromCharCode(byte), ""));
298
- }
299
- const payload = {
300
- audio_data: audioData,
301
- };
302
- this.socket.send(JSON.stringify(payload));
291
+ this.socket.send(audio);
303
292
  }
304
293
  stream() {
305
294
  return new WritableStream({
package/dist/node.cjs CHANGED
@@ -181,6 +181,7 @@ class RealtimeService {
181
181
  headers: { Authorization: this.apiKey },
182
182
  });
183
183
  }
184
+ this.socket.binaryType = "arraybuffer";
184
185
  this.socket.onclose = ({ code, reason }) => {
185
186
  if (!reason) {
186
187
  if (code in RealtimeErrorType) {
@@ -237,19 +238,7 @@ class RealtimeService {
237
238
  if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
238
239
  throw new Error("Socket is not open for communication");
239
240
  }
240
- let audioData;
241
- if (typeof Buffer !== "undefined") {
242
- audioData = Buffer.from(audio).toString("base64");
243
- }
244
- else {
245
- // Buffer is not available in the browser by default
246
- // https://stackoverflow.com/a/42334410/2919731
247
- audioData = btoa(new Uint8Array(audio).reduce((data, byte) => data + String.fromCharCode(byte), ""));
248
- }
249
- const payload = {
250
- audio_data: audioData,
251
- };
252
- this.socket.send(JSON.stringify(payload));
241
+ this.socket.send(audio);
253
242
  }
254
243
  stream() {
255
244
  return new web.WritableStream({
package/dist/node.mjs CHANGED
@@ -179,6 +179,7 @@ class RealtimeService {
179
179
  headers: { Authorization: this.apiKey },
180
180
  });
181
181
  }
182
+ this.socket.binaryType = "arraybuffer";
182
183
  this.socket.onclose = ({ code, reason }) => {
183
184
  if (!reason) {
184
185
  if (code in RealtimeErrorType) {
@@ -235,19 +236,7 @@ class RealtimeService {
235
236
  if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
236
237
  throw new Error("Socket is not open for communication");
237
238
  }
238
- let audioData;
239
- if (typeof Buffer !== "undefined") {
240
- audioData = Buffer.from(audio).toString("base64");
241
- }
242
- else {
243
- // Buffer is not available in the browser by default
244
- // https://stackoverflow.com/a/42334410/2919731
245
- audioData = btoa(new Uint8Array(audio).reduce((data, byte) => data + String.fromCharCode(byte), ""));
246
- }
247
- const payload = {
248
- audio_data: audioData,
249
- };
250
- this.socket.send(JSON.stringify(payload));
239
+ this.socket.send(audio);
251
240
  }
252
241
  stream() {
253
242
  return new WritableStream({
@@ -460,6 +460,12 @@ export type LemurBaseParams = {
460
460
  [key: string]: unknown;
461
461
  }
462
462
  ]>;
463
+ /**
464
+ * @description The model that is used for the final prompt after compression is performed.
465
+ * Defaults to "default".
466
+ *
467
+ * @default default
468
+ */
463
469
  final_model?: LiteralUnion<LemurModel, string>;
464
470
  /**
465
471
  * @description Custom formatted transcript data. Maximum size is the context limit of the selected model, which defaults to 100000.
@@ -2157,6 +2163,8 @@ export type TranscriptOptionalParams = {
2157
2163
  boost_param?: TranscriptBoostParam;
2158
2164
  /** @description Enable [Content Moderation](https://www.assemblyai.com/docs/models/content-moderation), can be true or false */
2159
2165
  content_safety?: boolean;
2166
+ /** @description The confidence threshold for content moderation. Values must be between 25 and 100. */
2167
+ content_safety_confidence?: number;
2160
2168
  /** @description Customize how words are spelled and formatted using to and from values */
2161
2169
  custom_spelling?: TranscriptCustomSpelling[];
2162
2170
  /** @description Whether custom topics is enabled, either true or false */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "assemblyai",
3
- "version": "4.1.0",
3
+ "version": "4.2.0",
4
4
  "description": "The AssemblyAI JavaScript SDK provides an easy-to-use interface for interacting with the AssemblyAI API, which supports async and real-time transcription, as well as the latest LeMUR models.",
5
5
  "engines": {
6
6
  "node": ">=18"
@@ -102,6 +102,7 @@ export class RealtimeService {
102
102
  headers: { Authorization: this.apiKey },
103
103
  });
104
104
  }
105
+ this.socket.binaryType = "arraybuffer";
105
106
 
106
107
  this.socket.onclose = ({ code, reason }: CloseEvent) => {
107
108
  if (!reason) {
@@ -160,23 +161,7 @@ export class RealtimeService {
160
161
  if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
161
162
  throw new Error("Socket is not open for communication");
162
163
  }
163
- let audioData;
164
- if (typeof Buffer !== "undefined") {
165
- audioData = Buffer.from(audio).toString("base64");
166
- } else {
167
- // Buffer is not available in the browser by default
168
- // https://stackoverflow.com/a/42334410/2919731
169
- audioData = btoa(
170
- new Uint8Array(audio).reduce(
171
- (data, byte) => data + String.fromCharCode(byte),
172
- ""
173
- )
174
- );
175
- }
176
- const payload = {
177
- audio_data: audioData,
178
- };
179
- this.socket.send(JSON.stringify(payload));
164
+ this.socket.send(audio);
180
165
  }
181
166
 
182
167
  stream(): WritableStream<ArrayBufferLike> {
@@ -514,6 +514,12 @@ export type LemurBaseParams = {
514
514
  }
515
515
  ]
516
516
  >;
517
+ /**
518
+ * @description The model that is used for the final prompt after compression is performed.
519
+ * Defaults to "default".
520
+ *
521
+ * @default default
522
+ */
517
523
  final_model?: LiteralUnion<LemurModel, string>;
518
524
  /**
519
525
  * @description Custom formatted transcript data. Maximum size is the context limit of the selected model, which defaults to 100000.
@@ -2305,6 +2311,8 @@ export type TranscriptOptionalParams = {
2305
2311
  boost_param?: TranscriptBoostParam;
2306
2312
  /** @description Enable [Content Moderation](https://www.assemblyai.com/docs/models/content-moderation), can be true or false */
2307
2313
  content_safety?: boolean;
2314
+ /** @description The confidence threshold for content moderation. Values must be between 25 and 100. */
2315
+ content_safety_confidence?: number;
2308
2316
  /** @description Customize how words are spelled and formatted using to and from values */
2309
2317
  custom_spelling?: TranscriptCustomSpelling[];
2310
2318
  /** @description Whether custom topics is enabled, either true or false */