@chatpanel/gateway 0.154.3 → 0.154.5

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.154.3",
3
+ "version": "0.154.5",
4
4
  "description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -24,7 +24,7 @@
24
24
  "dependencies": {
25
25
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
26
26
  "@chatpanel/bridge": "^0.52.0",
27
- "@chatpanel/events": "^0.505.0",
27
+ "@chatpanel/events": "^0.506.0",
28
28
  "@chatpanel/pii": "^0.15.6",
29
29
  "@huggingface/transformers": "^4.2.0",
30
30
  "defuddle": "^0.19.4",
package/src/stt-engine.js CHANGED
@@ -1 +1 @@
1
- import{join as ot}from"node:path";import{deflateSync as rt}from"node:zlib";import Oe from"node:os";import{existsSync as at,readdirSync as lt}from"node:fs";import{randomUUID as st}from"node:crypto";import{ensureLib as Re,modelRoot as Ce}from"./ner-engine.js";import{runtimeDtype as ue,runtimeName as Fe,DTYPE_SUFFIX as it}from"./model-runtime.js";import{verifyModelWeights as ct}from"./model-integrity.js";import{DEFAULT_STT_MODEL as $e,isEnglishOnly as me,sttModelDtype as _e,isKnownSttModel as ut,sttModelEngine as j}from"./stt-models.js";import*as X from"./parakeet-engine.js";import*as we from"./coreml-stt-engine.js";import*as le from"./indic-engine.js";import*as U from"./diarize-engine.js";import*as B from"./segment-engine.js";import{turnsFromSpans as He,mainLocal as Ue,timeByLocal as ft,audioOfLocal as dt}from"@chatpanel/events/speaker-turns.js";import{regroupSpeakers as gt,regroupThreshold as pt}from"@chatpanel/events/speaker-recluster.js";import{diarizeApproxMB as ht}from"./diarize-models.js";import*as se from"./translate-engine.js";import*as ne from"./indictrans-engine.js";import{rawOrtAvailable as mt}from"./ort.js";import*as z from"./vad-engine.js";import*as oe from"./echo-pair.js";import*as ye from"./aec-engine.js";import{pickSegmentLanguage as _t,detectTextLanguage as wt,needsTranslation as yt,localTranslatable as Mt,normalizeLanguages as Et,normalizeLanguage as St,decodeLanguages as Tt,lineLanguage as Lt,autoCandidates as At,AUTO_LEARN_CONFIDENCE as xt,AUTO_LEARN_SECONDS as kt,ANY_LANGUAGE_CONFIDENCE as bt,AUTO_LANGUAGES as vt}from"@chatpanel/events/speech-language.js";import*as Dt from"@chatpanel/events/speech-language.js";import{makeWarmTimer as Me}from"./warm-timer.js";const h=16e3,ze=h,Ge=3*h,Nt=2,Pt=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 Ot(e,t){if(t>Nt*h)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?Pt.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}const Rt=12,Ee=3;function Ct(e){const t=String(e||"").split(/\s+/).filter(Boolean);if(t.length<Ee)return{text:String(e||"").trim(),removed:0,total:t.length};const n=a=>a.toLowerCase().replace(/[^\p{L}\p{N}']/gu,""),o=[];let r=0;for(let a=0;a<t.length;){let i=0,c=0;for(let s=1;s<=Rt&&a+s*Ee<=t.length;s++){let l=1;for(;a+(l+1)*s<=t.length&&t.slice(a+l*s,a+(l+1)*s).every((f,d)=>n(f)===n(t[a+d]));)l++;l>=Ee&&(l-1)*s>i&&(i=(l-1)*s,c=s)}i?(o.push(...t.slice(a,a+c)),r+=i,a+=c+i):(o.push(t[a]),a++)}return{text:o.join(" "),removed:r,total:t.length}}const Ft=.6,Ke=2.4;function je(e){const t=Buffer.from(String(e||""),"utf8");return t.length<40?1:t.length/rt(t).length}function $t(e){return String(e||"").replace(/([^\d\s]{1,8}?)\1{4,}/gu,"$1")}function Ht({cores:e=Oe.availableParallelism?.()??Oe.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 ie(e){return{intraOpNumThreads:Ht(e),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}const Ut=.12,Be=.8,zt=.15,Gt=.5,Kt=1.2,Ie=(e,t)=>e>=Gt||e>=zt&&!(t<Kt),jt=.999,Bt=2.5;function Se(e={},t=1/0){return Ie(e.en??0,t)?"en":Object.entries(e).sort((n,o)=>o[1]-n[1])[0]?.[0]||null}const It=.9,Wt=.5;function Xt(e={},t=1/0,n=null){const o=Se(e,t);if(!o||o==="en")return o;const r=e[o]??0;return r>=It?(n?.add(o),o):r>=Wt&&n?.has(o)?o:"en"}function Vt(e,t=[]){const n=[];return e.forEach((o,r)=>{const a=t[r]??o.lang,i=n[n.length-1];i&&i.lang===a?i.to=o.to:n.push({from:o.from,to:o.to,lang:a})}),n}function Yt(e,{base:t=null,rate:n=h}={}){const o=e||[],r=s=>{const[l,f]=Object.entries(s.scores||{}).sort((d,x)=>x[1]-d[1])[0]||[];return l&&l!=="en"&&f>=jt?l:null},a=new Array(o.length).fill(null);for(let s=0;s<o.length;){const l=r(o[s]);let f=s+1;if(l)for(;f<o.length&&r(o[f])===l;)f++;if(l&&(o[f-1].to-o[s].from)/n>=Bt)for(let d=s;d<f;d++)a[d]=l;s=f}const i=[];let c=t;return o.forEach((s,l)=>{a[l]?c=a[l]:c!=="en"&&Ie(s.scores?.en??0,(s.to-s.from)/n)&&(c="en");const f=i[i.length-1];f&&f.lang===c?f.to=s.to:i.push({from:s.from,to:s.to,lang:c})}),i}async function qt(e,t,n){const{spelledEnglish:o,isSpelledEnglish:r,SPELLED_ENGLISH_MIN:a,SPELLED_SHAPE_MIN:i}=Dt;if(typeof o!="function")return e;const c=[];let s=!1;for(const l of e){const f=o(l.text);if(!l.lang||l.lang==="en"||f.english<a&&!r(l.text)){c.push(l);continue}const d=f.words>=i&&f.shaped===f.words,x=[];for(let u=0;u+1<t.length;u++)t[u]>=l.from&&t[u+1]<=l.to&&x.push([t[u],t[u+1]]);if(x.length<2||d){const u=r(l.text)?await n(l.from,l.to,"en"):"";u?(c.push({...l,text:u,lang:"en"}),s=!0):c.push(l);continue}const T=[];for(const[u,p]of x){const N=await n(u,p,l.lang),k=o(N),re=k.words>0&&k.words-k.shaped<=(k.english>=1&&k.words>=3?1:0);T.push({from:u,to:p,text:N,near:re,lang:r(N)?"en":l.lang})}for(let u=!0;u;)u=!1,T.forEach((p,N)=>{p.lang!=="en"&&p.near&&(T[N-1]?.lang==="en"||T[N+1]?.lang==="en")&&(p.lang="en",u=!0)});if(!T.some(u=>u.lang==="en")){c.push(l);continue}const E=[];for(const u of T){const p=E[E.length-1];p&&p.lang===u.lang?(p.to=u.to,p.n++):E.push({from:u.from,to:u.to,lang:u.lang,n:1,text:u.text})}for(const u of E){const p=u.n===1&&u.lang===l.lang?u.text:await n(u.from,u.to,u.lang);p&&c.push({from:u.from,to:u.to,lang:u.lang,text:p})}s=!0}return s?c.reduce((l,f)=>{const d=l[l.length-1];return d&&d.lang===f.lang&&d.to===f.from?l[l.length-1]={...d,to:f.to,text:`${d.text} ${f.text}`}:l.push(f),l},[]):e}function Qt(e,t,{frame:n=Math.round(.03*h),minPause:o=Ut*h,minPiece:r=Be*h}={}){const a=[];let i=0,c=-1;for(let s=0;s+n<=e;s+=n){const l=t(s,s+n)===!1;if(l&&c<0&&(c=s),(!l||s+2*n>e)&&c>=0){const f=l?s+n:s,d=Math.round((c+f)/2);f-c>=o&&d-i>=r&&e-d>=r&&(a.push(d),i=d),c=-1}}return a}const Jt=.12;function Zt(e,t=Math.round(.03*h)){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]=ee(e,r*t,(r+1)*t);return o.sort(),Math.max(1e-4,o[Math.floor(n*.9)]*Jt)}let w="off",A=null,m=null,D=null,Q=null,L=null,V=null,R=null;function en(e=A||$e,t=_e(e)||ue()){if(j(e)==="parakeet-tdt")return X.parakeetOnDisk(e,X.parakeetDtype(t));if(j(e)==="coreml-tdt")return we.coremlOnDisk(e);if(j(e)==="indic-canary")return le.indicOnDisk();const n=ot(Ce(),...e.split("/"),"onnx");if(!at(n))return!1;const o=it[t]??"";try{const r=lt(n);return r.includes(`encoder_model${o}.onnx`)&&r.some(a=>a===`decoder_model_merged${o}.onnx`||a===`decoder_model${o}.onnx`)}catch{return!1}}function Bn(){return w}function fe(){return w==="ready"&&!!m}function In(){return L}function Wn(){return{configured:w!=="off",ok:fe(),state:w,model:A,dtype:V,runtime:Fe(),error:D,warmMs:R?.warmMs??null,vad:z.state()}}function Xn(){return!!R?.pending()}function ce(){return G.size>0||w==="loading"||w==="downloading"}async function Te({log:e=()=>{}}={}){if(ce())return!1;R?.disarm();const t=m;if(m=null,Q=null,V=null,L=null,D=null,w="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((R?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function We(e){return e.then(t=>(t&&!ce()&&R?.arm(),t))}async function Xe(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null,licenseAccepted:r=null}={}){if(j(e)==="parakeet-tdt")return tn(e,{log:t,allowDownload:n,dtype:o});if(j(e)==="coreml-tdt")return on(e,{log:t,allowDownload:n});if(j(e)==="indic-canary")return rn(e,{log:t,allowDownload:n,licenseAccepted:r});const a=m,i=A;let c;try{c=await Re()}catch(T){return w="error",D=`engine load failed: ${T.message}`,t(`[stt] transformers.js not available (${T.message}) — dictation falls back to the browser engine`),!1}const l=(o&&o!=="auto"?o:null)||_e(e)||ue(),f=en(e,l);if(c.env.allowRemoteModels=f?!1:!!n,!f&&!n)return w="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const d=c.env.remoteHost,x=!ut(e);if(!f&&x)try{c.env.remoteHost="https://huggingface.co/"}catch{}w=f?"loading":"downloading",f||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${x?", from Hugging Face":""})…`));try{const T=u=>{if(!u)return;const p=typeof u.progress=="number"?Math.round(u.progress):L?.pct??0;u.status==="progress"||u.status==="download"||u.status==="initiate"?L={model:e,file:u.file||L?.file||null,pct:p}:u.status==="done"&&u.file&&t(`[stt] fetched ${u.file}`)};let E;try{E=await c.pipeline("automatic-speech-recognition",e,{dtype:l,progress_callback:T,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:ie()}})}catch(u){if(f||x||!n)throw u;t(`[stt] mirror fetch failed (${String(u.message).slice(0,80)}) — retrying from Hugging Face…`),c.env.remoteHost="https://huggingface.co/",c.env.allowRemoteModels=!0,E=await c.pipeline("automatic-speech-recognition",e,{dtype:l,progress_callback:T,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:ie()}})}if(!f)try{ct(e,{modelsDir:Ce(),log:t})}catch(u){try{await E.dispose?.()}catch{}throw u}if(m=E,A=e,w="ready",D=null,L=null,V=l,a&&a!==E)try{await a.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${l} (in-process, offline) — local dictation active`),!0}catch(T){return D=T.message,L=null,a?(m=a,A=i,w="ready"):w="error",t(`[stt] model load failed (${T.message})${a?" — keeping previous model":""}`),!1}finally{try{c.env.remoteHost=d}catch{}}}async function tn(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null}={}){const r=m,a=A,i=X.parakeetDtype(o&&o!=="auto"?o:nn()),c=X.parakeetOnDisk(e,i);if(!c&&!n)return w="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;w=c?"loading":"downloading",c||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const s=await X.loadRecognizer({modelId:e,dtype:i,allowDownload:n,log:t,sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:ie(),onProgress:f=>{L={model:e,file:f.file||null,pct:typeof f.pct=="number"?f.pct:L?.pct??0}}}),l=async f=>({text:await s.transcribe(f)});if(l.__transducer=!0,l.dispose=()=>s.dispose(),m=l,A=e,w="ready",D=null,L=null,V=i,r&&r!==l)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(s){return D=s.message,L=null,r?(m=r,A=a,w="ready"):w="error",t(`[stt] model load failed (${s.message})${r?" — keeping previous model":""}`),!1}}function nn(){return X.PARAKEET_DEFAULT_DTYPE}const Ve="fp16";async function on(e,{log:t=()=>{},allowDownload:n=!0}={}){const o=m,r=A,a=we.coremlOnDisk(e);if(!a&&!n)return w="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;w=a?"loading":"downloading",a||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let i=null;const c=await we.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:s=>{L={model:e,file:s.file||null,pct:typeof s.pct=="number"?s.pct:L?.pct??0}},onExit:s=>{m===i&&(m=null,Q=null,w="error",D=s,R?.disarm(),t(`[stt] ${s} — reloads on the next dictation`))}});if(i=async s=>({text:await c.transcribe(s)}),i.__transducer=!0,i.dispose=()=>c.dispose(),m=i,A=e,w="ready",D=null,L=null,V=Ve,o&&o!==i)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} (Core ML on the Neural Engine, helper ${c.version}, windows ${c.windows.join("/")} s, offline) — local dictation active`),!0}catch(i){return D=i.message,L=null,o?(m=o,A=r,w="ready"):w="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}async function rn(e,{log:t=()=>{},allowDownload:n=!0,licenseAccepted:o=null}={}){const r=m,a=A,i=le.indicOnDisk();if(!i&&!n)return w="error",D="model not on disk and downloads disabled",!1;w=i?"loading":"downloading",i||(L={model:e,file:null,pct:0},t(`[stt] downloading ${e} (one-time, ~1.5 GB, from Hugging Face)…`));try{i||await le.ensureIndicFiles({licenseAccepted:o,log:t,onProgress:l=>{L={model:e,file:l.file,pct:l.pct}}});const c=await le.loadRecognizer({sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:ie(),log:t}),s=async(l,f={})=>c.transcribe(l,f);if(s.identify=(l,f)=>c.identify(l,f),s.__transducer=!0,s.__indic=!0,s.dispose=()=>c.dispose(),m=s,A=e,w="ready",D=null,L=null,V="int8",r&&r!==s)try{await r.dispose?.()}catch{}return t(`[stt] ready — ${e} (Indic-Transcribe, int8, in-process, offline) — ${le.INDIC_LICENSE.attribution}`),!0}catch(c){return D=c.message,L=null,r?(m=r,A=a,w="ready"):w="error",t(`[stt] model load failed (${c.message})${r?" — keeping previous model":""}`),!1}}const an=30;function Ye({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:o=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof o=="number"&&o<=an||e==="download"?{allowDownload:!0}:null}function Le(e,{log:t=()=>{},warmMs:n,allowDownload:o=!0}={}){const r=Ye({mode:e,onDisk:U.modelOnDisk(),ready:U.isReady(),approxMB:ht(U.activeModel())});if(r&&U.init({allowDownload:r.allowDownload&&o!==!1,warmMs:n,onLog:t}),e==="off"||Ae)return;const a=Ye({mode:e,onDisk:B.modelOnDisk(),ready:B.isReady(),approxMB:B.SEGMENT_MODEL_APPROX_MB});a&&B.init({allowDownload:a.allowDownload&&o!==!1,warmMs:n,onLog:t})}let Ae=!1,xe=null;function ke(e={},{log:t=()=>{}}={}){e.vad!==!1&&(xe={vad:e.vad,allowDownload:e.allowDownload,warmMs:e.warmMs},(z.state()==="off"||z.state()==="error")&&z.init({allowDownload:e.allowDownload!==!1,warmMs:e.warmMs,onLog:t}))}function Vn(e={}){if(Q&&w!=="error")return Q;const t=typeof e.onLog=="function"?e.onLog:()=>{};return A=e.model||$e,Ae=e.segment===!1,w="loading",R=Me({warmMs:e.warmMs,busy:ce,log:t,unload:()=>Te({log:t})}),Q=We(Xe(A,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype,licenseAccepted:e.licenseAccepted||null})).then(n=>(n&&(Le(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),ke(e,{log:t})),n)),Q}async function Yn(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(Ae=t.segment===!1);const o=j(e)==="parakeet-tdt"?X.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:X.PARAKEET_DEFAULT_DTYPE):j(e)==="coreml-tdt"?Ve:j(e)==="indic-canary"?"int8":t.dtype&&t.dtype!=="auto"?t.dtype:_e(e)||ue();if(e===A&&fe()&&V===o)return Le(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;R??=Me({warmMs:t.warmMs,busy:ce,log:n,unload:()=>Te({log:n})});const r=await We(Xe(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype,licenseAccepted:t.licenseAccepted||null}));return r&&(Le(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),ke(t,{log:n})),r}const ln=8,sn=12e4,cn=6e4,un=1200,de=12,fn=3,dn=1,gn=.8,pn=.5,hn=60,be=700,ve=.008,mn=.002,_n=4;function wn(e){return e>0?Math.min(ve,Math.max(mn,e*_n)):ve}function yn(e){const t=Math.round(.1*h),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]=ee(e,r*t,(r+1)*t);return o.sort(),o[Math.floor(n*.1)]}const qe=30,Mn=15e3,G=new Map,J=new Map;let Z=Promise.resolve();function qn(){return G.size}const En=300,Sn=3e3;function Tn(e){const t=Number(e);return Number.isFinite(t)?Math.min(Sn,Math.max(En,Math.round(t))):be}function Qn({lang:e,langs:t=null,translateTo:n=null,translateLoad:o=null,echo:r=null,redact:a=!1,diarize:i=!1,vectors:c=!1,speakerLabel:s=null,endSilenceMs:l=be,interims:f=!0,remote:d=null,poll:x=!1,format:T="f32"}={}){if(G.size>=ln){const N=new Error("too many concurrent dictation sessions");throw N.code="too_many_sessions",N}const E=Array.isArray(t)?Et(t):null,u=typeof e=="string"&&e?e.slice(0,12):null,p={id:st(),format:T==="pcm16"?"pcm16":"f32",endSilenceMs:Tn(l),lang:E?E.length===1?E[0]:E.length?null:u:u,langs:E,lastLang:null,lastDecoded:null,learned:new Set,translateTo:St(n)||null,translateLoad:o||{},translations:Promise.resolve(),echo:r&&typeof r=="object"?oe.join(r.group,r.role):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!a,diarize:!!i,speakerLabel:typeof s=="string"&&s?s.slice(0,40):null,diarizer:i?new U.Diarizer:null,prints:i?[]:null,shown:new Map,regroupedAt:0,vectors:!!i&&c===!0,remote:d||null,interims:f!==!1&&!d,chunks:[],samples:0,listeners:new Set,poll:x?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return G.set(p.id,p),R?.disarm(),p.diarizer&&(U.retain(),B.retain()),p.translateTo&&(se.retain(),ne.retain()),p.echo&&ye.retain(),z.retain(),xe&&(z.state()==="off"||z.state()==="error")&&ke(xe),Qe(p),{id:p.id}}function ge(e){return G.get(String(e||""))||null}function Jn(e,t){const n=ge(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function I(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function Zn(e){const t=String(e||""),n=G.get(t);if(n)return n.poll?n.poll.splice(0):null;const o=J.get(t);return o?(clearTimeout(o.timer),J.delete(t),o.session.poll.splice(0)):null}function eo(e){return J.get(String(e||""))?.session||null}function Qe(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>bn(e.id).catch(()=>{}),cn),e.idleTimer.unref?.()}function to(e,t){const n=ge(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(Qe(n),n.echo?.role==="mic"){oe.pushMic(n.echo,t),Je(n);return}n.echo?.role==="reference"&&oe.pushReference(n.echo,t),n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,Je(n)}}function no(e){const t=ge(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),Z=Z.then(()=>De(t).catch(()=>{})),Z)}function oo(e,t="f32"){if(t==="pcm16"){const r=new Float32Array(Math.floor(e.length/2));for(let a=0;a<r.length;a++)r[a]=e.readInt16LE(a*2)/32768;return r}const n=e.length-e.length%4,o=new Float32Array(n/4);for(let r=0;r<o.length;r++)o[r]=e.readFloatLE(r*4);return o}function Je(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+un-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,Z=Z.then(()=>De(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function pe(e,t,n){const o=e.samples-t,r=[];n&&r.push(n),o>0&&r.push(Ze(e).subarray(t)),e.chunks=r,e.samples=r.reduce((a,i)=>a+i.length,0),e.lastInterim=""}function Ze(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=h/100,r=Math.max(0,e.length-t),a=Math.floor((e.length-r)/o),i=Math.max(1,Math.round(n/o));if(a<=i)return 0;const c=new Float32Array(a);for(let d=0;d<a;d++){let x=0;const T=r+d*o;for(let E=0;E<o;E++)x+=e[T+E]*e[T+E];c[d]=x/o}let s=-1,l=1/0,f=0;for(let d=0;d<i;d++)f+=c[d];for(let d=0;d+i<=a;d++)d>0&&(f+=c[d+i-1]-c[d-1]),f<l&&(l=f,s=d);return s<0?0:r+Math.round((s+i/2)*o)}function ee(e,t=0,n=e.length){let o=0;const r=Math.max(1,n-t);for(let a=t;a<n;a++)o+=e[a]*e[a];return Math.sqrt(o/r)}function An(e,t=ve){const n=Math.round(.02*h);let o=0,r=e.length;for(let a=0;a+n<=e.length;a+=n)if(ee(e,a,a+n)>=t){o=a;break}for(let a=e.length-n;a>=0;a-=n)if(ee(e,a,a+n)>=t){r=a+n;break}return r>o?e.subarray(o,r):e}async function et(e){try{const t=await Re(),n=m?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const o=e.length>h*8?e.subarray(0,h*8):e,r=await m.processor(o),a=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),i=await m.model({...r,decoder_input_ids:a}),c={};for(const[s,l]of Object.entries(n.lang_to_id))c[s.slice(2,-2)]=Number(i.logits.data[l]);return c}catch{return null}}async function xn(e){const t=await et(e);if(!t)return null;let n=null,o=-1/0;for(const[r,a]of Object.entries(t))a>o&&(o=a,n=r);return n}async function De(e,{flush:t=!1}={}){if(e.closed&&!t)return;if(e.echo?.role==="mic"){const g=await oe.drain(e.echo,{force:t});g.length&&(e.chunks.push(g),e.samples+=g.length,e.pushed+=g.length)}if(!e.remote&&!fe()||!e.samples)return;e.lastDecodeAt=Date.now();let n=Ze(e);const o=n.length,r=Math.max(0,(e.pushed||0)-e.samples),a=Math.round((e.endSilenceMs||be)/1e3*h),i=yn(n);i!==null&&(e.noiseFloor==null||i<e.noiseFloor)&&(e.noiseFloor=i);const c=wn(e.noiseFloor);let s=null,l=null;z.isReady()&&(e.vad||=z.createStream(),await e.vad.advance(n,r)&&(s=e.vad.speechIn(r,r+n.length,z.ONSET),n.length>a&&(l=e.vad.speechIn(r+n.length-a,r+n.length,z.OFFSET))));const f=n.length>a&&(l!==null?!l:ee(n,n.length-a)<c);if(s===!1||s===null&&ee(n)<c){n.length>h*5&&(e.chunks=[n.subarray(n.length-h)],e.samples=h);return}let d=!1,x=null;if(e.diarizer&&!e.speakerLabel&&!t&&B.isReady()&&n.length>=fn*h){const g=await kn(n);g&&(x=n.subarray(g),n=n.subarray(0,g),d=!0)}if(!e.interims&&!t&&!f&&!d&&n.length<de*h)return;if(!d&&!t&&!f&&o>=de*h&&o<qe*h){const g=Ln(n,3*h,Math.round(.2*h));g>0&&g<n.length&&(x=n.subarray(g),n=n.subarray(0,g))}const T=!e.remote&&!me(A)&&!m?.__transducer;if(T&&!e.langs&&!e.lang&&!e.langTried&&n.length>=h){e.langTried=!0;const g=await xn(n);g&&(e.lang=g,I(e,{type:"language",lang:g}))}const E=t||f||d||o>=de*h;let u=e.lang;if(T&&e.langs&&!e.lang){const g=e.langs.length>0,C=g?Tt(e.langs):At([...e.learned]);if(C.length===1)u=C[0];else if(u=C.includes(e.lastDecoded)?e.lastDecoded:null,(E||!u)&&n.length>=h/2){const F=await et(n);if(F){const S=_t({scores:F,allowed:C,seconds:n.length/h,last:e.lastDecoded});u=!g&&!S.inherited&&S.confidence<bt?e.lastDecoded||"en":S.lang,!g&&E&&!S.inherited&&S.confidence>=xt&&n.length>=kt*h&&e.learned.add(S.lang)}}E&&u&&(e.lastDecoded=u)}let p="",N=null,k=null,re=null;try{if(e.remote){const g=await e.remote.transcribe(n,{lang:e.lang,langs:e.langs});p=g.text,re=g.lang||null}else{const g=m.__indic?e.langs?.length?{langs:[...new Set([...e.langs,"en"])],last:e.lastLang,choose:Se}:e.lang?{lang:e.lang}:{langs:[...vt],last:e.lastLang,choose:(_,y)=>Xt(_,y,e.learned)}:me(A)?{}:{language:u||void 0,task:"transcribe"},C=m.__indic&&m.identify&&E&&g.langs&&n.length>=2*Be*h?Qt(n.length,(_=>(y,b)=>ee(n,y,b)>=_)(Zt(n))):[],F=[0,...C,n.length];let S=null;const Y=g.choose||Se;if(C.length){const _=await m.identify(n,{langs:g.langs}),y=[];for(let b=0;b+1<F.length;b++){const O=await m.identify(n.subarray(F[b],F[b+1]),{langs:g.langs});y.push({from:F[b],to:F[b+1],scores:O?.scores||{}})}if(S=Yt(y,{base:_?.scores?Y(_.scores,n.length/h):null}),S.length>1){const b=[];for(let O=0;O<S.length;O++){const $=S[O],M=$.lang&&$.lang!=="en"&&(S[O-1]?.lang==="en"||S[O+1]?.lang==="en");b.push(M?Y((await m.identify(n.subarray($.from,$.to),{langs:g.langs}))?.scores||{},($.to-$.from)/h):$.lang)}S=Vt(S,b)}S.length<2&&(S=null)}if(S){k=[];for(const _ of S){const y=await m(n.subarray(_.from,_.to),_.lang?{lang:_.lang}:{...g}),b=String(y?.text||"").trim(),O=y?.lang||_.lang||null;b&&k.push({text:b,lang:O,from:_.from,to:_.to}),O&&(g.last=O)}}else{const _=await m(n,g);p=String(_?.text||"").trim(),m.__indic&&(N=_?.lang||null),m.__indic&&p&&(k=[{text:p,lang:N,from:0,to:n.length}])}if(k&&E&&g.langs&&(k=await qt(k,F,async(_,y,b)=>String((await m(n.subarray(_,y),{lang:b}))?.text||"").trim())),k){p=k.map(y=>y.text).join(" ");const _=new Map;for(const y of k)y.lang&&_.set(y.lang,(_.get(y.lang)||0)+(y.to-y.from));N=[..._].sort((y,b)=>b[1]-y[1])[0]?.[0]||null,(k.length<2||_.size<2)&&(k=null)}}}catch(g){I(e,{type:"error",code:"decode_failed",message:g.message,fatal:!1}),E&&pe(e,o,x);return}if(!p){E&&pe(e,o,x);return}{const g=Ct(p);if(g.removed&&g.removed/g.total>=Ft&&g.total>=12?p="":p=g.text,p&&je(p)>Ke){const C=$t(p);p=C.replace(/[\s\p{P}]/gu,"").length<12||je(C)>Ke?"":C}if(!p){E&&pe(e,o,x);return}}const nt=o>=de*h,Ne=o>=qe*h;if(t||f||d||nt||Ne){const g=t?"flush":f?"silence":d?"speaker":Ne?"overflow":"length",C=g==="flush"||g==="silence"||g==="speaker";pe(e,o,x);const F=An(n,c);if(Ot(p,F?F.length:0)||e.echo?.role==="mic"&&ye.mostlyEcho(oe.verdict(e.echo,r,r+n.length)))return;let S=null,Y=null,_=null;if(e.diarizer)try{const M=e.speakerLabel?null:await B.spans(n),v=M?He(M):[];if(v.length){const H=new Map,K=new Map;for(const{local:P}of ft(v)){const W=dt(n,v,P),te=W.length?await U.embed(W):null;te&&K.set(P,{vec:te,samples:W.length});const q=W.length<ze,ae=W.length<Ge;H.set(P,e.diarizer.assign(te,{pinnedLabel:null,weak:q,thin:ae}))}const he=Math.round(r/h*1e3);Y=v.map(P=>({startMs:he+Math.round(P.start*1e3),durationMs:Math.round((P.end-P.start)*1e3),speaker:H.get(P.local)})).filter(P=>P.speaker),S=H.get(Ue(v))||null,S&&(_=K.get(Ue(v))||null)}}catch{}if(e.diarizer&&!S)try{const M=F,v=M?await U.embed(M):null,H=!!M&&M.length<ze,K=!!M&&M.length<Ge;v&&(_={vec:v,samples:M.length}),S=e.diarizer.assign(v,{pinnedLabel:e.speakerLabel,weak:H,thin:K})}catch{}let y=null;(e.langs||e.translateTo)&&(N?y=N:re?y=re:me(A)&&!e.remote?y="en":T?y=Lt(p,u||e.lang)||null:y=e.lang||wt(p,{allowed:e.langs||[],last:e.lastLang}).lang,y&&y!==e.lastLang&&(e.lastLang=y,I(e,{type:"language",lang:y})));const b=e.vectors&&_?{vec:U.plainVector(_.vec),seconds:Math.round(_.samples/h*100)/100,speakerModel:U.activeModel()}:null,O=Math.round(r/h*1e3),$=k&&(e.langs||e.translateTo)?k.map((M,v)=>({text:M.text,lang:M.lang,startMs:O+Math.round(M.from/h*1e3),durationMs:Math.round((M.to-M.from)/h*1e3),last:v===k.length-1})):[{text:p,lang:y,startMs:O,durationMs:Math.round(n.length/h*1e3),last:!0}];for(const M of $){$.length>1&&M.lang&&M.lang!==e.lastLang&&(e.lastLang=M.lang,I(e,{type:"language",lang:M.lang}));const{text:v,lang:H,startMs:K}=M,he=(v.match(new RegExp("\\p{Script=Latin}","gu"))||[]).length/Math.max(1,(v.match(new RegExp("\\p{L}","gu"))||[]).length),P=ne.indictransLanguage(H)&&he<.5&&ne.state()!=="error"&&mt(),W=!!e.translateTo&&yt(H,e.translateTo)&&(P||Mt(v,H)&&se.state()!=="error"),te=$.length>1&&Y?Y.filter(q=>q.startMs<K+M.durationMs&&q.startMs+q.durationMs>K):Y;if(I(e,{type:"final",text:v,reason:g,endOfTurn:M.last?C:!1,durationMs:M.durationMs,startMs:K,...H?{lang:H}:{},...W?{translating:!0}:{},...S?{speaker:S}:{},...te?.length?{turns:te}:{},...b||{}}),W){const q=e.translateTo,ae=P?ne:se;ae.state()==="off"&&ae.init({...e.translateLoad,...P?{sessionOptions:ie()}:{}}),e.translations=e.translations.then(async()=>{await ae.ready();const Pe=P?await ne.translate(v,H):await se.translate(v);I(e,{type:"translation",startMs:K,lang:H,to:q,text:Pe||null,...Pe?{}:{failed:!0}})}).catch(()=>{})}}if(e.prints&&!e.speakerLabel&&_&&S?.label){e.prints.push({starts:$.map(M=>M.startMs),vec:Array.from(_.vec),seconds:_.samples/h,label:S.label});for(const M of $)e.shown.set(M.startMs,S.label);(e.pushed||0)-e.regroupedAt>=hn*h&&tt(e)}}else p!==e.lastInterim&&(e.lastInterim=p,I(e,{type:"interim",text:p}))}async function kn(e){try{const t=await B.spans(e),n=t?He(t):[];if(n.length<2)return 0;const o=n[0].local;for(const r of n){if(r.local===o||r.start<dn||r.end-r.start<gn||n.some(i=>i.local===o&&i.end>r.start+pn))continue;const a=Math.round(Math.max(0,r.start-.05)*h);return a>h&&a<e.length-h/2?a:0}}catch{}return 0}function tt(e){if(!e.prints?.length)return;e.regroupedAt=e.pushed||0;const t=gt(e.prints.map((o,r)=>({key:r,vec:o.vec,seconds:o.seconds,label:o.label})),{threshold:pt(U.activeModel())}),n=[];e.prints.forEach((o,r)=>{const a=t.get(r);if(a)for(const i of o.starts)e.shown.get(i)!==a&&(e.shown.set(i,a),n.push({startMs:i,speaker:{label:a}}))}),n.length&&I(e,{type:"speakers",changes:n})}async function bn(e){const t=ge(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(Z=Z.then(()=>De(t,{flush:!0}).catch(()=>{}))),tt(t),await Promise.race([t.translations,new Promise(n=>setTimeout(n,Mn).unref?.())])}finally{if(I(t,{type:"end"}),t.listeners.clear(),G.delete(t.id),t.poll){const n=setTimeout(()=>J.delete(t.id),sn);n.unref?.(),J.set(t.id,{session:t,timer:n})}t.diarizer&&(U.release(),B.release()),t.translateTo&&(se.release(),ne.release()),t.echo&&ye.release(),z.release(),oe.leave(t.echo),G.size===0&&fe()&&R?.arm()}return!0}function ro(){for(const e of G.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);G.clear();for(const e of J.values())clearTimeout(e.timer);J.clear(),R?.disarm(),R=null,w="off",A=null,m=null,D=null,Q=null,L=null}function ao(e,t="test/fake",{warmMs:n=null,dtype:o=null}={}){m=e,A=t,w=e?"ready":"off",V=o,n!==null&&(R=Me({warmMs:n,busy:ce,unload:()=>Te()}),e&&R.arm())}export{an as AUTO_FETCH_MAX_MB,Ke as COMPRESSION_LIMIT,jt as FROM_ENGLISH,Bt as FROM_ENGLISH_RUN_S,Wt as LEAVE_KNOWN,It as LEAVE_SURE,Ft as LOOP_DROP,Jt as PAUSE_SHARE,Be as PIECE_MIN_S,Ut as PIECE_PAUSE_S,h as SAMPLE_RATE,Gt as SURE_ENGLISH,Ge as THIN_SPEAKER_SAMPLES,zt as TO_ENGLISH,Kt as WEAK_ENGLISH_MIN_S,ze as WEAK_SPEAKER_SAMPLES,ro as _reset,ao as _setPipeForTest,Xt as anyLanguageSegment,Tn as clampEndSilence,Ct as collapseLoops,$t as collapseRuns,je as compressionRatio,Qn as createSession,no as decodeNow,Zn as drainEvents,bn as endSession,eo as endedSession,ge as getSession,Wn as health,Vn as init,fe as isReady,Yt as languageGroups,Ot as looksHallucinated,en as modelOnDisk,yn as noiseFloorOf,Qt as pauseCuts,Zt as pauseLevel,In as progress,to as pushAudio,Ln as quietestCut,Vt as relabelGroups,qt as respellEnglish,ue as runtimeDtype,Fe as runtimeName,Se as segmentLanguage,qn as sessionCount,Yn as setModel,wn as silenceGate,Ye as speakerPlan,Bn as state,ie as sttSessionOptions,Ht as sttThreads,Jn as subscribe,oo as toFloat32,Te as unload,Xn as warmPending};
1
+ import{join as at}from"node:path";import{deflateSync as lt}from"node:zlib";import Oe from"node:os";import{existsSync as st,readdirSync as it}from"node:fs";import{randomUUID as ct}from"node:crypto";import{ensureLib as Re,modelRoot as Ce}from"./ner-engine.js";import{runtimeDtype as fe,runtimeName as Fe,DTYPE_SUFFIX as ut}from"./model-runtime.js";import{verifyModelWeights as ft}from"./model-integrity.js";import{DEFAULT_STT_MODEL as $e,isEnglishOnly as _e,sttModelDtype as we,isKnownSttModel as dt,sttModelEngine as j}from"./stt-models.js";import*as V from"./parakeet-engine.js";import*as ye from"./coreml-stt-engine.js";import*as le from"./indic-engine.js";import*as z from"./diarize-engine.js";import*as B from"./segment-engine.js";import{turnsFromSpans as He,mainLocal as Ue,timeByLocal as gt,audioOfLocal as pt}from"@chatpanel/events/speaker-turns.js";import{regroupSpeakers as ht,regroupThreshold as mt}from"@chatpanel/events/speaker-recluster.js";import{diarizeApproxMB as _t}from"./diarize-models.js";import*as se from"./translate-engine.js";import*as oe from"./indictrans-engine.js";import{rawOrtAvailable as wt}from"./ort.js";import*as U from"./vad-engine.js";import*as re from"./echo-pair.js";import*as Me from"./aec-engine.js";import{pickSegmentLanguage as yt,detectTextLanguage as Mt,needsTranslation as Et,localTranslatable as St,normalizeLanguages as Tt,normalizeLanguage as Lt,decodeLanguages as At,lineLanguage as xt,autoCandidates as kt,AUTO_LEARN_CONFIDENCE as bt,AUTO_LEARN_SECONDS as vt,ANY_LANGUAGE_CONFIDENCE as Dt,AUTO_LANGUAGES as Nt}from"@chatpanel/events/speech-language.js";import*as Pt from"@chatpanel/events/speech-language.js";import{makeWarmTimer as Ee}from"./warm-timer.js";const p=16e3,ze=p,Ge=3*p,Ot=2,Rt=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 Ct(e,t){if(t>Ot*p)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?Rt.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}const Ft=12,Se=3;function $t(e){const t=String(e||"").split(/\s+/).filter(Boolean);if(t.length<Se)return{text:String(e||"").trim(),removed:0,total:t.length};const n=a=>a.toLowerCase().replace(/[^\p{L}\p{N}']/gu,""),o=[];let r=0;for(let a=0;a<t.length;){let i=0,c=0;for(let l=1;l<=Ft&&a+l*Se<=t.length;l++){let s=1;for(;a+(s+1)*l<=t.length&&t.slice(a+s*l,a+(s+1)*l).every((f,d)=>n(f)===n(t[a+d]));)s++;s>=Se&&(s-1)*l>i&&(i=(s-1)*l,c=l)}i?(o.push(...t.slice(a,a+c)),r+=i,a+=c+i):(o.push(t[a]),a++)}return{text:o.join(" "),removed:r,total:t.length}}const Ht=.6,Ie=2.4;function Ke(e){const t=Buffer.from(String(e||""),"utf8");return t.length<40?1:t.length/lt(t).length}function Ut(e){return String(e||"").replace(/([^\d\s]{1,8}?)\1{4,}/gu,"$1")}function zt({cores:e=Oe.availableParallelism?.()??Oe.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 ie(e){return{intraOpNumThreads:zt(e),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}const Gt=.12,je=.8,It=.15,Kt=.5,jt=1.2,Be=(e,t)=>e>=Kt||e>=It&&!(t<jt),Bt=.999,Wt=2.5;function We(e={},t=1/0){return Be(e.en??0,t)?"en":Object.entries(e).sort((n,o)=>o[1]-n[1])[0]?.[0]||null}const Xt=.9,Vt=.5;function Xe(e={},t=1/0,n=null){const o=We(e,t);if(!o||o==="en")return o;const r=e[o]??0;return r>=Xt?(n?.add(o),o):r>=Vt&&n?.has(o)?o:"en"}function Yt(e,t=[]){const n=[];return e.forEach((o,r)=>{const a=t[r]??o.lang,i=n[n.length-1];i&&i.lang===a?i.to=o.to:n.push({from:o.from,to:o.to,lang:a})}),n}function qt(e,{base:t=null,rate:n=p}={}){const o=e||[],r=l=>{const[s,f]=Object.entries(l.scores||{}).sort((d,k)=>k[1]-d[1])[0]||[];return s&&s!=="en"&&f>=Bt?s:null},a=new Array(o.length).fill(null);for(let l=0;l<o.length;){const s=r(o[l]);let f=l+1;if(s)for(;f<o.length&&r(o[f])===s;)f++;if(s&&(o[f-1].to-o[l].from)/n>=Wt)for(let d=l;d<f;d++)a[d]=s;l=f}const i=[];let c=t;return o.forEach((l,s)=>{a[s]?c=a[s]:c!=="en"&&Be(l.scores?.en??0,(l.to-l.from)/n)&&(c="en");const f=i[i.length-1];f&&f.lang===c?f.to=l.to:i.push({from:l.from,to:l.to,lang:c})}),i}async function Qt(e,t,n){const{spelledEnglish:o,isSpelledEnglish:r,SPELLED_ENGLISH_MIN:a,SPELLED_SHAPE_MIN:i}=Pt;if(typeof o!="function")return e;const c=[];let l=!1;for(const s of e){const f=o(s.text);if(!s.lang||s.lang==="en"||f.english<a&&!r(s.text)){c.push(s);continue}const d=f.words>=i&&f.shaped===f.words,k=[];for(let u=0;u+1<t.length;u++)t[u]>=s.from&&t[u+1]<=s.to&&k.push([t[u],t[u+1]]);if(k.length<2||d){const u=r(s.text)?await n(s.from,s.to,"en"):"";u?(c.push({...s,text:u,lang:"en"}),l=!0):c.push(s);continue}const T=[];for(const[u,w]of k){const M=await n(u,w,s.lang),G=o(M),N=G.words>0&&G.words-G.shaped<=(G.english>=1&&G.words>=3?1:0);T.push({from:u,to:w,text:M,near:N,lang:r(M)?"en":s.lang})}for(let u=!0;u;)u=!1,T.forEach((w,M)=>{w.lang!=="en"&&w.near&&(T[M-1]?.lang==="en"||T[M+1]?.lang==="en")&&(w.lang="en",u=!0)});if(!T.some(u=>u.lang==="en")){c.push(s);continue}const L=[];for(const u of T){const w=L[L.length-1];w&&w.lang===u.lang?(w.to=u.to,w.n++):L.push({from:u.from,to:u.to,lang:u.lang,n:1,text:u.text})}for(const u of L){const w=u.n===1&&u.lang===s.lang?u.text:await n(u.from,u.to,u.lang);w&&c.push({from:u.from,to:u.to,lang:u.lang,text:w})}l=!0}return l?c.reduce((s,f)=>{const d=s[s.length-1];return d&&d.lang===f.lang&&d.to===f.from?s[s.length-1]={...d,to:f.to,text:`${d.text} ${f.text}`}:s.push(f),s},[]):e}function Jt(e,t,{frame:n=Math.round(.03*p),minPause:o=Gt*p,minPiece:r=je*p}={}){const a=[];let i=0,c=-1;for(let l=0;l+n<=e;l+=n){const s=t(l,l+n)===!1;if(s&&c<0&&(c=l),(!s||l+2*n>e)&&c>=0){const f=s?l+n:l,d=Math.round((c+f)/2);f-c>=o&&d-i>=r&&e-d>=r&&(a.push(d),i=d),c=-1}}return a}const Zt=.12;function en(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]=te(e,r*t,(r+1)*t);return o.sort(),Math.max(1e-4,o[Math.floor(n*.9)]*Zt)}let y="off",x=null,_=null,D=null,J=null,A=null,Y=null,R=null;function tn(e=x||$e,t=we(e)||fe()){if(j(e)==="parakeet-tdt")return V.parakeetOnDisk(e,V.parakeetDtype(t));if(j(e)==="coreml-tdt")return ye.coremlOnDisk(e);if(j(e)==="indic-canary")return le.indicOnDisk();const n=at(Ce(),...e.split("/"),"onnx");if(!st(n))return!1;const o=ut[t]??"";try{const r=it(n);return r.includes(`encoder_model${o}.onnx`)&&r.some(a=>a===`decoder_model_merged${o}.onnx`||a===`decoder_model${o}.onnx`)}catch{return!1}}function Wn(){return y}function de(){return y==="ready"&&!!_}function Xn(){return A}function Vn(){return{configured:y!=="off",ok:de(),state:y,model:x,dtype:Y,runtime:Fe(),error:D,warmMs:R?.warmMs??null,vad:U.state()}}function Yn(){return!!R?.pending()}function ce(){return I.size>0||y==="loading"||y==="downloading"}async function Te({log:e=()=>{}}={}){if(ce())return!1;R?.disarm();const t=_;if(_=null,J=null,Y=null,A=null,D=null,y="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((R?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function Ve(e){return e.then(t=>(t&&!ce()&&R?.arm(),t))}async function Ye(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null,licenseAccepted:r=null}={}){if(j(e)==="parakeet-tdt")return nn(e,{log:t,allowDownload:n,dtype:o});if(j(e)==="coreml-tdt")return rn(e,{log:t,allowDownload:n});if(j(e)==="indic-canary")return an(e,{log:t,allowDownload:n,licenseAccepted:r});const a=_,i=x;let c;try{c=await Re()}catch(T){return y="error",D=`engine load failed: ${T.message}`,t(`[stt] transformers.js not available (${T.message}) — dictation falls back to the browser engine`),!1}const s=(o&&o!=="auto"?o:null)||we(e)||fe(),f=tn(e,s);if(c.env.allowRemoteModels=f?!1:!!n,!f&&!n)return y="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const d=c.env.remoteHost,k=!dt(e);if(!f&&k)try{c.env.remoteHost="https://huggingface.co/"}catch{}y=f?"loading":"downloading",f||(A={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${k?", from Hugging Face":""})…`));try{const T=u=>{if(!u)return;const w=typeof u.progress=="number"?Math.round(u.progress):A?.pct??0;u.status==="progress"||u.status==="download"||u.status==="initiate"?A={model:e,file:u.file||A?.file||null,pct:w}:u.status==="done"&&u.file&&t(`[stt] fetched ${u.file}`)};let L;try{L=await c.pipeline("automatic-speech-recognition",e,{dtype:s,progress_callback:T,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:ie()}})}catch(u){if(f||k||!n)throw u;t(`[stt] mirror fetch failed (${String(u.message).slice(0,80)}) — retrying from Hugging Face…`),c.env.remoteHost="https://huggingface.co/",c.env.allowRemoteModels=!0,L=await c.pipeline("automatic-speech-recognition",e,{dtype:s,progress_callback:T,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:ie()}})}if(!f)try{ft(e,{modelsDir:Ce(),log:t})}catch(u){try{await L.dispose?.()}catch{}throw u}if(_=L,x=e,y="ready",D=null,A=null,Y=s,a&&a!==L)try{await a.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${s} (in-process, offline) — local dictation active`),!0}catch(T){return D=T.message,A=null,a?(_=a,x=i,y="ready"):y="error",t(`[stt] model load failed (${T.message})${a?" — keeping previous model":""}`),!1}finally{try{c.env.remoteHost=d}catch{}}}async function nn(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null}={}){const r=_,a=x,i=V.parakeetDtype(o&&o!=="auto"?o:on()),c=V.parakeetOnDisk(e,i);if(!c&&!n)return y="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;y=c?"loading":"downloading",c||(A={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const l=await V.loadRecognizer({modelId:e,dtype:i,allowDownload:n,log:t,sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:ie(),onProgress:f=>{A={model:e,file:f.file||null,pct:typeof f.pct=="number"?f.pct:A?.pct??0}}}),s=async f=>({text:await l.transcribe(f)});if(s.__transducer=!0,s.dispose=()=>l.dispose(),_=s,x=e,y="ready",D=null,A=null,Y=i,r&&r!==s)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(l){return D=l.message,A=null,r?(_=r,x=a,y="ready"):y="error",t(`[stt] model load failed (${l.message})${r?" — keeping previous model":""}`),!1}}function on(){return V.PARAKEET_DEFAULT_DTYPE}const qe="fp16";async function rn(e,{log:t=()=>{},allowDownload:n=!0}={}){const o=_,r=x,a=ye.coremlOnDisk(e);if(!a&&!n)return y="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;y=a?"loading":"downloading",a||(A={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let i=null;const c=await ye.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:l=>{A={model:e,file:l.file||null,pct:typeof l.pct=="number"?l.pct:A?.pct??0}},onExit:l=>{_===i&&(_=null,J=null,y="error",D=l,R?.disarm(),t(`[stt] ${l} — reloads on the next dictation`))}});if(i=async l=>({text:await c.transcribe(l)}),i.__transducer=!0,i.dispose=()=>c.dispose(),_=i,x=e,y="ready",D=null,A=null,Y=qe,o&&o!==i)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} (Core ML on the Neural Engine, helper ${c.version}, windows ${c.windows.join("/")} s, offline) — local dictation active`),!0}catch(i){return D=i.message,A=null,o?(_=o,x=r,y="ready"):y="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}async function an(e,{log:t=()=>{},allowDownload:n=!0,licenseAccepted:o=null}={}){const r=_,a=x,i=le.indicOnDisk();if(!i&&!n)return y="error",D="model not on disk and downloads disabled",!1;y=i?"loading":"downloading",i||(A={model:e,file:null,pct:0},t(`[stt] downloading ${e} (one-time, ~1.5 GB, from Hugging Face)…`));try{i||await le.ensureIndicFiles({licenseAccepted:o,log:t,onProgress:s=>{A={model:e,file:s.file,pct:s.pct}}});const c=await le.loadRecognizer({sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:ie(),log:t}),l=async(s,f={})=>c.transcribe(s,f);if(l.identify=(s,f)=>c.identify(s,f),l.__transducer=!0,l.__indic=!0,l.dispose=()=>c.dispose(),_=l,x=e,y="ready",D=null,A=null,Y="int8",r&&r!==l)try{await r.dispose?.()}catch{}return t(`[stt] ready — ${e} (Indic-Transcribe, int8, in-process, offline) — ${le.INDIC_LICENSE.attribution}`),!0}catch(c){return D=c.message,A=null,r?(_=r,x=a,y="ready"):y="error",t(`[stt] model load failed (${c.message})${r?" — keeping previous model":""}`),!1}}const ln=30;function Qe({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:o=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof o=="number"&&o<=ln||e==="download"?{allowDownload:!0}:null}function Le(e,{log:t=()=>{},warmMs:n,allowDownload:o=!0}={}){const r=Qe({mode:e,onDisk:z.modelOnDisk(),ready:z.isReady(),approxMB:_t(z.activeModel())});if(r&&z.init({allowDownload:r.allowDownload&&o!==!1,warmMs:n,onLog:t}),e==="off"||Ae)return;const a=Qe({mode:e,onDisk:B.modelOnDisk(),ready:B.isReady(),approxMB:B.SEGMENT_MODEL_APPROX_MB});a&&B.init({allowDownload:a.allowDownload&&o!==!1,warmMs:n,onLog:t})}let Ae=!1,xe=null;function ke(e={},{log:t=()=>{}}={}){e.vad!==!1&&(xe={vad:e.vad,allowDownload:e.allowDownload,warmMs:e.warmMs},(U.state()==="off"||U.state()==="error")&&U.init({allowDownload:e.allowDownload!==!1,warmMs:e.warmMs,onLog:t}))}function qn(e={}){if(J&&y!=="error")return J;const t=typeof e.onLog=="function"?e.onLog:()=>{};return x=e.model||$e,Ae=e.segment===!1,y="loading",R=Ee({warmMs:e.warmMs,busy:ce,log:t,unload:()=>Te({log:t})}),J=Ve(Ye(x,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype,licenseAccepted:e.licenseAccepted||null})).then(n=>(n&&(Le(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),ke(e,{log:t})),n)),J}async function Qn(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(Ae=t.segment===!1);const o=j(e)==="parakeet-tdt"?V.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:V.PARAKEET_DEFAULT_DTYPE):j(e)==="coreml-tdt"?qe:j(e)==="indic-canary"?"int8":t.dtype&&t.dtype!=="auto"?t.dtype:we(e)||fe();if(e===x&&de()&&Y===o)return Le(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;R??=Ee({warmMs:t.warmMs,busy:ce,log:n,unload:()=>Te({log:n})});const r=await Ve(Ye(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype,licenseAccepted:t.licenseAccepted||null}));return r&&(Le(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),ke(t,{log:n})),r}const sn=8,cn=12e4,un=6e4,fn=1200,ue=12,dn=3,gn=1,pn=.8,hn=.5,mn=60,be=700,_n=.3,ve=.008,wn=.002,yn=4;function Mn(e){return e>0?Math.min(ve,Math.max(wn,e*yn)):ve}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]=te(e,r*t,(r+1)*t);return o.sort(),o[Math.floor(n*.1)]}const Je=30,Sn=15e3,I=new Map,Z=new Map;let ee=Promise.resolve();function Jn(){return I.size}const Tn=300,Ln=3e3;function An(e){const t=Number(e);return Number.isFinite(t)?Math.min(Ln,Math.max(Tn,Math.round(t))):be}function Zn({lang:e,langs:t=null,translateTo:n=null,translateLoad:o=null,echo:r=null,redact:a=!1,diarize:i=!1,vectors:c=!1,speakerLabel:l=null,endSilenceMs:s=be,interims:f=!0,remote:d=null,poll:k=!1,format:T="f32"}={}){if(I.size>=sn){const M=new Error("too many concurrent dictation sessions");throw M.code="too_many_sessions",M}const L=Array.isArray(t)?Tt(t):null,u=typeof e=="string"&&e?e.slice(0,12):null,w={id:ct(),format:T==="pcm16"?"pcm16":"f32",endSilenceMs:An(s),lang:L?L.length===1?L[0]:L.length?null:u:u,langs:L,lastLang:null,lastDecoded:null,learned:new Set,translateTo:Lt(n)||null,translateLoad:o||{},translations:Promise.resolve(),echo:r&&typeof r=="object"?re.join(r.group,r.role):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!a,diarize:!!i,speakerLabel:typeof l=="string"&&l?l.slice(0,40):null,diarizer:i?new z.Diarizer:null,prints:i?[]:null,shown:new Map,regroupedAt:0,vectors:!!i&&c===!0,remote:d||null,interims:f!==!1&&!d,chunks:[],samples:0,listeners:new Set,poll:k?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return I.set(w.id,w),R?.disarm(),w.diarizer&&(z.retain(),B.retain()),w.translateTo&&(se.retain(),oe.retain()),w.echo&&Me.retain(),U.retain(),xe&&(U.state()==="off"||U.state()==="error")&&ke(xe),Ze(w),{id:w.id}}function ge(e){return I.get(String(e||""))||null}function eo(e,t){const n=ge(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function W(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function to(e){const t=String(e||""),n=I.get(t);if(n)return n.poll?n.poll.splice(0):null;const o=Z.get(t);return o?(clearTimeout(o.timer),Z.delete(t),o.session.poll.splice(0)):null}function no(e){return Z.get(String(e||""))?.session||null}function Ze(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>Dn(e.id).catch(()=>{}),un),e.idleTimer.unref?.()}function oo(e,t){const n=ge(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(Ze(n),n.echo?.role==="mic"){re.pushMic(n.echo,t),et(n);return}n.echo?.role==="reference"&&re.pushReference(n.echo,t),n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,et(n)}}function ro(e){const t=ge(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),ee=ee.then(()=>De(t).catch(()=>{})),ee)}function ao(e,t="f32"){if(t==="pcm16"){const r=new Float32Array(Math.floor(e.length/2));for(let a=0;a<r.length;a++)r[a]=e.readInt16LE(a*2)/32768;return r}const n=e.length-e.length%4,o=new Float32Array(n/4);for(let r=0;r<o.length;r++)o[r]=e.readFloatLE(r*4);return o}function et(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+fn-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,ee=ee.then(()=>De(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function pe(e,t,n){const o=e.samples-t,r=[];n&&r.push(n),o>0&&r.push(tt(e).subarray(t)),e.chunks=r,e.samples=r.reduce((a,i)=>a+i.length,0),e.lastInterim=""}function tt(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 xn(e,t,n){const o=p/100,r=Math.max(0,e.length-t),a=Math.floor((e.length-r)/o),i=Math.max(1,Math.round(n/o));if(a<=i)return 0;const c=new Float32Array(a);for(let d=0;d<a;d++){let k=0;const T=r+d*o;for(let L=0;L<o;L++)k+=e[T+L]*e[T+L];c[d]=k/o}let l=-1,s=1/0,f=0;for(let d=0;d<i;d++)f+=c[d];for(let d=0;d+i<=a;d++)d>0&&(f+=c[d+i-1]-c[d-1]),f<s&&(s=f,l=d);return l<0?0:r+Math.round((l+i/2)*o)}function te(e,t=0,n=e.length){let o=0;const r=Math.max(1,n-t);for(let a=t;a<n;a++)o+=e[a]*e[a];return Math.sqrt(o/r)}function kn(e,t=ve){const n=Math.round(.02*p);let o=0,r=e.length;for(let a=0;a+n<=e.length;a+=n)if(te(e,a,a+n)>=t){o=a;break}for(let a=e.length-n;a>=0;a-=n)if(te(e,a,a+n)>=t){r=a+n;break}return r>o?e.subarray(o,r):e}async function nt(e){try{const t=await Re(),n=_?.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 _.processor(o),a=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),i=await _.model({...r,decoder_input_ids:a}),c={};for(const[l,s]of Object.entries(n.lang_to_id))c[l.slice(2,-2)]=Number(i.logits.data[s]);return c}catch{return null}}async function bn(e){const t=await nt(e);if(!t)return null;let n=null,o=-1/0;for(const[r,a]of Object.entries(t))a>o&&(o=a,n=r);return n}async function De(e,{flush:t=!1}={}){if(e.closed&&!t)return;if(e.echo?.role==="mic"){const g=await re.drain(e.echo,{force:t});g.length&&(e.chunks.push(g),e.samples+=g.length,e.pushed+=g.length)}if(!e.remote&&!de()||!e.samples)return;e.lastDecodeAt=Date.now();let n=tt(e);const o=n.length,r=Math.max(0,(e.pushed||0)-e.samples),a=Math.round((e.endSilenceMs||be)/1e3*p),i=En(n);i!==null&&(e.noiseFloor==null||i<e.noiseFloor)&&(e.noiseFloor=i);const c=Mn(e.noiseFloor);let l=null,s=null,f=!1;U.isReady()&&(e.vad||=U.createStream(),await e.vad.advance(n,r)&&(l=e.vad.speechIn(r,r+n.length,U.ONSET),f=l===!0&&e.vad.voicedIn(r,r+n.length,U.OFFSET)<_n,n.length>a&&(s=e.vad.speechIn(r+n.length-a,r+n.length,U.OFFSET))));const d=n.length>a&&(s!==null?!s:te(n,n.length-a)<c);if(l===!1||l===null&&te(n)<c){n.length>p*5&&(e.chunks=[n.subarray(n.length-p)],e.samples=p);return}if(f){!t&&n.length>ue*p&&(e.chunks=[n.subarray(n.length-p)],e.samples=p);return}let k=!1,T=null;if(e.diarizer&&!e.speakerLabel&&!t&&B.isReady()&&n.length>=dn*p){const g=await vn(n);g&&(T=n.subarray(g),n=n.subarray(0,g),k=!0)}if(!e.interims&&!t&&!d&&!k&&n.length<ue*p)return;if(!k&&!t&&!d&&o>=ue*p&&o<Je*p){const g=xn(n,3*p,Math.round(.2*p));g>0&&g<n.length&&(T=n.subarray(g),n=n.subarray(0,g))}const L=!e.remote&&!_e(x)&&!_?.__transducer;if(L&&!e.langs&&!e.lang&&!e.langTried&&n.length>=p){e.langTried=!0;const g=await bn(n);g&&(e.lang=g,W(e,{type:"language",lang:g}))}const u=t||d||k||o>=ue*p;let w=e.lang;if(L&&e.langs&&!e.lang){const g=e.langs.length>0,C=g?At(e.langs):kt([...e.learned]);if(C.length===1)w=C[0];else if(w=C.includes(e.lastDecoded)?e.lastDecoded:null,(u||!w)&&n.length>=p/2){const F=await nt(n);if(F){const S=yt({scores:F,allowed:C,seconds:n.length/p,last:e.lastDecoded});w=!g&&!S.inherited&&S.confidence<Dt?e.lastDecoded||"en":S.lang,!g&&u&&!S.inherited&&S.confidence>=bt&&n.length>=vt*p&&e.learned.add(S.lang)}}u&&w&&(e.lastDecoded=w)}let M="",G=null,N=null,he=null;try{if(e.remote){const g=await e.remote.transcribe(n,{lang:e.lang,langs:e.langs});M=g.text,he=g.lang||null}else{const g=_.__indic?e.langs?.length?{langs:[...new Set([...e.langs,"en"])],last:e.lastLang,choose:(h,m)=>Xe(h,m,e.learned)}:e.lang?{lang:e.lang}:{langs:[...Nt],last:e.lastLang,choose:(h,m)=>Xe(h,m,e.learned)}:_e(x)?{}:{language:w||void 0,task:"transcribe"},C=_.__indic&&_.identify&&u&&g.langs&&n.length>=2*je*p?Jt(n.length,(h=>(m,b)=>te(n,m,b)>=h)(en(n))):[],F=[0,...C,n.length];let S=null;const q=g.choose||We;if(C.length){const h=await _.identify(n,{langs:g.langs}),m=[];for(let b=0;b+1<F.length;b++){const O=await _.identify(n.subarray(F[b],F[b+1]),{langs:g.langs});m.push({from:F[b],to:F[b+1],scores:O?.scores||{}})}if(S=qt(m,{base:h?.scores?q(h.scores,n.length/p):null}),S.length>1){const b=[];for(let O=0;O<S.length;O++){const $=S[O],E=$.lang&&$.lang!=="en"&&(S[O-1]?.lang==="en"||S[O+1]?.lang==="en");b.push(E?q((await _.identify(n.subarray($.from,$.to),{langs:g.langs}))?.scores||{},($.to-$.from)/p):$.lang)}S=Yt(S,b)}S.length<2&&(S=null)}if(S){N=[];for(const h of S){const m=await _(n.subarray(h.from,h.to),h.lang?{lang:h.lang}:{...g}),b=String(m?.text||"").trim(),O=m?.lang||h.lang||null;b&&N.push({text:b,lang:O,from:h.from,to:h.to}),O&&(g.last=O)}}else{const h=await _(n,g);M=String(h?.text||"").trim(),_.__indic&&(G=h?.lang||null),_.__indic&&M&&(N=[{text:M,lang:G,from:0,to:n.length}])}if(N&&u&&g.langs&&(N=await Qt(N,F,async(h,m,b)=>String((await _(n.subarray(h,m),{lang:b}))?.text||"").trim())),N){M=N.map(m=>m.text).join(" ");const h=new Map;for(const m of N)m.lang&&h.set(m.lang,(h.get(m.lang)||0)+(m.to-m.from));G=[...h].sort((m,b)=>b[1]-m[1])[0]?.[0]||null,(N.length<2||h.size<2)&&(N=null)}}}catch(g){W(e,{type:"error",code:"decode_failed",message:g.message,fatal:!1}),u&&pe(e,o,T);return}if(!M){u&&pe(e,o,T);return}{const g=$t(M);if(g.removed&&g.removed/g.total>=Ht&&g.total>=12?M="":M=g.text,M&&Ke(M)>Ie){const C=Ut(M);M=C.replace(/[\s\p{P}]/gu,"").length<12||Ke(C)>Ie?"":C}if(!M){u&&pe(e,o,T);return}}const rt=o>=ue*p,Ne=o>=Je*p;if(t||d||k||rt||Ne){const g=t?"flush":d?"silence":k?"speaker":Ne?"overflow":"length",C=g==="flush"||g==="silence"||g==="speaker";pe(e,o,T);const F=kn(n,c);if(Ct(M,F?F.length:0)||e.echo?.role==="mic"&&Me.mostlyEcho(re.verdict(e.echo,r,r+n.length)))return;let S=null,q=null,h=null;if(e.diarizer)try{const E=e.speakerLabel?null:await B.spans(n),v=E?He(E):[];if(v.length){const H=new Map,K=new Map;for(const{local:P}of gt(v)){const X=pt(n,v,P),ne=X.length?await z.embed(X):null;ne&&K.set(P,{vec:ne,samples:X.length});const Q=X.length<ze,ae=X.length<Ge;H.set(P,e.diarizer.assign(ne,{pinnedLabel:null,weak:Q,thin:ae}))}const me=Math.round(r/p*1e3);q=v.map(P=>({startMs:me+Math.round(P.start*1e3),durationMs:Math.round((P.end-P.start)*1e3),speaker:H.get(P.local)})).filter(P=>P.speaker),S=H.get(Ue(v))||null,S&&(h=K.get(Ue(v))||null)}}catch{}if(e.diarizer&&!S)try{const E=F,v=E?await z.embed(E):null,H=!!E&&E.length<ze,K=!!E&&E.length<Ge;v&&(h={vec:v,samples:E.length}),S=e.diarizer.assign(v,{pinnedLabel:e.speakerLabel,weak:H,thin:K})}catch{}let m=null;(e.langs||e.translateTo)&&(G?m=G:he?m=he:_e(x)&&!e.remote?m="en":L?m=xt(M,w||e.lang)||null:m=e.lang||Mt(M,{allowed:e.langs||[],last:e.lastLang}).lang,m&&m!==e.lastLang&&(e.lastLang=m,W(e,{type:"language",lang:m})));const b=e.vectors&&h?{vec:z.plainVector(h.vec),seconds:Math.round(h.samples/p*100)/100,speakerModel:z.activeModel()}:null,O=Math.round(r/p*1e3),$=N&&(e.langs||e.translateTo)?N.map((E,v)=>({text:E.text,lang:E.lang,startMs:O+Math.round(E.from/p*1e3),durationMs:Math.round((E.to-E.from)/p*1e3),last:v===N.length-1})):[{text:M,lang:m,startMs:O,durationMs:Math.round(n.length/p*1e3),last:!0}];for(const E of $){$.length>1&&E.lang&&E.lang!==e.lastLang&&(e.lastLang=E.lang,W(e,{type:"language",lang:E.lang}));const{text:v,lang:H,startMs:K}=E,me=(v.match(new RegExp("\\p{Script=Latin}","gu"))||[]).length/Math.max(1,(v.match(new RegExp("\\p{L}","gu"))||[]).length),P=oe.indictransLanguage(H)&&me<.5&&oe.state()!=="error"&&wt(),X=!!e.translateTo&&Et(H,e.translateTo)&&(P||St(v,H)&&se.state()!=="error"),ne=$.length>1&&q?q.filter(Q=>Q.startMs<K+E.durationMs&&Q.startMs+Q.durationMs>K):q;if(W(e,{type:"final",text:v,reason:g,endOfTurn:E.last?C:!1,durationMs:E.durationMs,startMs:K,...H?{lang:H}:{},...X?{translating:!0}:{},...S?{speaker:S}:{},...ne?.length?{turns:ne}:{},...b||{}}),X){const Q=e.translateTo,ae=P?oe:se;ae.state()==="off"&&ae.init({...e.translateLoad,...P?{sessionOptions:ie()}:{}}),e.translations=e.translations.then(async()=>{await ae.ready();const Pe=P?await oe.translate(v,H):await se.translate(v);W(e,{type:"translation",startMs:K,lang:H,to:Q,text:Pe||null,...Pe?{}:{failed:!0}})}).catch(()=>{})}}if(e.prints&&!e.speakerLabel&&h&&S?.label){e.prints.push({starts:$.map(E=>E.startMs),vec:Array.from(h.vec),seconds:h.samples/p,label:S.label});for(const E of $)e.shown.set(E.startMs,S.label);(e.pushed||0)-e.regroupedAt>=mn*p&&ot(e)}}else M!==e.lastInterim&&(e.lastInterim=M,W(e,{type:"interim",text:M}))}async function vn(e){try{const t=await B.spans(e),n=t?He(t):[];if(n.length<2)return 0;const o=n[0].local;for(const r of n){if(r.local===o||r.start<gn||r.end-r.start<pn||n.some(i=>i.local===o&&i.end>r.start+hn))continue;const a=Math.round(Math.max(0,r.start-.05)*p);return a>p&&a<e.length-p/2?a:0}}catch{}return 0}function ot(e){if(!e.prints?.length)return;e.regroupedAt=e.pushed||0;const t=ht(e.prints.map((o,r)=>({key:r,vec:o.vec,seconds:o.seconds,label:o.label})),{threshold:mt(z.activeModel())}),n=[];e.prints.forEach((o,r)=>{const a=t.get(r);if(a)for(const i of o.starts)e.shown.get(i)!==a&&(e.shown.set(i,a),n.push({startMs:i,speaker:{label:a}}))}),n.length&&W(e,{type:"speakers",changes:n})}async function Dn(e){const t=ge(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(ee=ee.then(()=>De(t,{flush:!0}).catch(()=>{}))),ot(t),await Promise.race([t.translations,new Promise(n=>setTimeout(n,Sn).unref?.())])}finally{if(W(t,{type:"end"}),t.listeners.clear(),I.delete(t.id),t.poll){const n=setTimeout(()=>Z.delete(t.id),cn);n.unref?.(),Z.set(t.id,{session:t,timer:n})}t.diarizer&&(z.release(),B.release()),t.translateTo&&(se.release(),oe.release()),t.echo&&Me.release(),U.release(),re.leave(t.echo),I.size===0&&de()&&R?.arm()}return!0}function lo(){for(const e of I.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);I.clear();for(const e of Z.values())clearTimeout(e.timer);Z.clear(),R?.disarm(),R=null,y="off",x=null,_=null,D=null,J=null,A=null}function so(e,t="test/fake",{warmMs:n=null,dtype:o=null}={}){_=e,x=t,y=e?"ready":"off",Y=o,n!==null&&(R=Ee({warmMs:n,busy:ce,unload:()=>Te()}),e&&R.arm())}export{ln as AUTO_FETCH_MAX_MB,Ie as COMPRESSION_LIMIT,Bt as FROM_ENGLISH,Wt as FROM_ENGLISH_RUN_S,Vt as LEAVE_KNOWN,Xt as LEAVE_SURE,Ht as LOOP_DROP,_n as MIN_VOICED_S,Zt as PAUSE_SHARE,je as PIECE_MIN_S,Gt as PIECE_PAUSE_S,p as SAMPLE_RATE,Kt as SURE_ENGLISH,Ge as THIN_SPEAKER_SAMPLES,It as TO_ENGLISH,jt as WEAK_ENGLISH_MIN_S,ze as WEAK_SPEAKER_SAMPLES,lo as _reset,so as _setPipeForTest,Xe as anyLanguageSegment,An as clampEndSilence,$t as collapseLoops,Ut as collapseRuns,Ke as compressionRatio,Zn as createSession,ro as decodeNow,to as drainEvents,Dn as endSession,no as endedSession,ge as getSession,Vn as health,qn as init,de as isReady,qt as languageGroups,Ct as looksHallucinated,tn as modelOnDisk,En as noiseFloorOf,Jt as pauseCuts,en as pauseLevel,Xn as progress,oo as pushAudio,xn as quietestCut,Yt as relabelGroups,Qt as respellEnglish,fe as runtimeDtype,Fe as runtimeName,We as segmentLanguage,Jn as sessionCount,Qn as setModel,Mn as silenceGate,Qe as speakerPlan,Wn as state,ie as sttSessionOptions,zt as sttThreads,eo as subscribe,ao as toFloat32,Te as unload,Yn as warmPending};
package/src/vad-engine.js CHANGED
@@ -1 +1 @@
1
- import{verifyFresh as b}from"./model-integrity.js";import{existsSync as k}from"node:fs";import{join as O}from"node:path";import{ensureLib as F,modelRoot as v,withModelSource as S}from"./ner-engine.js";import{makeWarmTimer as R}from"./warm-timer.js";import{engineLoadOptions as V}from"./ort.js";const h="onnx-community/silero-vad",H=2.2,D=16e3,i=512,N=.5,J=.35,P=.05,I=40,B=62;let o="off",f=null,M=null,c=null,g=null,w=null,d=null,x=0,y=0,_=null;function Q(){return o}function L(){return o==="ready"&&(!!f||!!_)}function Y(){return w}function Z(){return{configured:o!=="off",ok:L(),state:o,model:h,error:c,warmMs:d?.warmMs??null}}function A(){return y>0||x>0||o==="loading"||o==="downloading"}function ee(){x++,d?.disarm()}function te(){x=Math.max(0,x-1),x===0&&y===0&&L()&&d?.arm()}function G(){return k(O(v(),...h.split("/"),"onnx","model.onnx"))}async function W({log:e=()=>{}}={}){if(A())return!1;d?.disarm();const n=f;if(f=null,g=null,w=null,c=null,o="off",n){try{await n.dispose?.()}catch{}e("[vad] idle — model unloaded")}return!0}async function j({log:e=()=>{},allowDownload:n=!0}={}){try{M=await F()}catch(r){return o="error",c=r.message,!1}const t=G();if(!t&&!n)return o="error",c="model not on disk and downloads disabled",!1;o=t?"loading":"downloading",t||(w={model:h,file:null,pct:0},e(`[vad] downloading ${h} (one-time, ~2 MB)…`));try{return f=await S({host:t?null:"https://huggingface.co/",allowRemote:!t},r=>r.AutoModel.from_pretrained(h,{config:{model_type:"custom"},dtype:"fp32",...V({threads:1})})),await b(!t,h,{modelsDir:v(),log:e,dispose:async()=>{await f?.dispose?.(),f=null}}),o="ready",c=null,w=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,w=null,o="error",e(`[vad] load failed (${r.message}) — the energy gate decides, as before`),!1}}function ne(e={}){if(g&&o!=="error")return g;o="loading";const n=typeof e.onLog=="function"?e.onLog:()=>{};return d=R({warmMs:e.warmMs,busy:A,log:n,unload:()=>W({log:n})}),g=j({log:n,allowDownload:e.allowDownload!==!1}).then(t=>(t&&!A()&&d?.arm(),t)),g}function X(e){if(!e.length)return 1;const n=[...e].sort((r,E)=>r-E),t=n[Math.floor(n.length*.9)]||0;return t>0?Math.min(I,Math.max(1,P/t)):1}function oe(){let e=null,n=0;const t=new Map,r=[],E=Math.ceil(90*D/i);async function T(l){let s=0;for(let u=0;u<l.length;u++)s+=l[u]*l[u];r.push(Math.sqrt(s/l.length)),r.length>B&&r.shift();const p=X(r),a=p===1?l:l.map(u=>u*p);if(_)return _(a);e||=new M.Tensor("float32",new Float32Array(256),[2,1,128]);const m=await f({input:new M.Tensor("float32",a,[1,i]),sr:new M.Tensor("int64",[BigInt(D)],[]),state:e});return e=m.stateN,Number(m.output.data[0])}return{async advance(l,s){if(!L())return!1;const p=s+l.length;n<s&&(n=Math.ceil(s/i)*i),y++;try{for(;n+i<=p;n+=i){const a=n-s;t.set(n/i,await T(l.slice(a,a+i)))}}catch{return!1}finally{y--}for(const a of t.keys()){if(t.size<=E)break;t.delete(a)}return!0},speechIn(l,s,p=N){let a=!1;for(let m=Math.floor(l/i);m*i<s;m++){const u=t.get(m);if(u!==void 0&&(a=!0,u>=p))return!0}return a?!1:null},_probs:t}}function re(){d?.disarm(),d=null,x=0,y=0,o="off",f=null,_=null,c=null,g=null,w=null}function le(e){_=e||null,o=e?"ready":"off"}export{h as DEFAULT_VAD_MODEL,i as FRAME,I as LEVEL_MAX_GAIN,P as LEVEL_TARGET,B as LEVEL_WINDOW,J as OFFSET,N as ONSET,D as SAMPLE_RATE,H as VAD_MODEL_APPROX_MB,re as _reset,le as _setForTest,oe as createStream,Z as health,ne as init,L as isReady,X as levelGain,G as modelOnDisk,Y as progress,te as release,ee as retain,Q as state,W as unload};
1
+ import{verifyFresh as O}from"./model-integrity.js";import{existsSync as F}from"node:fs";import{join as S}from"node:path";import{ensureLib as R,modelRoot as T,withModelSource as V}from"./ner-engine.js";import{makeWarmTimer as I}from"./warm-timer.js";import{engineLoadOptions as N}from"./ort.js";const h="onnx-community/silero-vad",J=2.2,L=16e3,s=512,b=.5,Q=.35,P=.05,B=40,G=62;let o="off",c=null,M=null,m=null,g=null,w=null,p=null,x=0,y=0,_=null;function Y(){return o}function A(){return o==="ready"&&(!!c||!!_)}function Z(){return w}function ee(){return{configured:o!=="off",ok:A(),state:o,model:h,error:m,warmMs:p?.warmMs??null}}function v(){return y>0||x>0||o==="loading"||o==="downloading"}function te(){x++,p?.disarm()}function ne(){x=Math.max(0,x-1),x===0&&y===0&&A()&&p?.arm()}function W(){return F(S(T(),...h.split("/"),"onnx","model.onnx"))}async function j({log:e=()=>{}}={}){if(v())return!1;p?.disarm();const n=c;if(c=null,g=null,w=null,m=null,o="off",n){try{await n.dispose?.()}catch{}e("[vad] idle — model unloaded")}return!0}async function X({log:e=()=>{},allowDownload:n=!0}={}){try{M=await R()}catch(r){return o="error",m=r.message,!1}const t=W();if(!t&&!n)return o="error",m="model not on disk and downloads disabled",!1;o=t?"loading":"downloading",t||(w={model:h,file:null,pct:0},e(`[vad] downloading ${h} (one-time, ~2 MB)…`));try{return c=await V({host:t?null:"https://huggingface.co/",allowRemote:!t},r=>r.AutoModel.from_pretrained(h,{config:{model_type:"custom"},dtype:"fp32",...N({threads:1})})),await O(!t,h,{modelsDir:T(),log:e,dispose:async()=>{await c?.dispose?.(),c=null}}),o="ready",m=null,w=null,e("[vad] ready — Silero VAD on levelled audio decides what is speech (the energy gate is the fallback)"),!0}catch(r){return m=r.message,w=null,o="error",e(`[vad] load failed (${r.message}) — the energy gate decides, as before`),!1}}function oe(e={}){if(g&&o!=="error")return g;o="loading";const n=typeof e.onLog=="function"?e.onLog:()=>{};return p=I({warmMs:e.warmMs,busy:v,log:n,unload:()=>j({log:n})}),g=X({log:n,allowDownload:e.allowDownload!==!1}).then(t=>(t&&!v()&&p?.arm(),t)),g}function $(e){if(!e.length)return 1;const n=[...e].sort((r,E)=>r-E),t=n[Math.floor(n.length*.9)]||0;return t>0?Math.min(B,Math.max(1,P/t)):1}function re(){let e=null,n=0;const t=new Map,r=[],E=Math.ceil(90*L/s);async function k(l){let u=0;for(let i=0;i<l.length;i++)u+=l[i]*l[i];r.push(Math.sqrt(u/l.length)),r.length>G&&r.shift();const d=$(r),a=d===1?l:l.map(i=>i*d);if(_)return _(a);e||=new M.Tensor("float32",new Float32Array(256),[2,1,128]);const f=await c({input:new M.Tensor("float32",a,[1,s]),sr:new M.Tensor("int64",[BigInt(L)],[]),state:e});return e=f.stateN,Number(f.output.data[0])}return{async advance(l,u){if(!A())return!1;const d=u+l.length;n<u&&(n=Math.ceil(u/s)*s),y++;try{for(;n+s<=d;n+=s){const a=n-u;t.set(n/s,await k(l.slice(a,a+s)))}}catch{return!1}finally{y--}for(const a of t.keys()){if(t.size<=E)break;t.delete(a)}return!0},speechIn(l,u,d=b){let a=!1;for(let f=Math.floor(l/s);f*s<u;f++){const i=t.get(f);if(i!==void 0&&(a=!0,i>=d))return!0}return a?!1:null},voicedIn(l,u,d=b){let a=!1,f=0;for(let i=Math.floor(l/s);i*s<u;i++){const D=t.get(i);D!==void 0&&(a=!0,D>=d&&f++)}return a?f*s/L:null},_probs:t}}function le(){p?.disarm(),p=null,x=0,y=0,o="off",c=null,_=null,m=null,g=null,w=null}function ae(e){_=e||null,o=e?"ready":"off"}export{h as DEFAULT_VAD_MODEL,s as FRAME,B as LEVEL_MAX_GAIN,P as LEVEL_TARGET,G as LEVEL_WINDOW,Q as OFFSET,b as ONSET,L as SAMPLE_RATE,J as VAD_MODEL_APPROX_MB,le as _reset,ae as _setForTest,re as createStream,ee as health,oe as init,A as isReady,$ as levelGain,W as modelOnDisk,Z as progress,ne as release,te as retain,Y as state,j as unload};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.154.3";export{o as VERSION};
1
+ const o="0.154.5";export{o as VERSION};