@soniox/soniox-node
Version:
Node.js client library for Soniox speech recognition service.
3 lines (2 loc) • 6.52 kB
JavaScript
;var k=Object.create;var f=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var O=Object.getPrototypeOf,P=Object.prototype.hasOwnProperty;var v=(n,e)=>{for(var r in e)f(n,r,{get:e[r],enumerable:!0})},b=(n,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of S(e))!P.call(n,s)&&s!==r&&f(n,s,{get:()=>e[s],enumerable:!(i=C(e,s))||i.enumerable});return n};var h=(n,e,r)=>(r=n!=null?k(O(n)):{},b(e||!n||!n.__esModule?f(r,"default",{value:n,enumerable:!0}):r,n)),M=n=>b(f({},"__esModule",{value:!0}),n);var W={};v(W,{SpeechClient:()=>d,dateToTimestamp:()=>K,timestampToDate:()=>I});module.exports=M(W);var w=h(require("fs")),A=h(require("fs/promises")),p=h(require("@grpc/grpc-js")),q=h(require("@grpc/proto-loader")),E=__dirname+"/speech_service.proto",D=131072,T=6291456,G=q.loadSync(E,{keepCase:!0,longs:String,enums:String,defaults:!0,oneofs:!0}),F=p.loadPackageDefinition(G),x=F.soniox.speech_service;async function _(n,e){await new Promise((r,i)=>{n.write(e,s=>{s?i(s):r()})})}function K(n){let e=n.getTime(),r=Math.floor(e/1e3),i=e-r*1e3;return{seconds:r.toString(),nanos:i*1e6}}function I(n){let e=1e3*parseInt(n.seconds)+Math.floor(.001*n.nanos);return new Date(e)}var d=class{constructor(e){this.config={api_host:process.env.SONIOX_API_HOST||"https://api.soniox.com:443",api_key:process.env.SONIOX_API_KEY||""};this.connection=this._getConnectionData(this.config.api_host);this.client=new x.SpeechService(this.connection.host,this.connection.credentials,{"grpc.max_send_message_length":T,"grpc.max_receive_message_length":T});this.defaultRequestConfig={client_request_reference:"",audio_format:"",sample_rate_hertz:0,num_audio_channels:0,include_nonfinal:!1,enable_separate_recognition_per_channel:!1,enable_endpoint_detection:!1,speech_context:null,enable_profanity_filter:!1,content_moderation_phrases:[],enable_streaming_speaker_diarization:!1,enable_global_speaker_diarization:!1,min_num_speakers:0,max_num_speakers:0,enable_speaker_identification:!1,cand_speaker_names:[],model:"",enable_dictation:!1};this.transcribeFileShort=async(e,r)=>{if(!e)throw new Error('Missing "file_path".');r={...this.defaultRequestConfig,...r},this._validateConfig(r);let i=await A.readFile(e);return await new Promise((s,o)=>{let c={api_key:this.config.api_key,config:r,audio:new Uint8Array(i)};this.client.Transcribe(c,(a,t)=>{if(a||!t){o(a||"Response is undefined");return}if(r.enable_separate_recognition_per_channel){if(t.channel_results.length==0){o("Response does not contain channel_results.");return}s(t.channel_results)}else{if(t.result==null){o("Response does not contain result.");return}s(t.result)}})})};this.transcribeFileAsync=async(e,r,i)=>{if(!e)throw new Error('Missing "file_path".');if(!r)throw new Error('Missing "reference_name".');i={...this.defaultRequestConfig,...i},this._validateConfig(i);let s=w.createReadStream(e,{highWaterMark:D}),o=[],c=new Promise((y,m)=>{o.push(this.client.TranscribeAsync((R,g)=>{if(R){m(R);return}if(!g){m("missing response");return}y(g)}))}),a=o[0],t={api_key:this.config.api_key,reference_name:r,config:i,enable_eof:!0};await _(a,t);for await(let y of s){let m={audio:new Uint8Array(y)};await _(a,m)}return await _(a,{eof:!0}),a.end(),(await c).file_id};this.getTranscribeAsyncStatus=async e=>{if(!e)throw new Error('Missing "file_id".');let r={api_key:this.config.api_key,file_id:e};return await new Promise((i,s)=>{this.client.GetTranscribeAsyncStatus(r,(o,c)=>{if(o){s(o);return}if(!c){s("missing response");return}if(c.files.length!==1){s("Unexpected number of files returned.");return}i(c.files[0])})})};this.getTranscribeAsyncResult=async e=>{if(!e)throw new Error('Missing "file_id".');let r={api_key:this.config.api_key,file_id:e};return await new Promise((i,s)=>{let o=this.client.GetTranscribeAsyncResult(r),c=new Map,a=null;o.on("data",function(t){if(!!t.result)if(t.separate_recognition_per_channel){let u=c.get(t.result.channel);if(!u)c.set(t.result.channel,t.result);else{for(let l of t.result.words)u.words.push(l);u.final_proc_time_ms=t.result.final_proc_time_ms,u.total_proc_time_ms=t.result.total_proc_time_ms,u.speakers=t.result.speakers}}else if(!a)a=t.result;else{for(let u of t.result.words)a.words.push(u);a.final_proc_time_ms=t.result.final_proc_time_ms,a.total_proc_time_ms=t.result.total_proc_time_ms,a.speakers=t.result.speakers}}),o.on("error",function(t){s(t)}),o.on("end",function(){if(c.size>0){let t=Array.from(c.values());t.sort((u,l)=>u.channel<l.channel?-1:u.channel>l.channel?1:0),i(t)}else a?i(a):s("no results received")})})};this.deleteTranscribeAsyncFile=async e=>{if(!e)throw new Error('Missing "file_id".');let r={api_key:this.config.api_key,file_id:e};return await new Promise((i,s)=>{this.client.DeleteTranscribeAsyncFile(r,(o,c)=>{if(o){s(o);return}if(!c){s("missing response");return}i(c)})})};this.transcribeStream=(e,r,i)=>{if(!r)throw new Error('Missing "onData" callback handler.');if(!i)throw new Error('Missing "onEnd" callback handler.');e={...this.defaultRequestConfig,...e},this._validateConfig(e);let s=this.client.TranscribeStream(),o=t=>{let u={audio:t};s.write(u)},c=async t=>{await _(s,{audio:t})},a=()=>{s.end()};return(async()=>{try{let t={api_key:this.config.api_key,config:e};await _(s,t);for await(let u of s){let l=u;l.result&&r(l.result)}}catch(t){i(t);return}i(null)})(),{write:o,writeAsync:c,end:a}};this.createTemporaryApiKey=async({usage_type:e,expires_in_s:r,client_request_reference:i})=>{let s={api_key:this.config.api_key,usage_type:e,expires_in_s:r,client_request_reference:i};return await new Promise((o,c)=>{this.client.CreateTemporaryApiKey(s,(a,t)=>{if(a){c(a);return}if(!t){c("missing response");return}o(t)})})};if(e!=null&&e.api_host&&(this.config.api_host=e.api_host),e!=null&&e.api_key&&(this.config.api_key=e.api_key),!this.config.api_host)throw new Error('Missing "api_host".');if(!this.config.api_key)throw new Error('Missing "api_key".')}_getConnectionData(e){if(!e)throw new Error('Missing "api_host".');return e.startsWith("http://")?{host:e.substring(7),credentials:p.credentials.createInsecure()}:e.startsWith("https://")?{host:e.substring(8),credentials:p.credentials.createSsl()}:{host:e,credentials:p.credentials.createInsecure()}}_validateConfig(e){for(let[r,i]of Object.entries(e))if(!this.defaultRequestConfig.hasOwnProperty(r))throw new Error(`Invalid config parameter "${r}" with value "${i}".`)}};0&&(module.exports={SpeechClient,dateToTimestamp,timestampToDate});
//# sourceMappingURL=index.js.map