@chatpanel/gateway 0.105.1 → 0.116.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/src/stt-engine.js CHANGED
@@ -1 +1 @@
1
- import{join as Ee}from"node:path";import{existsSync as Te,readdirSync as ke}from"node:fs";import{randomUUID as xe}from"node:crypto";import{ensureLib as oe,modelRoot as ie}from"./ner-engine.js";import{runtimeDtype as B,runtimeName as le,DTYPE_SUFFIX as Se}from"./model-runtime.js";import{verifyModelWeights as be}from"./model-integrity.js";import{DEFAULT_STT_MODEL as ae,isEnglishOnly as se,sttModelDtype as q,isKnownSttModel as De,sttModelEngine as P}from"./stt-models.js";import*as D from"./parakeet-engine.js";import*as Q from"./coreml-stt-engine.js";import*as b from"./diarize-engine.js";import*as L from"./segment-engine.js";import{turnsFromSpans as Le,mainLocal as Ae,timeByLocal as ve,audioOfLocal as $e}from"@chatpanel/events/speaker-turns.js";import{diarizeApproxMB as Fe}from"./diarize-models.js";import{makeWarmTimer as V}from"./warm-timer.js";const h=16e3,ce=h,ue=3*h,Pe=2,Ne=new Set(["thank you","thanks","thank you for watching","thanks for watching","you","uh","um","hmm","hm","mm","amen","bye","okay","ok","yeah","oh","the","that","so","and","i","a","me","we","yes","no","thank you very much","subtitles by the amara.org community","you you"]);function Re(e,t){if(t>Pe*h)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?Ne.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}let s="off",w=null,g=null,M=null,A=null,y=null,v=null,E=null;function Oe(e=w||ae,t=q(e)||B()){if(P(e)==="parakeet-tdt")return D.parakeetOnDisk(e,D.parakeetDtype(t));if(P(e)==="coreml-tdt")return Q.coremlOnDisk(e);const n=Ee(ie(),...e.split("/"),"onnx");if(!Te(n))return!1;const r=Se[t]??"";try{const o=ke(n);return o.includes(`encoder_model${r}.onnx`)&&o.some(i=>i===`decoder_model_merged${r}.onnx`||i===`decoder_model${r}.onnx`)}catch{return!1}}function mt(){return s}function K(){return s==="ready"&&!!g}function pt(){return y}function ht(){return{configured:s!=="off",ok:K(),state:s,model:w,dtype:v,runtime:le(),error:M,warmMs:E?.warmMs??null}}function gt(){return!!E?.pending()}function O(){return k.size>0||s==="loading"||s==="downloading"}async function J({log:e=()=>{}}={}){if(O())return!1;E?.disarm();const t=g;if(g=null,A=null,v=null,y=null,M=null,s="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((E?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function fe(e){return e.then(t=>(t&&!O()&&E?.arm(),t))}async function de(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(P(e)==="parakeet-tdt")return ze(e,{log:t,allowDownload:n,dtype:r});if(P(e)==="coreml-tdt")return He(e,{log:t,allowDownload:n});const o=g,i=w;let l;try{l=await oe()}catch(_){return s="error",M=`engine load failed: ${_.message}`,t(`[stt] transformers.js not available (${_.message}) — dictation falls back to the browser engine`),!1}const a=(r&&r!=="auto"?r:null)||q(e)||B(),f=Oe(e,a);if(l.env.allowRemoteModels=f?!1:!!n,!f&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const p=l.env.remoteHost,d=!De(e);if(!f&&d)try{l.env.remoteHost="https://huggingface.co/"}catch{}s=f?"loading":"downloading",f||(y={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${d?", from Hugging Face":""})…`));try{const _=m=>{if(!m)return;const j=typeof m.progress=="number"?Math.round(m.progress):y?.pct??0;m.status==="progress"||m.status==="download"||m.status==="initiate"?y={model:e,file:m.file||y?.file||null,pct:j}:m.status==="done"&&m.file&&t(`[stt] fetched ${m.file}`)};let c;try{c=await l.pipeline("automatic-speech-recognition",e,{dtype:a,progress_callback:_})}catch(m){if(f||d||!n)throw m;t(`[stt] mirror fetch failed (${String(m.message).slice(0,80)}) — retrying from Hugging Face…`),l.env.remoteHost="https://huggingface.co/",l.env.allowRemoteModels=!0,c=await l.pipeline("automatic-speech-recognition",e,{dtype:a,progress_callback:_})}if(!f)try{be(e,{modelsDir:ie(),log:t})}catch(m){try{await c.dispose?.()}catch{}throw m}if(g=c,w=e,s="ready",M=null,y=null,v=a,o&&o!==c)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${a} (in-process, offline) — local dictation active`),!0}catch(_){return M=_.message,y=null,o?(g=o,w=i,s="ready"):s="error",t(`[stt] model load failed (${_.message})${o?" — keeping previous model":""}`),!1}finally{try{l.env.remoteHost=p}catch{}}}async function ze(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=g,i=w,l=D.parakeetDtype(r&&r!=="auto"?r:Ce()),u=D.parakeetOnDisk(e,l);if(!u&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;s=u?"loading":"downloading",u||(y={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const a=await D.loadRecognizer({modelId:e,dtype:l,allowDownload:n,log:t,onProgress:p=>{y={model:e,file:p.file||null,pct:typeof p.pct=="number"?p.pct:y?.pct??0}}}),f=async p=>({text:await a.transcribe(p)});if(f.__transducer=!0,f.dispose=()=>a.dispose(),g=f,w=e,s="ready",M=null,y=null,v=l,o&&o!==f)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${l} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(a){return M=a.message,y=null,o?(g=o,w=i,s="ready"):s="error",t(`[stt] model load failed (${a.message})${o?" — keeping previous model":""}`),!1}}function Ce(){return D.PARAKEET_DEFAULT_DTYPE}const me="fp16";async function He(e,{log:t=()=>{},allowDownload:n=!0}={}){const r=g,o=w,i=Q.coremlOnDisk(e);if(!i&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;s=i?"loading":"downloading",i||(y={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let l=null;const u=await Q.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:a=>{y={model:e,file:a.file||null,pct:typeof a.pct=="number"?a.pct:y?.pct??0}},onExit:a=>{g===l&&(g=null,A=null,s="error",M=a,E?.disarm(),t(`[stt] ${a} — reloads on the next dictation`))}});if(l=async a=>({text:await u.transcribe(a)}),l.__transducer=!0,l.dispose=()=>u.dispose(),g=l,w=e,s="ready",M=null,y=null,v=me,r&&r!==l)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} (Core ML on the Neural Engine, helper ${u.version}, windows ${u.windows.join("/")} s, offline) — local dictation active`),!0}catch(l){return M=l.message,y=null,r?(g=r,w=o,s="ready"):s="error",t(`[stt] model load failed (${l.message})${r?" — keeping previous model":""}`),!1}}const Ue=30;function pe({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:r=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof r=="number"&&r<=Ue||e==="download"?{allowDownload:!0}:null}function Z(e,{log:t=()=>{},warmMs:n,allowDownload:r=!0}={}){const o=pe({mode:e,onDisk:b.modelOnDisk(),ready:b.isReady(),approxMB:Fe(b.activeModel())});if(o&&b.init({allowDownload:o.allowDownload&&r!==!1,warmMs:n,onLog:t}),e==="off"||I)return;const i=pe({mode:e,onDisk:L.modelOnDisk(),ready:L.isReady(),approxMB:L.SEGMENT_MODEL_APPROX_MB});i&&L.init({allowDownload:i.allowDownload&&r!==!1,warmMs:n,onLog:t})}let I=!1;function yt(e={}){if(A&&s!=="error")return A;const t=typeof e.onLog=="function"?e.onLog:()=>{};return w=e.model||ae,I=e.segment===!1,s="loading",E=V({warmMs:e.warmMs,busy:O,log:t,unload:()=>J({log:t})}),A=fe(de(w,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype})).then(n=>(n&&Z(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),n)),A}async function wt(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(I=t.segment===!1);const r=P(e)==="parakeet-tdt"?D.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:D.PARAKEET_DEFAULT_DTYPE):P(e)==="coreml-tdt"?me:t.dtype&&t.dtype!=="auto"?t.dtype:q(e)||B();if(e===w&&K()&&v===r)return Z(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;E??=V({warmMs:t.warmMs,busy:O,log:n,unload:()=>J({log:n})});const o=await fe(de(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype}));return o&&Z(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),o}const Be=8,Ke=12e4,Xe=6e4,je=1200,ee=12,te=700,ne=.008,Ye=.002,Ge=4;function We(e){return e>0?Math.min(ne,Math.max(Ye,e*Ge)):ne}function qe(e){const t=Math.round(.1*h),n=Math.floor(e.length/t);if(n<5)return null;const r=new Float32Array(n);for(let o=0;o<n;o++)r[o]=C(e,o*t,(o+1)*t);return r.sort(),r[Math.floor(n*.1)]}const he=30,k=new Map,$=new Map;let F=Promise.resolve();function _t(){return k.size}const Qe=300,Ve=3e3;function Je(e){const t=Number(e);return Number.isFinite(t)?Math.min(Ve,Math.max(Qe,Math.round(t))):te}function Mt({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=te,interims:i=!0,remote:l=null,poll:u=!1}={}){if(k.size>=Be){const f=new Error("too many concurrent dictation sessions");throw f.code="too_many_sessions",f}const a={id:xe(),endSilenceMs:Je(o),lang:typeof e=="string"&&e?e.slice(0,12):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!t,diarize:!!n,speakerLabel:typeof r=="string"&&r?r.slice(0,40):null,diarizer:n?new b.Diarizer:null,remote:l||null,interims:i!==!1&&!l,chunks:[],samples:0,listeners:new Set,poll:u?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return k.set(a.id,a),E?.disarm(),a.diarizer&&(b.retain(),L.retain()),ge(a),{id:a.id}}function X(e){return k.get(String(e||""))||null}function Et(e,t){const n=X(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function z(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function Tt(e){const t=String(e||""),n=k.get(t);if(n)return n.poll?n.poll.splice(0):null;const r=$.get(t);return r?(clearTimeout(r.timer),$.delete(t),r.session.poll.splice(0)):null}function kt(e){return $.get(String(e||""))?.session||null}function ge(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>nt(e.id).catch(()=>{}),Xe),e.idleTimer.unref?.()}function xt(e,t){const n=X(e);if(!n||n.closed){const r=new Error("no such session");throw r.code="no_session",r}!(t instanceof Float32Array)||!t.length||(n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,ge(n),Ze(n))}function St(e){const t=X(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),F=F.then(()=>re(t).catch(()=>{})),F)}function bt(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let r=0;r<n.length;r++)n[r]=e.readFloatLE(r*4);return n}function Ze(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+je-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,F=F.then(()=>re(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function ye(e){const t=new Float32Array(e.samples);let n=0;for(const r of e.chunks)t.set(r,n),n+=r.length;return t}function Ie(e,t,n){const r=h/100,o=Math.max(0,e.length-t),i=Math.floor((e.length-o)/r),l=Math.max(1,Math.round(n/r));if(i<=l)return 0;const u=new Float32Array(i);for(let d=0;d<i;d++){let _=0;const c=o+d*r;for(let m=0;m<r;m++)_+=e[c+m]*e[c+m];u[d]=_/r}let a=-1,f=1/0,p=0;for(let d=0;d<l;d++)p+=u[d];for(let d=0;d+l<=i;d++)d>0&&(p+=u[d+l-1]-u[d-1]),p<f&&(f=p,a=d);return a<0?0:o+Math.round((a+l/2)*r)}function C(e,t=0,n=e.length){let r=0;const o=Math.max(1,n-t);for(let i=t;i<n;i++)r+=e[i]*e[i];return Math.sqrt(r/o)}function et(e,t=ne){const n=Math.round(.02*h);let r=0,o=e.length;for(let i=0;i+n<=e.length;i+=n)if(C(e,i,i+n)>=t){r=i;break}for(let i=e.length-n;i>=0;i-=n)if(C(e,i,i+n)>=t){o=i+n;break}return o>r?e.subarray(r,o):e}async function tt(e){try{const t=await oe(),n=g?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const r=e.length>h*8?e.subarray(0,h*8):e,o=await g.processor(r),i=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),l=await g.model({...o,decoder_input_ids:i});let u=null,a=-1/0;for(const[f,p]of Object.entries(n.lang_to_id)){const d=Number(l.logits.data[p]);d>a&&(a=d,u=f)}return u?u.slice(2,-2):null}catch{return null}}async function re(e,{flush:t=!1}={}){if(e.closed&&!t||!e.remote&&!K()||!e.samples)return;e.lastDecodeAt=Date.now();let n=ye(e);const r=n.length,o=Math.max(0,(e.pushed||0)-e.samples),i=Math.round((e.endSilenceMs||te)/1e3*h),l=qe(n);l!==null&&(e.noiseFloor==null||l<e.noiseFloor)&&(e.noiseFloor=l);const u=We(e.noiseFloor),a=n.length>i&&C(n,n.length-i)<u;if(C(n)<u){n.length>h*5&&(e.chunks=[n.subarray(n.length-h)],e.samples=h);return}if(!e.interims&&!t&&!a&&n.length<ee*h)return;let f=null;if(!t&&!a&&r>=ee*h&&r<he*h){const c=Ie(n,3*h,Math.round(.2*h));c>0&&c<n.length&&(f=n.subarray(c),n=n.subarray(0,c))}if(!e.remote&&!e.lang&&!e.langTried&&!se(w)&&!g?.__transducer&&n.length>=h){e.langTried=!0;const c=await tt(n);c&&(e.lang=c,z(e,{type:"language",lang:c}))}let p="";try{if(e.remote)p=(await e.remote.transcribe(n,{lang:e.lang})).text;else{const c=se(w)?{}:{language:e.lang||void 0,task:"transcribe"},m=await g(n,c);p=String(m?.text||"").trim()}}catch(c){z(e,{type:"error",code:"decode_failed",message:c.message,fatal:!1});return}if(!p)return;const d=r>=ee*h,_=r>=he*h;if(t||a||d||_){const c=t?"flush":a?"silence":_?"overflow":"length",m=c==="flush"||c==="silence",j=e.samples-r,H=[];f&&H.push(f),j>0&&H.push(ye(e).subarray(r)),e.chunks=H,e.samples=H.reduce((T,x)=>T+x.length,0),e.lastInterim="";const Y=et(n,u);if(Re(p,Y?Y.length:0))return;let N=null,G=null;if(e.diarizer)try{const T=e.speakerLabel?null:await L.spans(n),x=T?Le(T):[];if(x.length){const R=new Map;for(const{local:S}of ve(x)){const U=$e(n,x,S),we=U.length?await b.embed(U):null,_e=U.length<ce,Me=U.length<ue;R.set(S,e.diarizer.assign(we,{pinnedLabel:null,weak:_e,thin:Me}))}const W=Math.round(o/h*1e3);G=x.map(S=>({startMs:W+Math.round(S.start*1e3),durationMs:Math.round((S.end-S.start)*1e3),speaker:R.get(S.local)})).filter(S=>S.speaker),N=R.get(Ae(x))||null}}catch{}if(e.diarizer&&!N)try{const T=Y,x=T?await b.embed(T):null,R=!!T&&T.length<ce,W=!!T&&T.length<ue;N=e.diarizer.assign(x,{pinnedLabel:e.speakerLabel,weak:R,thin:W})}catch{}z(e,{type:"final",text:p,reason:c,endOfTurn:m,durationMs:Math.round(n.length/h*1e3),startMs:Math.round(o/h*1e3),...N?{speaker:N}:{},...G?.length?{turns:G}:{}})}else p!==e.lastInterim&&(e.lastInterim=p,z(e,{type:"interim",text:p}))}async function nt(e){const t=X(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(F=F.then(()=>re(t,{flush:!0}).catch(()=>{})))}finally{if(z(t,{type:"end"}),t.listeners.clear(),k.delete(t.id),t.poll){const n=setTimeout(()=>$.delete(t.id),Ke);n.unref?.(),$.set(t.id,{session:t,timer:n})}t.diarizer&&(b.release(),L.release()),k.size===0&&K()&&E?.arm()}return!0}function Dt(){for(const e of k.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);k.clear();for(const e of $.values())clearTimeout(e.timer);$.clear(),E?.disarm(),E=null,s="off",w=null,g=null,M=null,A=null,y=null}function Lt(e,t="test/fake",{warmMs:n=null,dtype:r=null}={}){g=e,w=t,s=e?"ready":"off",v=r,n!==null&&(E=V({warmMs:n,busy:O,unload:()=>J()}),e&&E.arm())}export{Ue as AUTO_FETCH_MAX_MB,h as SAMPLE_RATE,ue as THIN_SPEAKER_SAMPLES,ce as WEAK_SPEAKER_SAMPLES,Dt as _reset,Lt as _setPipeForTest,Je as clampEndSilence,Mt as createSession,St as decodeNow,Tt as drainEvents,nt as endSession,kt as endedSession,X as getSession,ht as health,yt as init,K as isReady,Re as looksHallucinated,Oe as modelOnDisk,qe as noiseFloorOf,pt as progress,xt as pushAudio,Ie as quietestCut,B as runtimeDtype,le as runtimeName,_t as sessionCount,wt as setModel,We as silenceGate,pe as speakerPlan,mt as state,Et as subscribe,bt as toFloat32,J as unload,gt as warmPending};
1
+ import{join as Qe}from"node:path";import{deflateSync as Je}from"node:zlib";import ve from"node:os";import{existsSync as Ze,readdirSync as et}from"node:fs";import{randomUUID as tt}from"node:crypto";import{ensureLib as Ne,modelRoot as Oe}from"./ner-engine.js";import{runtimeDtype as ie,runtimeName as Pe,DTYPE_SUFFIX as nt}from"./model-runtime.js";import{verifyModelWeights as ot}from"./model-integrity.js";import{DEFAULT_STT_MODEL as Re,isEnglishOnly as me,sttModelDtype as he,isKnownSttModel as rt,sttModelEngine as z}from"./stt-models.js";import*as B from"./parakeet-engine.js";import*as _e from"./coreml-stt-engine.js";import*as ne from"./indic-engine.js";import*as U from"./diarize-engine.js";import*as Y from"./segment-engine.js";import{turnsFromSpans as lt,mainLocal as at,timeByLocal as st,audioOfLocal as it}from"@chatpanel/events/speaker-turns.js";import{diarizeApproxMB as ct}from"./diarize-models.js";import*as oe from"./translate-engine.js";import*as Z from"./indictrans-engine.js";import{rawOrtAvailable as ut}from"./ort.js";import*as R from"./vad-engine.js";import*as ee from"./echo-pair.js";import{mostlyEcho as ft}from"./aec-engine.js";import{pickSegmentLanguage as dt,detectTextLanguage as gt,needsTranslation as pt,localTranslatable as mt,normalizeLanguages as ht,normalizeLanguage as _t,decodeLanguages as wt,lineLanguage as yt,autoCandidates as Mt,AUTO_LEARN_CONFIDENCE as Tt,AUTO_LEARN_SECONDS as St,ANY_LANGUAGE_CONFIDENCE as Et,AUTO_LANGUAGES as Lt}from"@chatpanel/events/speech-language.js";import{makeWarmTimer as we}from"./warm-timer.js";const p=16e3,Fe=p,Ce=3*p,At=2,xt=new Set(["thank you","thanks","thank you for watching","thanks for watching","you","uh","um","hmm","hm","mm","amen","bye","okay","ok","yeah","oh","the","that","so","and","i","a","me","we","yes","no","thank you very much","subtitles by the amara.org community","you you"]);function bt(e,t){if(t>At*p)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?xt.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}const kt=12,ye=3;function Dt(e){const t=String(e||"").split(/\s+/).filter(Boolean);if(t.length<ye)return{text:String(e||"").trim(),removed:0,total:t.length};const n=l=>l.toLowerCase().replace(/[^\p{L}\p{N}']/gu,""),o=[];let r=0;for(let l=0;l<t.length;){let i=0,s=0;for(let a=1;a<=kt&&l+a*ye<=t.length;a++){let c=1;for(;l+(c+1)*a<=t.length&&t.slice(l+c*a,l+(c+1)*a).every((u,g)=>n(u)===n(t[l+g]));)c++;c>=ye&&(c-1)*a>i&&(i=(c-1)*a,s=a)}i?(o.push(...t.slice(l,l+s)),r+=i,l+=s+i):(o.push(t[l]),l++)}return{text:o.join(" "),removed:r,total:t.length}}const vt=.6,$e=2.4;function He(e){const t=Buffer.from(String(e||""),"utf8");return t.length<40?1:t.length/Je(t).length}function Nt(e){return String(e||"").replace(/([^\d\s]{1,8}?)\1{4,}/gu,"$1")}function Ot({cores:e=ve.availableParallelism?.()??ve.cpus().length,env:t=process.env}={}){const n=Number(t.CHATPANEL_STT_THREADS);return Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(4,Math.floor(e/2)))}function re(e){return{intraOpNumThreads:Ot(e),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}const Pt=.12,ze=.8,Ue=.15,Rt=.999,Ft=2.5;function ce(e={}){return(e.en??0)>=Ue?"en":Object.entries(e).sort((t,n)=>n[1]-t[1])[0]?.[0]||null}function Ct(e,t=[]){const n=[];return e.forEach((o,r)=>{const l=t[r]??o.lang,i=n[n.length-1];i&&i.lang===l?i.to=o.to:n.push({from:o.from,to:o.to,lang:l})}),n}function $t(e,{base:t=null,rate:n=p}={}){const o=e||[],r=a=>{const[c,u]=Object.entries(a.scores||{}).sort((g,A)=>A[1]-g[1])[0]||[];return c&&c!=="en"&&u>=Rt?c:null},l=new Array(o.length).fill(null);for(let a=0;a<o.length;){const c=r(o[a]);let u=a+1;if(c)for(;u<o.length&&r(o[u])===c;)u++;if(c&&(o[u-1].to-o[a].from)/n>=Ft)for(let g=a;g<u;g++)l[g]=c;a=u}const i=[];let s=t;return o.forEach((a,c)=>{l[c]?s=l[c]:s!=="en"&&(a.scores?.en??0)>=Ue&&(s="en");const u=i[i.length-1];u&&u.lang===s?u.to=a.to:i.push({from:a.from,to:a.to,lang:s})}),i}function Ht(e,t,{frame:n=Math.round(.03*p),minPause:o=Pt*p,minPiece:r=ze*p}={}){const l=[];let i=0,s=-1;for(let a=0;a+n<=e;a+=n){const c=t(a,a+n)===!1;if(c&&s<0&&(s=a),(!c||a+2*n>e)&&s>=0){const u=c?a+n:a,g=Math.round((s+u)/2);u-s>=o&&g-i>=r&&e-g>=r&&(l.push(g),i=g),s=-1}}return l}const zt=.12;function Ut(e,t=Math.round(.03*p)){const n=Math.floor(e.length/t);if(n<3)return 0;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=Q(e,r*t,(r+1)*t);return o.sort(),Math.max(1e-4,o[Math.floor(n*.9)]*zt)}let m="off",E=null,h=null,D=null,q=null,T=null,X=null,N=null;function Gt(e=E||Re,t=he(e)||ie()){if(z(e)==="parakeet-tdt")return B.parakeetOnDisk(e,B.parakeetDtype(t));if(z(e)==="coreml-tdt")return _e.coremlOnDisk(e);if(z(e)==="indic-canary")return ne.indicOnDisk();const n=Qe(Oe(),...e.split("/"),"onnx");if(!Ze(n))return!1;const o=nt[t]??"";try{const r=et(n);return r.includes(`encoder_model${o}.onnx`)&&r.some(l=>l===`decoder_model_merged${o}.onnx`||l===`decoder_model${o}.onnx`)}catch{return!1}}function An(){return m}function ue(){return m==="ready"&&!!h}function xn(){return T}function bn(){return{configured:m!=="off",ok:ue(),state:m,model:E,dtype:X,runtime:Pe(),error:D,warmMs:N?.warmMs??null,vad:R.state()}}function kn(){return!!N?.pending()}function le(){return C.size>0||m==="loading"||m==="downloading"}async function Me({log:e=()=>{}}={}){if(le())return!1;N?.disarm();const t=h;if(h=null,q=null,X=null,T=null,D=null,m="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((N?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function Ge(e){return e.then(t=>(t&&!le()&&N?.arm(),t))}async function je(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null,licenseAccepted:r=null}={}){if(z(e)==="parakeet-tdt")return jt(e,{log:t,allowDownload:n,dtype:o});if(z(e)==="coreml-tdt")return Xt(e,{log:t,allowDownload:n});if(z(e)==="indic-canary")return Kt(e,{log:t,allowDownload:n,licenseAccepted:r});const l=h,i=E;let s;try{s=await Ne()}catch(L){return m="error",D=`engine load failed: ${L.message}`,t(`[stt] transformers.js not available (${L.message}) — dictation falls back to the browser engine`),!1}const c=(o&&o!=="auto"?o:null)||he(e)||ie(),u=Gt(e,c);if(s.env.allowRemoteModels=u?!1:!!n,!u&&!n)return m="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const g=s.env.remoteHost,A=!rt(e);if(!u&&A)try{s.env.remoteHost="https://huggingface.co/"}catch{}m=u?"loading":"downloading",u||(T={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${A?", from Hugging Face":""})…`));try{const L=d=>{if(!d)return;const J=typeof d.progress=="number"?Math.round(d.progress):T?.pct??0;d.status==="progress"||d.status==="download"||d.status==="initiate"?T={model:e,file:d.file||T?.file||null,pct:J}:d.status==="done"&&d.file&&t(`[stt] fetched ${d.file}`)};let w;try{w=await s.pipeline("automatic-speech-recognition",e,{dtype:c,progress_callback:L,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:re()}})}catch(d){if(u||A||!n)throw d;t(`[stt] mirror fetch failed (${String(d.message).slice(0,80)}) — retrying from Hugging Face…`),s.env.remoteHost="https://huggingface.co/",s.env.allowRemoteModels=!0,w=await s.pipeline("automatic-speech-recognition",e,{dtype:c,progress_callback:L,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:re()}})}if(!u)try{ot(e,{modelsDir:Oe(),log:t})}catch(d){try{await w.dispose?.()}catch{}throw d}if(h=w,E=e,m="ready",D=null,T=null,X=c,l&&l!==w)try{await l.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${c} (in-process, offline) — local dictation active`),!0}catch(L){return D=L.message,T=null,l?(h=l,E=i,m="ready"):m="error",t(`[stt] model load failed (${L.message})${l?" — keeping previous model":""}`),!1}finally{try{s.env.remoteHost=g}catch{}}}async function jt(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null}={}){const r=h,l=E,i=B.parakeetDtype(o&&o!=="auto"?o:Bt()),s=B.parakeetOnDisk(e,i);if(!s&&!n)return m="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;m=s?"loading":"downloading",s||(T={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const a=await B.loadRecognizer({modelId:e,dtype:i,allowDownload:n,log:t,sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:re(),onProgress:u=>{T={model:e,file:u.file||null,pct:typeof u.pct=="number"?u.pct:T?.pct??0}}}),c=async u=>({text:await a.transcribe(u)});if(c.__transducer=!0,c.dispose=()=>a.dispose(),h=c,E=e,m="ready",D=null,T=null,X=i,r&&r!==c)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(a){return D=a.message,T=null,r?(h=r,E=l,m="ready"):m="error",t(`[stt] model load failed (${a.message})${r?" — keeping previous model":""}`),!1}}function Bt(){return B.PARAKEET_DEFAULT_DTYPE}const Be="fp16";async function Xt(e,{log:t=()=>{},allowDownload:n=!0}={}){const o=h,r=E,l=_e.coremlOnDisk(e);if(!l&&!n)return m="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;m=l?"loading":"downloading",l||(T={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let i=null;const s=await _e.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:a=>{T={model:e,file:a.file||null,pct:typeof a.pct=="number"?a.pct:T?.pct??0}},onExit:a=>{h===i&&(h=null,q=null,m="error",D=a,N?.disarm(),t(`[stt] ${a} — reloads on the next dictation`))}});if(i=async a=>({text:await s.transcribe(a)}),i.__transducer=!0,i.dispose=()=>s.dispose(),h=i,E=e,m="ready",D=null,T=null,X=Be,o&&o!==i)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} (Core ML on the Neural Engine, helper ${s.version}, windows ${s.windows.join("/")} s, offline) — local dictation active`),!0}catch(i){return D=i.message,T=null,o?(h=o,E=r,m="ready"):m="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}async function Kt(e,{log:t=()=>{},allowDownload:n=!0,licenseAccepted:o=null}={}){const r=h,l=E,i=ne.indicOnDisk();if(!i&&!n)return m="error",D="model not on disk and downloads disabled",!1;m=i?"loading":"downloading",i||(T={model:e,file:null,pct:0},t(`[stt] downloading ${e} (one-time, ~1.5 GB, from dl.chatpanel.net)…`));try{i||await ne.ensureIndicFiles({licenseAccepted:o,log:t,onProgress:c=>{T={model:e,file:c.file,pct:c.pct}}});const s=await ne.loadRecognizer({sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:re(),log:t}),a=async(c,u={})=>s.transcribe(c,u);if(a.identify=(c,u)=>s.identify(c,u),a.__transducer=!0,a.__indic=!0,a.dispose=()=>s.dispose(),h=a,E=e,m="ready",D=null,T=null,X="int8",r&&r!==a)try{await r.dispose?.()}catch{}return t(`[stt] ready — ${e} (Indic-Transcribe, int8, in-process, offline) — ${ne.INDIC_LICENSE.attribution}`),!0}catch(s){return D=s.message,T=null,r?(h=r,E=l,m="ready"):m="error",t(`[stt] model load failed (${s.message})${r?" — keeping previous model":""}`),!1}}const Wt=30;function Xe({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:o=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof o=="number"&&o<=Wt||e==="download"?{allowDownload:!0}:null}function Te(e,{log:t=()=>{},warmMs:n,allowDownload:o=!0}={}){const r=Xe({mode:e,onDisk:U.modelOnDisk(),ready:U.isReady(),approxMB:ct(U.activeModel())});if(r&&U.init({allowDownload:r.allowDownload&&o!==!1,warmMs:n,onLog:t}),e==="off"||Se)return;const l=Xe({mode:e,onDisk:Y.modelOnDisk(),ready:Y.isReady(),approxMB:Y.SEGMENT_MODEL_APPROX_MB});l&&Y.init({allowDownload:l.allowDownload&&o!==!1,warmMs:n,onLog:t})}let Se=!1,Ee=null;function Le(e={},{log:t=()=>{}}={}){e.vad!==!1&&(Ee={vad:e.vad,allowDownload:e.allowDownload,warmMs:e.warmMs},(R.state()==="off"||R.state()==="error")&&R.init({allowDownload:e.allowDownload!==!1,warmMs:e.warmMs,onLog:t}))}function Dn(e={}){if(q&&m!=="error")return q;const t=typeof e.onLog=="function"?e.onLog:()=>{};return E=e.model||Re,Se=e.segment===!1,m="loading",N=we({warmMs:e.warmMs,busy:le,log:t,unload:()=>Me({log:t})}),q=Ge(je(E,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype,licenseAccepted:e.licenseAccepted||null})).then(n=>(n&&(Te(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),Le(e,{log:t})),n)),q}async function vn(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(Se=t.segment===!1);const o=z(e)==="parakeet-tdt"?B.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:B.PARAKEET_DEFAULT_DTYPE):z(e)==="coreml-tdt"?Be:z(e)==="indic-canary"?"int8":t.dtype&&t.dtype!=="auto"?t.dtype:he(e)||ie();if(e===E&&ue()&&X===o)return Te(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;N??=we({warmMs:t.warmMs,busy:le,log:n,unload:()=>Me({log:n})});const r=await Ge(je(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype,licenseAccepted:t.licenseAccepted||null}));return r&&(Te(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),Le(t,{log:n})),r}const Yt=8,qt=12e4,It=6e4,Vt=1200,fe=12,Ae=700,xe=.008,Qt=.002,Jt=4;function Zt(e){return e>0?Math.min(xe,Math.max(Qt,e*Jt)):xe}function en(e){const t=Math.round(.1*p),n=Math.floor(e.length/t);if(n<5)return null;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=Q(e,r*t,(r+1)*t);return o.sort(),o[Math.floor(n*.1)]}const Ke=30,tn=15e3,C=new Map,I=new Map;let V=Promise.resolve();function Nn(){return C.size}const nn=300,on=3e3;function rn(e){const t=Number(e);return Number.isFinite(t)?Math.min(on,Math.max(nn,Math.round(t))):Ae}function On({lang:e,langs:t=null,translateTo:n=null,translateLoad:o=null,echo:r=null,redact:l=!1,diarize:i=!1,speakerLabel:s=null,endSilenceMs:a=Ae,interims:c=!0,remote:u=null,poll:g=!1}={}){if(C.size>=Yt){const d=new Error("too many concurrent dictation sessions");throw d.code="too_many_sessions",d}const A=Array.isArray(t)?ht(t):null,L=typeof e=="string"&&e?e.slice(0,12):null,w={id:tt(),endSilenceMs:rn(a),lang:A?A.length===1?A[0]:A.length?null:L:L,langs:A,lastLang:null,lastDecoded:null,learned:new Set,translateTo:_t(n)||null,translateLoad:o||{},translations:Promise.resolve(),echo:r&&typeof r=="object"?ee.join(r.group,r.role):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!l,diarize:!!i,speakerLabel:typeof s=="string"&&s?s.slice(0,40):null,diarizer:i?new U.Diarizer:null,remote:u||null,interims:c!==!1&&!u,chunks:[],samples:0,listeners:new Set,poll:g?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return C.set(w.id,w),N?.disarm(),w.diarizer&&(U.retain(),Y.retain()),w.translateTo&&(oe.retain(),Z.retain()),R.retain(),Ee&&(R.state()==="off"||R.state()==="error")&&Le(Ee),We(w),{id:w.id}}function de(e){return C.get(String(e||""))||null}function Pn(e,t){const n=de(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function K(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function Rn(e){const t=String(e||""),n=C.get(t);if(n)return n.poll?n.poll.splice(0):null;const o=I.get(t);return o?(clearTimeout(o.timer),I.delete(t),o.session.poll.splice(0)):null}function Fn(e){return I.get(String(e||""))?.session||null}function We(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>cn(e.id).catch(()=>{}),It),e.idleTimer.unref?.()}function Cn(e,t){const n=de(e);if(!n||n.closed){const o=new Error("no such session");throw o.code="no_session",o}if(!(!(t instanceof Float32Array)||!t.length)){if(We(n),n.echo?.role==="mic"){ee.pushMic(n.echo,t),Ye(n);return}n.echo?.role==="reference"&&ee.pushReference(n.echo,t),n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,Ye(n)}}function $n(e){const t=de(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),V=V.then(()=>be(t).catch(()=>{})),V)}function Hn(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let o=0;o<n.length;o++)n[o]=e.readFloatLE(o*4);return n}function Ye(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+Vt-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,V=V.then(()=>be(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function qe(e){const t=new Float32Array(e.samples);let n=0;for(const o of e.chunks)t.set(o,n),n+=o.length;return t}function ln(e,t,n){const o=p/100,r=Math.max(0,e.length-t),l=Math.floor((e.length-r)/o),i=Math.max(1,Math.round(n/o));if(l<=i)return 0;const s=new Float32Array(l);for(let g=0;g<l;g++){let A=0;const L=r+g*o;for(let w=0;w<o;w++)A+=e[L+w]*e[L+w];s[g]=A/o}let a=-1,c=1/0,u=0;for(let g=0;g<i;g++)u+=s[g];for(let g=0;g+i<=l;g++)g>0&&(u+=s[g+i-1]-s[g-1]),u<c&&(c=u,a=g);return a<0?0:r+Math.round((a+i/2)*o)}function Q(e,t=0,n=e.length){let o=0;const r=Math.max(1,n-t);for(let l=t;l<n;l++)o+=e[l]*e[l];return Math.sqrt(o/r)}function an(e,t=xe){const n=Math.round(.02*p);let o=0,r=e.length;for(let l=0;l+n<=e.length;l+=n)if(Q(e,l,l+n)>=t){o=l;break}for(let l=e.length-n;l>=0;l-=n)if(Q(e,l,l+n)>=t){r=l+n;break}return r>o?e.subarray(o,r):e}async function Ie(e){try{const t=await Ne(),n=h?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const o=e.length>p*8?e.subarray(0,p*8):e,r=await h.processor(o),l=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),i=await h.model({...r,decoder_input_ids:l}),s={};for(const[a,c]of Object.entries(n.lang_to_id))s[a.slice(2,-2)]=Number(i.logits.data[c]);return s}catch{return null}}async function sn(e){const t=await Ie(e);if(!t)return null;let n=null,o=-1/0;for(const[r,l]of Object.entries(t))l>o&&(o=l,n=r);return n}async function be(e,{flush:t=!1}={}){if(e.closed&&!t)return;if(e.echo?.role==="mic"){const f=await ee.drain(e.echo,{force:t});f.length&&(e.chunks.push(f),e.samples+=f.length,e.pushed+=f.length)}if(!e.remote&&!ue()||!e.samples)return;e.lastDecodeAt=Date.now();let n=qe(e);const o=n.length,r=Math.max(0,(e.pushed||0)-e.samples),l=Math.round((e.endSilenceMs||Ae)/1e3*p),i=en(n);i!==null&&(e.noiseFloor==null||i<e.noiseFloor)&&(e.noiseFloor=i);const s=Zt(e.noiseFloor);let a=null,c=null;R.isReady()&&(e.vad||=R.createStream(),await e.vad.advance(n,r)&&(a=e.vad.speechIn(r,r+n.length,R.ONSET),n.length>l&&(c=e.vad.speechIn(r+n.length-l,r+n.length,R.OFFSET))));const u=n.length>l&&(c!==null?!c:Q(n,n.length-l)<s);if(a===!1||a===null&&Q(n)<s){n.length>p*5&&(e.chunks=[n.subarray(n.length-p)],e.samples=p);return}if(!e.interims&&!t&&!u&&n.length<fe*p)return;let g=null;if(!t&&!u&&o>=fe*p&&o<Ke*p){const f=ln(n,3*p,Math.round(.2*p));f>0&&f<n.length&&(g=n.subarray(f),n=n.subarray(0,f))}const A=!e.remote&&!me(E)&&!h?.__transducer;if(A&&!e.langs&&!e.lang&&!e.langTried&&n.length>=p){e.langTried=!0;const f=await sn(n);f&&(e.lang=f,K(e,{type:"language",lang:f}))}const L=t||u||o>=fe*p;let w=e.lang;if(A&&e.langs&&!e.lang){const f=e.langs.length>0,O=f?wt(e.langs):Mt([...e.learned]);if(O.length===1)w=O[0];else if(w=O.includes(e.lastDecoded)?e.lastDecoded:null,(L||!w)&&n.length>=p/2){const b=await Ie(n);if(b){const M=dt({scores:b,allowed:O,seconds:n.length/p,last:e.lastDecoded});w=!f&&!M.inherited&&M.confidence<Et?e.lastDecoded||"en":M.lang,!f&&L&&!M.inherited&&M.confidence>=Tt&&n.length>=St*p&&e.learned.add(M.lang)}}L&&w&&(e.lastDecoded=w)}let d="",J=null,$=null,ge=null;try{if(e.remote){const f=await e.remote.transcribe(n,{lang:e.lang,langs:e.langs});d=f.text,ge=f.lang||null}else{const f=h.__indic?e.langs?.length?{langs:[...new Set([...e.langs,"en"])],last:e.lastLang,choose:ce}:e.lang?{lang:e.lang}:{langs:[...Lt],last:e.lastLang,choose:ce}:me(E)?{}:{language:w||void 0,task:"transcribe"},O=h.__indic&&h.identify&&L&&f.langs&&n.length>=2*ze*p?Ht(n.length,(M=>(_,v)=>Q(n,_,v)>=M)(Ut(n))):[];let b=null;if(O.length){const M=await h.identify(n,{langs:f.langs}),_=[0,...O,n.length],v=[];for(let k=0;k+1<_.length;k++){const S=await h.identify(n.subarray(_[k],_[k+1]),{langs:f.langs});v.push({from:_[k],to:_[k+1],scores:S?.scores||{}})}if(b=$t(v,{base:M?.scores?ce(M.scores):null}),b.length>1){const k=[];for(let S=0;S<b.length;S++){const G=b[S],te=G.lang&&G.lang!=="en"&&(b[S-1]?.lang==="en"||b[S+1]?.lang==="en");k.push(te?ce((await h.identify(n.subarray(G.from,G.to),{langs:f.langs}))?.scores||{}):G.lang)}b=Ct(b,k)}b.length<2&&(b=null)}if(b){$=[];for(const _ of b){const v=await h(n.subarray(_.from,_.to),_.lang?{lang:_.lang}:{...f}),k=String(v?.text||"").trim(),S=v?.lang||_.lang||null;k&&$.push({text:k,lang:S,from:_.from,to:_.to}),S&&(f.last=S)}d=$.map(_=>_.text).join(" ");const M=new Map;for(const _ of $)_.lang&&M.set(_.lang,(M.get(_.lang)||0)+(_.to-_.from));J=[...M].sort((_,v)=>v[1]-_[1])[0]?.[0]||null,($.length<2||M.size<2)&&($=null)}else{const M=await h(n,f);d=String(M?.text||"").trim(),h.__indic&&(J=M?.lang||null)}}}catch(f){K(e,{type:"error",code:"decode_failed",message:f.message,fatal:!1});return}if(!d)return;{const f=Dt(d);if(f.removed&&f.removed/f.total>=vt&&f.total>=12?d="":d=f.text,d&&He(d)>$e){const O=Nt(d);d=O.replace(/[\s\p{P}]/gu,"").length<12||He(O)>$e?"":O}if(!d)return}const Ve=o>=fe*p,ke=o>=Ke*p;if(t||u||Ve||ke){const f=t?"flush":u?"silence":ke?"overflow":"length",O=f==="flush"||f==="silence",b=e.samples-o,M=[];g&&M.push(g),b>0&&M.push(qe(e).subarray(o)),e.chunks=M,e.samples=M.reduce((y,x)=>y+x.length,0),e.lastInterim="";const _=an(n,s);if(bt(d,_?_.length:0)||e.echo?.role==="mic"&&ft(ee.verdict(e.echo,r,r+n.length)))return;let v=null,k=null;if(e.diarizer)try{const y=e.speakerLabel?null:await Y.spans(n),x=y?lt(y):[];if(x.length){const P=new Map;for(const{local:F}of st(x)){const H=it(n,x,F),ae=H.length?await U.embed(H):null,se=H.length<Fe,W=H.length<Ce;P.set(F,e.diarizer.assign(ae,{pinnedLabel:null,weak:se,thin:W}))}const j=Math.round(r/p*1e3);k=x.map(F=>({startMs:j+Math.round(F.start*1e3),durationMs:Math.round((F.end-F.start)*1e3),speaker:P.get(F.local)})).filter(F=>F.speaker),v=P.get(at(x))||null}}catch{}if(e.diarizer&&!v)try{const y=_,x=y?await U.embed(y):null,P=!!y&&y.length<Fe,j=!!y&&y.length<Ce;v=e.diarizer.assign(x,{pinnedLabel:e.speakerLabel,weak:P,thin:j})}catch{}let S=null;(e.langs||e.translateTo)&&(J?S=J:ge?S=ge:me(E)&&!e.remote?S="en":A?S=yt(d,w||e.lang)||null:S=e.lang||gt(d,{allowed:e.langs||[],last:e.lastLang}).lang,S&&S!==e.lastLang&&(e.lastLang=S,K(e,{type:"language",lang:S})));const G=Math.round(r/p*1e3),te=$&&(e.langs||e.translateTo)?$.map((y,x)=>({text:y.text,lang:y.lang,startMs:G+Math.round(y.from/p*1e3),durationMs:Math.round((y.to-y.from)/p*1e3),last:x===$.length-1})):[{text:d,lang:S,startMs:G,durationMs:Math.round(n.length/p*1e3),last:!0}];for(const y of te){te.length>1&&y.lang&&y.lang!==e.lastLang&&(e.lastLang=y.lang,K(e,{type:"language",lang:y.lang}));const{text:x,lang:P,startMs:j}=y,F=(x.match(new RegExp("\\p{Script=Latin}","gu"))||[]).length/Math.max(1,(x.match(new RegExp("\\p{L}","gu"))||[]).length),H=Z.indictransLanguage(P)&&F<.5&&Z.state()!=="error"&&ut(),ae=!!e.translateTo&&pt(P,e.translateTo)&&(H||mt(x,P)&&oe.state()!=="error"),se=te.length>1&&k?k.filter(W=>W.startMs<j+y.durationMs&&W.startMs+W.durationMs>j):k;if(K(e,{type:"final",text:x,reason:f,endOfTurn:y.last?O:!1,durationMs:y.durationMs,startMs:j,...P?{lang:P}:{},...ae?{translating:!0}:{},...v?{speaker:v}:{},...se?.length?{turns:se}:{}}),ae){const W=e.translateTo,pe=H?Z:oe;pe.state()==="off"&&pe.init({...e.translateLoad,...H?{sessionOptions:re()}:{}}),e.translations=e.translations.then(async()=>{await pe.ready();const De=H?await Z.translate(x,P):await oe.translate(x);K(e,{type:"translation",startMs:j,lang:P,to:W,text:De||null,...De?{}:{failed:!0}})}).catch(()=>{})}}}else d!==e.lastInterim&&(e.lastInterim=d,K(e,{type:"interim",text:d}))}async function cn(e){const t=de(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(V=V.then(()=>be(t,{flush:!0}).catch(()=>{}))),await Promise.race([t.translations,new Promise(n=>setTimeout(n,tn).unref?.())])}finally{if(K(t,{type:"end"}),t.listeners.clear(),C.delete(t.id),t.poll){const n=setTimeout(()=>I.delete(t.id),qt);n.unref?.(),I.set(t.id,{session:t,timer:n})}t.diarizer&&(U.release(),Y.release()),t.translateTo&&(oe.release(),Z.release()),R.release(),ee.leave(t.echo),C.size===0&&ue()&&N?.arm()}return!0}function zn(){for(const e of C.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);C.clear();for(const e of I.values())clearTimeout(e.timer);I.clear(),N?.disarm(),N=null,m="off",E=null,h=null,D=null,q=null,T=null}function Un(e,t="test/fake",{warmMs:n=null,dtype:o=null}={}){h=e,E=t,m=e?"ready":"off",X=o,n!==null&&(N=we({warmMs:n,busy:le,unload:()=>Me()}),e&&N.arm())}export{Wt as AUTO_FETCH_MAX_MB,$e as COMPRESSION_LIMIT,Rt as FROM_ENGLISH,Ft as FROM_ENGLISH_RUN_S,vt as LOOP_DROP,zt as PAUSE_SHARE,ze as PIECE_MIN_S,Pt as PIECE_PAUSE_S,p as SAMPLE_RATE,Ce as THIN_SPEAKER_SAMPLES,Ue as TO_ENGLISH,Fe as WEAK_SPEAKER_SAMPLES,zn as _reset,Un as _setPipeForTest,rn as clampEndSilence,Dt as collapseLoops,Nt as collapseRuns,He as compressionRatio,On as createSession,$n as decodeNow,Rn as drainEvents,cn as endSession,Fn as endedSession,de as getSession,bn as health,Dn as init,ue as isReady,$t as languageGroups,bt as looksHallucinated,Gt as modelOnDisk,en as noiseFloorOf,Ht as pauseCuts,Ut as pauseLevel,xn as progress,Cn as pushAudio,ln as quietestCut,Ct as relabelGroups,ie as runtimeDtype,Pe as runtimeName,ce as segmentLanguage,Nn as sessionCount,vn as setModel,Zt as silenceGate,Xe as speakerPlan,An as state,re as sttSessionOptions,Ot as sttThreads,Pn as subscribe,Hn as toFloat32,Me as unload,kn as warmPending};
package/src/stt-models.js CHANGED
@@ -1 +1 @@
1
- const i="istupakov/parakeet-tdt-0.6b-v3-onnx",a=[{id:"onnx-community/whisper-tiny.en",label:"Tiny (English)",lang:"English",tier:"light",approxMB:150,ramMB:400,note:"Fastest, lightest. English only — great for quick dictation on any machine."},{id:"onnx-community/whisper-base",label:"Base (multilingual)",lang:"99 languages (auto-detected)",tier:"balanced",approxMB:300,ramMB:700,note:"Small and quick to install. Detects the spoken language automatically; good accuracy at real-time speed."},{id:"onnx-community/whisper-small",label:"Small (multilingual)",lang:"99 languages (auto-detected)",tier:"accurate",approxMB:950,ramMB:1600,note:"Noticeably more accurate; needs a faster CPU to keep up in real time."},{id:"onnx-community/whisper-large-v3-turbo",label:"Large v3 Turbo (multilingual)",lang:"99 languages (auto-detected)",tier:"max",approxMB:1600,ramMB:3200,note:"Best accuracy. For powerful machines; use the native (npm) gateway for speed."},{id:"istupakov/parakeet-tdt-0.6b-v3-onnx",label:"Parakeet TDT 0.6B v3 (multilingual, fast)",lang:"25 European languages (auto-detected)",tier:"accurate",engine:"parakeet-tdt",recommended:!0,approxMB:690,ramMB:1600,note:"Recommended — NVIDIA Parakeet transducer. Several× faster than Whisper at similar or better accuracy, English + 24 EU languages. One-time download; best on the native (npm) gateway."},{id:"ConwayResearch/Underdog-Bark-3.0",label:"Parakeet TDT 0.6B v3 for the Neural Engine (English)",lang:"English",tier:"light",engine:"coreml-tdt",platforms:["darwin-arm64"],approxMB:200,ramMB:500,note:"The same Parakeet model, repacked for the Apple Neural Engine: a 200 MB download and the fastest dictation on a Mac. English only. Needs the Apple helper."}],s="istupakov/parakeet-tdt-0.6b-v3-onnx";function p(e){return n(e)?.engine||"whisper"}function u(e,{platform:t=process.platform,arch:r=process.arch,helper:l=!1}={}){return Array.isArray(e?.platforms)&&!e.platforms.includes(`${t}-${r}`)?"Needs a Mac with Apple Silicon.":e?.engine==="coreml-tdt"&&!l?"Needs the Apple helper — Install it on the Apple on-device row (Runtime).":null}function d(e){return a.some(t=>t.id===e)}function n(e){return a.find(t=>t.id===e)||null}function c(e){return/\.en$/.test(String(e||""))}function m(e){return n(e)?.dtype||null}function g(e){const t=String(e||"");return/^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(t)&&!t.includes("..")}const o=[{id:"auto",label:"Auto (recommended)",note:"q8 on the native gateway, fp32 on the WASM binary."},{id:"q8",label:"q8 — fast, balanced",note:"Int8. Best speed/quality trade-off (native default)."},{id:"q4",label:"q4 — smallest & fastest",note:"4-bit. Least memory; slightly lower accuracy."},{id:"int8",label:"int8",note:"Alternative int8 export."},{id:"fp16",label:"fp16 — more accurate",note:"Half precision. Larger, a bit slower."},{id:"fp32",label:"fp32 — most accurate (slow)",note:"Full precision. Largest + slowest; the only one that loads on the WASM binary."}];function h(e){return o.some(t=>t.id===e)}export{i as DEFAULT_STT_MODEL,s as RECOMMENDED_STT_MODEL,o as STT_DTYPES,a as STT_MODEL_CATALOG,c as isEnglishOnly,d as isKnownSttModel,g as isValidCustomSttId,h as isValidDtype,n as sttModel,m as sttModelDtype,p as sttModelEngine,u as sttModelUnavailable};
1
+ const d="istupakov/parakeet-tdt-0.6b-v3-onnx",n=Object.freeze({id:"indic-open-model-license",version:"1.0",name:"Indic Open Model License v1.0",url:"https://github.com/Bodhan-AI/bodhan-model-info/blob/main/licenses/indic-open-model-license/v1/Indic_Open_Model_License.md",summary:["Free to use, including commercially, when it runs on your own computer — as it does in Chap.","You may not run it as a service or API for other people without Bodhan AI's written approval.","Not for mass surveillance, deceptive automated calls, impersonating someone's voice, or other prohibited uses (section 10).","Provided as is, with no warranty. Built by Bodhan AI (IIT Madras) on NVIDIA Canary (CC-BY-4.0)."],attribution:"Built with Indic-Transcribe from Bodhan AI / AI4Bharat"});function c(e){return e?`${e.id}@${e.version}`:null}const a=[{id:"onnx-community/whisper-tiny.en",label:"Tiny (English)",lang:"English",tier:"light",approxMB:150,ramMB:400,note:"Fastest, lightest. English only — great for quick dictation on any machine."},{id:"onnx-community/whisper-base",label:"Base (multilingual)",lang:"99 languages (auto-detected)",tier:"balanced",approxMB:300,ramMB:700,note:"Small and quick to install. Detects the spoken language automatically; good accuracy at real-time speed."},{id:"onnx-community/whisper-small",label:"Small (multilingual)",lang:"99 languages (auto-detected)",tier:"accurate",approxMB:950,ramMB:1600,note:"Noticeably more accurate; needs a faster CPU to keep up in real time."},{id:"onnx-community/whisper-large-v3-turbo",label:"Large v3 Turbo (multilingual)",lang:"99 languages (auto-detected)",tier:"max",approxMB:1600,ramMB:3200,note:"Best accuracy. For powerful machines; use the native (npm) gateway for speed."},{id:"istupakov/parakeet-tdt-0.6b-v3-onnx",label:"Parakeet TDT 0.6B v3 (multilingual, fast)",lang:"25 European languages (auto-detected)",tier:"accurate",engine:"parakeet-tdt",recommended:!0,approxMB:690,ramMB:1600,note:"Recommended — NVIDIA Parakeet transducer. Several× faster than Whisper at similar or better accuracy, English + 24 EU languages. One-time download; best on the native (npm) gateway."},{id:"ConwayResearch/Underdog-Bark-3.0",label:"Parakeet TDT 0.6B v3 for the Neural Engine (English)",lang:"English",tier:"light",engine:"coreml-tdt",platforms:["darwin-arm64"],approxMB:200,ramMB:500,note:"The same Parakeet model, repacked for the Apple Neural Engine: a 200 MB download and the fastest dictation on a Mac. English only. Needs the Apple helper."},{id:"bodhan-ai/indic-transcribe-core",label:"Indic-Transcribe (Indian languages)",lang:"25 Indian languages + Indian English (detected line by line, mixed speech)",tier:"accurate",engine:"indic-canary",requiresNative:!0,approxMB:1530,ramMB:2600,license:n,attribution:n.attribution,note:"Best for Telugu, Hindi, Tamil and the other Indian languages, with Indian English and mixed speech: each line is identified and written in its own script. By Bodhan AI (IIT Madras) on NVIDIA Canary; free to use on your own computer under its licence."}],u="istupakov/parakeet-tdt-0.6b-v3-onnx";function p(e){return i(e)?.engine||"whisper"}function m(e,{platform:t=process.platform,arch:o=process.arch,helper:r=!1,native:l=!globalThis.__CHATPANEL_WASM_PATHS__}={}){return Array.isArray(e?.platforms)&&!e.platforms.includes(`${t}-${o}`)?"Needs a Mac with Apple Silicon.":e?.requiresNative&&!l?"Needs the npm gateway — the standalone binary cannot run it.":e?.engine==="coreml-tdt"&&!r?"Needs the Apple helper — Install it on the Apple on-device row (Runtime).":null}function h(e){return a.some(t=>t.id===e)}function i(e){return a.find(t=>t.id===e)||null}function g(e){return/\.en$/.test(String(e||""))}function b(e){return i(e)?.dtype||null}function f(e){const t=String(e||"");return/^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(t)&&!t.includes("..")}const s=[{id:"auto",label:"Auto (recommended)",note:"q8 on the native gateway, fp32 on the WASM binary."},{id:"q8",label:"q8 — fast, balanced",note:"Int8. Best speed/quality trade-off (native default)."},{id:"q4",label:"q4 — smallest & fastest",note:"4-bit. Least memory; slightly lower accuracy."},{id:"int8",label:"int8",note:"Alternative int8 export."},{id:"fp16",label:"fp16 — more accurate",note:"Half precision. Larger, a bit slower."},{id:"fp32",label:"fp32 — most accurate (slow)",note:"Full precision. Largest + slowest; the only one that loads on the WASM binary."}];function y(e){return s.some(t=>t.id===e)}export{d as DEFAULT_STT_MODEL,n as INDIC_LICENSE,u as RECOMMENDED_STT_MODEL,s as STT_DTYPES,a as STT_MODEL_CATALOG,g as isEnglishOnly,h as isKnownSttModel,f as isValidCustomSttId,y as isValidDtype,c as licenseAcceptance,i as sttModel,b as sttModelDtype,p as sttModelEngine,m as sttModelUnavailable};
package/src/stt-remote.js CHANGED
@@ -1 +1 @@
1
- const p=16e3;function E(e,i=16e3){const n=e.length,t=Buffer.alloc(44+n*2);t.write("RIFF",0),t.writeUInt32LE(36+n*2,4),t.write("WAVE",8),t.write("fmt ",12),t.writeUInt32LE(16,16),t.writeUInt16LE(1,20),t.writeUInt16LE(1,22),t.writeUInt32LE(i,24),t.writeUInt32LE(i*2,28),t.writeUInt16LE(2,32),t.writeUInt16LE(16,34),t.write("data",36),t.writeUInt32LE(n*2,40);for(let r=0;r<n;r++){const a=Math.max(-1,Math.min(1,e[r]));t.writeInt16LE(a<0?a*32768:a*32767,44+r*2)}return t}const f=Object.freeze(["openai"]);function d(e,{fetchImpl:i,now:n=()=>performance.now()}={}){if(!e||!["remote","container"].includes(e.kind)||!/^https?:\/\//.test(e.url||""))throw new Error("stt-remote: a remote provider needs a url");const t=e.adapter||"openai";if(!f.includes(t))throw new Error(`stt-remote: unknown adapter ${t}`);const r=e.url.replace(/\/+$/,"");return{provider:{kind:e.kind,url:e.url,adapter:t,model:e.model||"whisper-1"},async transcribe(a,{lang:c=null,timeoutMs:l=3e4}={}){const u=n(),o=new FormData;o.append("file",new Blob([E(a)],{type:"audio/wav"}),"segment.wav"),o.append("model",e.model||"whisper-1"),o.append("response_format","json"),c&&o.append("language",c);const s=await i(`${r}/audio/transcriptions`,{method:"POST",headers:{accept:"application/json",...e.token?{authorization:`Bearer ${e.token}`}:{}},body:o,signal:AbortSignal.timeout(l)});if(!s.ok){const w=await s.text().catch(()=>"");throw new Error(`${t} transcription ${s.status}${w?`: ${w.slice(0,200)}`:""}`)}const m=await s.json().catch(()=>({}));return{text:String(m?.text||"").trim(),ms:Math.round(n()-u)}}}}export{f as STT_REMOTE_ADAPTERS,d as createRemoteTranscriber,E as wavFromFloat32};
1
+ const L=16e3;function b(t,a=16e3){const o=t.length,e=Buffer.alloc(44+o*2);e.write("RIFF",0),e.writeUInt32LE(36+o*2,4),e.write("WAVE",8),e.write("fmt ",12),e.writeUInt32LE(16,16),e.writeUInt16LE(1,20),e.writeUInt16LE(1,22),e.writeUInt32LE(a,24),e.writeUInt32LE(a*2,28),e.writeUInt16LE(2,32),e.writeUInt16LE(16,34),e.write("data",36),e.writeUInt32LE(o*2,40);for(let r=0;r<o;r++){const i=Math.max(-1,Math.min(1,t[r]));e.writeInt16LE(i<0?i*32768:i*32767,44+r*2)}return e}const _=Object.freeze(["openai","elevenlabs"]),E=Object.freeze({openai:"/audio/transcriptions",elevenlabs:"/speech-to-text"});function x(t){const a=String(t||"").trim();if(!a)return null;try{return new Intl.Locale(a).language.toLowerCase()||null}catch{return null}}function S(t,{fetchImpl:a,now:o=()=>performance.now()}={}){if(!t||!["remote","container"].includes(t.kind)||!/^https?:\/\//.test(t.url||""))throw new Error("stt-remote: a remote provider needs a url");const e=t.adapter||"openai";if(!_.includes(e))throw new Error(`stt-remote: unknown adapter ${e}`);const r=t.url.replace(/\/+$/,"");return{provider:{kind:t.kind,url:t.url,adapter:e,model:t.model||(e==="elevenlabs"?"scribe_v1":"whisper-1")},async transcribe(i,{lang:c=null,langs:h=null,timeoutMs:p=3e4}={}){const d=o();if(e==="elevenlabs"){const n=new FormData;n.append("file",new Blob([b(i)],{type:"audio/wav"}),"segment.wav"),n.append("model_id",t.model||"scribe_v1"),c&&!h?.length&&n.append("language_code",c),n.append("tag_audio_events","false"),n.append("diarize","false");const u=await a(`${r}${E.elevenlabs}`,{method:"POST",headers:{accept:"application/json",...t.token?{"xi-api-key":t.token}:{}},body:n,signal:AbortSignal.timeout(p)});if(!u.ok){const f=await u.text().catch(()=>"");throw new Error(`elevenlabs transcription ${u.status}${f?`: ${f.slice(0,200)}`:""}`)}const w=await u.json().catch(()=>({})),m=x(w?.language_code);return{text:String(w?.text||"").trim(),ms:Math.round(o()-d),...m?{lang:m,confidence:Number(w?.language_probability)||null}:{}}}const s=new FormData;s.append("file",new Blob([b(i)],{type:"audio/wav"}),"segment.wav"),s.append("model",t.model||"whisper-1"),s.append("response_format","json"),c&&s.append("language",c);const l=await a(`${r}${E.openai}`,{method:"POST",headers:{accept:"application/json",...t.token?{authorization:`Bearer ${t.token}`}:{}},body:s,signal:AbortSignal.timeout(p)});if(!l.ok){const n=await l.text().catch(()=>"");throw new Error(`${e} transcription ${l.status}${n?`: ${n.slice(0,200)}`:""}`)}const g=await l.json().catch(()=>({}));return{text:String(g?.text||"").trim(),ms:Math.round(o()-d)}}}}export{_ as STT_REMOTE_ADAPTERS,E as STT_REMOTE_PATHS,S as createRemoteTranscriber,x as languageFromService,b as wavFromFloat32};
@@ -0,0 +1 @@
1
+ import{existsSync as S,readdirSync as $}from"node:fs";import{join as b}from"node:path";import{ensureLib as k,modelRoot as v,withModelSource as P}from"./ner-engine.js";import{runtimeDtype as h,DTYPE_SUFFIX as T}from"./model-runtime.js";import{makeWarmTimer as E}from"./warm-timer.js";const M="Xenova/opus-mt-mul-en",A=112,R=1200;let t="off",p=M,c=null,f=null,u=null,i=null,l=null,_=0,m=0,w=Promise.resolve(),g=null;function H(){return p}function W(){return t}function x(){return t==="ready"&&!!c}function Y(){return i}function q(){return{configured:t!=="off",ok:x(),state:t,model:p,error:f,approxMB:A,onDisk:D(),warmMs:l?.warmMs??null}}function y(){return _>0||m>0||t==="loading"||t==="downloading"}function z(){m++,l?.disarm()}function G(){m=Math.max(0,m-1),m===0&&_===0&&x()&&l?.arm()}async function F({log:e=()=>{}}={}){if(y())return!1;l?.disarm();const n=c;if(c=null,g=null,u=null,i=null,f=null,t="off",n){try{await n.dispose?.()}catch{}e("[translate] idle — model unloaded (reloads on the next translated meeting)")}return!0}function D(e=p,n=h()){const d=b(v(),...e.split("/"),"onnx");if(!S(d))return!1;const r=T[n]??"";try{const a=$(d);return a.includes(`encoder_model${r}.onnx`)&&a.some(o=>o===`decoder_model_merged${r}.onnx`||o===`decoder_model${r}.onnx`)}catch{return!1}}async function O({log:e=()=>{},allowDownload:n=!0}={}){let d;try{d=await k()}catch(o){return t="error",f=o.message,e(`[translate] engine unavailable (${o.message})`),!1}const r=p,a=D(r);if(!a&&!n)return t="error",f="model not on disk and downloads disabled",!1;t=a?"loading":"downloading",a||(i={model:r,file:null,pct:0},e(`[translate] downloading ${r} (one-time, ~${A} MB)…`));try{const o=s=>{if(!s)return;const L=typeof s.progress=="number"?Math.round(s.progress):i?.pct??0;(s.status==="progress"||s.status==="download"||s.status==="initiate")&&(i={model:r,file:s.file||i?.file||null,pct:L})};return c=await P({host:a?null:"https://huggingface.co/",allowRemote:!a},s=>s.pipeline("translation",r,{dtype:h(),progress_callback:o})),t="ready",f=null,i=null,e(`[translate] ready — ${r} @ ${h()} (meeting lines into English, in-process, offline)`),!0}catch(o){return f=o.message,i=null,t="error",e(`[translate] load failed (${o.message}) — lines stay in the language they were spoken in`),!1}}function X(e){return e.then(n=>(n&&!y()&&l?.arm(),n))}function J(e={}){if(u&&t!=="error")return u;t="loading";const n=typeof e.onLog=="function"?e.onLog:()=>{};return l=E({warmMs:e.warmMs,busy:y,log:n,unload:()=>F({log:n})}),u=X(O({log:n,allowDownload:e.allowDownload!==!1})),u}function K(){return u?u.then(()=>x(),()=>!1):Promise.resolve(x())}function Q(e){const n=String(e||"").trim().slice(0,R);if(!n||!x())return Promise.resolve(null);_++,l?.disarm();const d=w.then(async()=>{try{if(g)return await g(n)??null;const r=await c(n,{max_new_tokens:400});return String((Array.isArray(r)?r[0]:r)?.translation_text||"").trim()||null}catch{return null}});return w=d.catch(()=>null),d.finally(()=>{_--,y()||l?.arm()})}function V(){l?.disarm(),l=null,m=0,_=0,t="off",p=M,c=null,g=null,f=null,u=null,i=null,w=Promise.resolve()}function Z(e){g=e||null,c=e?{dispose:async()=>{}}:null,t=e?"ready":"off"}export{M as DEFAULT_TRANSLATE_MODEL,A as TRANSLATE_MODEL_APPROX_MB,V as _reset,Z as _setForTest,H as activeModel,q as health,J as init,x as isReady,D as modelOnDisk,Y as progress,K as ready,G as release,z as retain,W as state,Q as translate,F as unload};
@@ -0,0 +1 @@
1
+ import{existsSync as v}from"node:fs";import{join as D}from"node:path";import{ensureLib as k,modelRoot as O,withModelSource as S}from"./ner-engine.js";import{makeWarmTimer as F}from"./warm-timer.js";const w="onnx-community/silero-vad",z=2.2,T=16e3,s=512,R=.5,K=.35,V=.05,N=40,P=62;let o="off",m=null,M=null,c=null,h=null,g=null,f=null,x=0,_=0,y=null;function U(){return o}function L(){return o==="ready"&&(!!m||!!y)}function C(){return g}function H(){return{configured:o!=="off",ok:L(),state:o,model:w,error:c,warmMs:f?.warmMs??null}}function A(){return _>0||x>0||o==="loading"||o==="downloading"}function J(){x++,f?.disarm()}function Q(){x=Math.max(0,x-1),x===0&&_===0&&L()&&f?.arm()}function I(){return v(D(O(),...w.split("/"),"onnx","model.onnx"))}async function B({log:e=()=>{}}={}){if(A())return!1;f?.disarm();const t=m;if(m=null,h=null,g=null,c=null,o="off",t){try{await t.dispose?.()}catch{}e("[vad] idle — model unloaded")}return!0}async function G({log:e=()=>{},allowDownload:t=!0}={}){try{M=await k()}catch(r){return o="error",c=r.message,!1}const n=I();if(!n&&!t)return o="error",c="model not on disk and downloads disabled",!1;o=n?"loading":"downloading",n||(g={model:w,file:null,pct:0},e(`[vad] downloading ${w} (one-time, ~2 MB)…`));try{return m=await S({host:n?null:"https://huggingface.co/",allowRemote:!n},r=>r.AutoModel.from_pretrained(w,{config:{model_type:"custom"},dtype:"fp32"})),o="ready",c=null,g=null,e("[vad] ready — Silero VAD on levelled audio decides what is speech (the energy gate is the fallback)"),!0}catch(r){return c=r.message,g=null,o="error",e(`[vad] load failed (${r.message}) — the energy gate decides, as before`),!1}}function Y(e={}){if(h&&o!=="error")return h;o="loading";const t=typeof e.onLog=="function"?e.onLog:()=>{};return f=F({warmMs:e.warmMs,busy:A,log:t,unload:()=>B({log:t})}),h=G({log:t,allowDownload:e.allowDownload!==!1}).then(n=>(n&&!A()&&f?.arm(),n)),h}function W(e){if(!e.length)return 1;const t=[...e].sort((r,E)=>r-E),n=t[Math.floor(t.length*.9)]||0;return n>0?Math.min(N,Math.max(1,V/n)):1}function Z(){let e=null,t=0;const n=new Map,r=[],E=Math.ceil(90*T/s);async function b(l){let i=0;for(let u=0;u<l.length;u++)i+=l[u]*l[u];r.push(Math.sqrt(i/l.length)),r.length>P&&r.shift();const d=W(r),a=d===1?l:l.map(u=>u*d);if(y)return y(a);e||=new M.Tensor("float32",new Float32Array(256),[2,1,128]);const p=await m({input:new M.Tensor("float32",a,[1,s]),sr:new M.Tensor("int64",[BigInt(T)],[]),state:e});return e=p.stateN,Number(p.output.data[0])}return{async advance(l,i){if(!L())return!1;const d=i+l.length;t<i&&(t=Math.ceil(i/s)*s),_++;try{for(;t+s<=d;t+=s){const a=t-i;n.set(t/s,await b(l.slice(a,a+s)))}}catch{return!1}finally{_--}for(const a of n.keys()){if(n.size<=E)break;n.delete(a)}return!0},speechIn(l,i,d=R){let a=!1;for(let p=Math.floor(l/s);p*s<i;p++){const u=n.get(p);if(u!==void 0&&(a=!0,u>=d))return!0}return a?!1:null},_probs:n}}function ee(){f?.disarm(),f=null,x=0,_=0,o="off",m=null,y=null,c=null,h=null,g=null}function te(e){y=e||null,o=e?"ready":"off"}export{w as DEFAULT_VAD_MODEL,s as FRAME,N as LEVEL_MAX_GAIN,V as LEVEL_TARGET,P as LEVEL_WINDOW,K as OFFSET,R as ONSET,T as SAMPLE_RATE,z as VAD_MODEL_APPROX_MB,ee as _reset,te as _setForTest,Z as createStream,H as health,Y as init,L as isReady,W as levelGain,I as modelOnDisk,C as progress,Q as release,J as retain,U as state,B as unload};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.105.1";export{o as VERSION};
1
+ const o="0.116.0";export{o as VERSION};