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