@chatpanel/gateway 0.154.1 → 0.154.2
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 +1 -1
- 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.154.
|
|
3
|
+
"version": "0.154.2",
|
|
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": {
|
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 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};
|
|
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};
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.154.
|
|
1
|
+
const o="0.154.2";export{o as VERSION};
|