@chatpanel/gateway 0.137.1 → 0.139.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/src/stt-engine.js CHANGED
@@ -1 +1 @@
1
- import{join as Ve}from"node:path";import{deflateSync as Qe}from"node:zlib";import ve from"node:os";import{existsSync as Je,readdirSync as Ze}from"node:fs";import{randomUUID as et}from"node:crypto";import{ensureLib as Ne,modelRoot as Pe}from"./ner-engine.js";import{runtimeDtype as se,runtimeName as Oe,DTYPE_SUFFIX as tt}from"./model-runtime.js";import{verifyModelWeights as nt}from"./model-integrity.js";import{DEFAULT_STT_MODEL as Re,isEnglishOnly as me,sttModelDtype as he,isKnownSttModel as ot,sttModelEngine as G}from"./stt-models.js";import*as I from"./parakeet-engine.js";import*as _e from"./coreml-stt-engine.js";import*as te from"./indic-engine.js";import*as j from"./diarize-engine.js";import*as Y from"./segment-engine.js";import{turnsFromSpans as rt,mainLocal as lt,timeByLocal as at,audioOfLocal as st}from"@chatpanel/events/speaker-turns.js";import{diarizeApproxMB as it}from"./diarize-models.js";import*as ne from"./translate-engine.js";import*as Z from"./indictrans-engine.js";import{rawOrtAvailable as ct}from"./ort.js";import*as $ from"./vad-engine.js";import*as ee from"./echo-pair.js";import{mostlyEcho as ut}from"./aec-engine.js";import{pickSegmentLanguage as ft,detectTextLanguage as dt,needsTranslation as gt,localTranslatable as pt,normalizeLanguages as mt,normalizeLanguage as ht,decodeLanguages as _t,lineLanguage as wt,autoCandidates as yt,AUTO_LEARN_CONFIDENCE as Mt,AUTO_LEARN_SECONDS as Et,ANY_LANGUAGE_CONFIDENCE as St,AUTO_LANGUAGES as Tt}from"@chatpanel/events/speech-language.js";import*as Lt from"@chatpanel/events/speech-language.js";import{makeWarmTimer as we}from"./warm-timer.js";const p=16e3,Fe=p,$e=3*p,xt=2,At=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 kt(e,t){if(t>xt*p)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?At.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}const bt=12,ye=3;function Dt(e){const t=String(e||"").split(/\s+/).filter(Boolean);if(t.length<ye)return{text:String(e||"").trim(),removed:0,total:t.length};const n=l=>l.toLowerCase().replace(/[^\p{L}\p{N}']/gu,""),o=[];let r=0;for(let l=0;l<t.length;){let f=0,c=0;for(let i=1;i<=bt&&l+i*ye<=t.length;i++){let s=1;for(;l+(s+1)*i<=t.length&&t.slice(l+s*i,l+(s+1)*i).every((u,d)=>n(u)===n(t[l+d]));)s++;s>=ye&&(s-1)*i>f&&(f=(s-1)*i,c=i)}f?(o.push(...t.slice(l,l+c)),r+=f,l+=c+f):(o.push(t[l]),l++)}return{text:o.join(" "),removed:r,total:t.length}}const vt=.6,Ce=2.4;function He(e){const t=Buffer.from(String(e||""),"utf8");return t.length<40?1:t.length/Qe(t).length}function Nt(e){return String(e||"").replace(/([^\d\s]{1,8}?)\1{4,}/gu,"$1")}function Pt({cores:e=ve.availableParallelism?.()??ve.cpus().length,env:t=process.env}={}){const n=Number(t.CHATPANEL_STT_THREADS);return Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(4,Math.floor(e/2)))}function oe(e){return{intraOpNumThreads:Pt(e),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}const Ot=.12,ze=.8,Rt=.15,Ft=.5,$t=1.2,Ue=(e,t)=>e>=Ft||e>=Rt&&!(t<$t),Ct=.999,Ht=2.5;function ie(e={},t=1/0){return Ue(e.en??0,t)?"en":Object.entries(e).sort((n,o)=>o[1]-n[1])[0]?.[0]||null}function zt(e,t=[]){const n=[];return e.forEach((o,r)=>{const l=t[r]??o.lang,f=n[n.length-1];f&&f.lang===l?f.to=o.to:n.push({from:o.from,to:o.to,lang:l})}),n}function Ut(e,{base:t=null,rate:n=p}={}){const o=e||[],r=i=>{const[s,u]=Object.entries(i.scores||{}).sort((d,b)=>b[1]-d[1])[0]||[];return s&&s!=="en"&&u>=Ct?s:null},l=new Array(o.length).fill(null);for(let i=0;i<o.length;){const s=r(o[i]);let u=i+1;if(s)for(;u<o.length&&r(o[u])===s;)u++;if(s&&(o[u-1].to-o[i].from)/n>=Ht)for(let d=i;d<u;d++)l[d]=s;i=u}const f=[];let c=t;return o.forEach((i,s)=>{l[s]?c=l[s]:c!=="en"&&Ue(i.scores?.en??0,(i.to-i.from)/n)&&(c="en");const u=f[f.length-1];u&&u.lang===c?u.to=i.to:f.push({from:i.from,to:i.to,lang:c})}),f}async function Gt(e,t,n){const{spelledEnglish:o,isSpelledEnglish:r,SPELLED_ENGLISH_MIN:l,SPELLED_SHAPE_MIN:f}=Lt;if(typeof o!="function")return e;const c=[];let i=!1;for(const s of e){const u=o(s.text);if(!s.lang||s.lang==="en"||u.english<l&&!r(s.text)){c.push(s);continue}const d=u.words>=f&&u.shaped===u.words,b=[];for(let a=0;a+1<t.length;a++)t[a]>=s.from&&t[a+1]<=s.to&&b.push([t[a],t[a+1]]);if(b.length<2||d){const a=r(s.text)?await n(s.from,s.to,"en"):"";a?(c.push({...s,text:a,lang:"en"}),i=!0):c.push(s);continue}const h=[];for(const[a,S]of b){const A=await n(a,S,s.lang),z=o(A),ge=z.words>0&&z.words-z.shaped<=(z.english>=1&&z.words>=3?1:0);h.push({from:a,to:S,text:A,near:ge,lang:r(A)?"en":s.lang})}for(let a=!0;a;)a=!1,h.forEach((S,A)=>{S.lang!=="en"&&S.near&&(h[A-1]?.lang==="en"||h[A+1]?.lang==="en")&&(S.lang="en",a=!0)});if(!h.some(a=>a.lang==="en")){c.push(s);continue}const M=[];for(const a of h){const S=M[M.length-1];S&&S.lang===a.lang?(S.to=a.to,S.n++):M.push({from:a.from,to:a.to,lang:a.lang,n:1,text:a.text})}for(const a of M){const S=a.n===1&&a.lang===s.lang?a.text:await n(a.from,a.to,a.lang);S&&c.push({from:a.from,to:a.to,lang:a.lang,text:S})}i=!0}return i?c.reduce((s,u)=>{const d=s[s.length-1];return d&&d.lang===u.lang&&d.to===u.from?s[s.length-1]={...d,to:u.to,text:`${d.text} ${u.text}`}:s.push(u),s},[]):e}function jt(e,t,{frame:n=Math.round(.03*p),minPause:o=Ot*p,minPiece:r=ze*p}={}){const l=[];let f=0,c=-1;for(let i=0;i+n<=e;i+=n){const s=t(i,i+n)===!1;if(s&&c<0&&(c=i),(!s||i+2*n>e)&&c>=0){const u=s?i+n:i,d=Math.round((c+u)/2);u-c>=o&&d-f>=r&&e-d>=r&&(l.push(d),f=d),c=-1}}return l}const Bt=.12;function It(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]=J(e,r*t,(r+1)*t);return o.sort(),Math.max(1e-4,o[Math.floor(n*.9)]*Bt)}let _="off",x=null,m=null,v=null,q=null,L=null,K=null,P=null;function Kt(e=x||Re,t=he(e)||se()){if(G(e)==="parakeet-tdt")return I.parakeetOnDisk(e,I.parakeetDtype(t));if(G(e)==="coreml-tdt")return _e.coremlOnDisk(e);if(G(e)==="indic-canary")return te.indicOnDisk();const n=Ve(Pe(),...e.split("/"),"onnx");if(!Je(n))return!1;const o=tt[t]??"";try{const r=Ze(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 _}function ce(){return _==="ready"&&!!m}function vn(){return L}function Nn(){return{configured:_!=="off",ok:ce(),state:_,model:x,dtype:K,runtime:Oe(),error:v,warmMs:P?.warmMs??null,vad:$.state()}}function Pn(){return!!P?.pending()}function re(){return H.size>0||_==="loading"||_==="downloading"}async function Me({log:e=()=>{}}={}){if(re())return!1;P?.disarm();const t=m;if(m=null,q=null,K=null,L=null,v=null,_="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 Ge(e){return e.then(t=>(t&&!re()&&P?.arm(),t))}async function je(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null,licenseAccepted:r=null}={}){if(G(e)==="parakeet-tdt")return Wt(e,{log:t,allowDownload:n,dtype:o});if(G(e)==="coreml-tdt")return Yt(e,{log:t,allowDownload:n});if(G(e)==="indic-canary")return qt(e,{log:t,allowDownload:n,licenseAccepted:r});const l=m,f=x;let c;try{c=await Ne()}catch(h){return _="error",v=`engine load failed: ${h.message}`,t(`[stt] transformers.js not available (${h.message}) — dictation falls back to the browser engine`),!1}const s=(o&&o!=="auto"?o:null)||he(e)||se(),u=Kt(e,s);if(c.env.allowRemoteModels=u?!1:!!n,!u&&!n)return _="error",v="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const d=c.env.remoteHost,b=!ot(e);if(!u&&b)try{c.env.remoteHost="https://huggingface.co/"}catch{}_=u?"loading":"downloading",u||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${b?", from Hugging Face":""})…`));try{const h=a=>{if(!a)return;const S=typeof a.progress=="number"?Math.round(a.progress):L?.pct??0;a.status==="progress"||a.status==="download"||a.status==="initiate"?L={model:e,file:a.file||L?.file||null,pct:S}:a.status==="done"&&a.file&&t(`[stt] fetched ${a.file}`)};let M;try{M=await c.pipeline("automatic-speech-recognition",e,{dtype:s,progress_callback:h,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:oe()}})}catch(a){if(u||b||!n)throw a;t(`[stt] mirror fetch failed (${String(a.message).slice(0,80)}) — retrying from Hugging Face…`),c.env.remoteHost="https://huggingface.co/",c.env.allowRemoteModels=!0,M=await c.pipeline("automatic-speech-recognition",e,{dtype:s,progress_callback:h,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:oe()}})}if(!u)try{nt(e,{modelsDir:Pe(),log:t})}catch(a){try{await M.dispose?.()}catch{}throw a}if(m=M,x=e,_="ready",v=null,L=null,K=s,l&&l!==M)try{await l.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${s} (in-process, offline) — local dictation active`),!0}catch(h){return v=h.message,L=null,l?(m=l,x=f,_="ready"):_="error",t(`[stt] model load failed (${h.message})${l?" — keeping previous model":""}`),!1}finally{try{c.env.remoteHost=d}catch{}}}async function Wt(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null}={}){const r=m,l=x,f=I.parakeetDtype(o&&o!=="auto"?o:Xt()),c=I.parakeetOnDisk(e,f);if(!c&&!n)return _="error",v="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;_=c?"loading":"downloading",c||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const i=await I.loadRecognizer({modelId:e,dtype:f,allowDownload:n,log:t,sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:oe(),onProgress:u=>{L={model:e,file:u.file||null,pct:typeof u.pct=="number"?u.pct:L?.pct??0}}}),s=async u=>({text:await i.transcribe(u)});if(s.__transducer=!0,s.dispose=()=>i.dispose(),m=s,x=e,_="ready",v=null,L=null,K=f,r&&r!==s)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${f} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(i){return v=i.message,L=null,r?(m=r,x=l,_="ready"):_="error",t(`[stt] model load failed (${i.message})${r?" — keeping previous model":""}`),!1}}function Xt(){return I.PARAKEET_DEFAULT_DTYPE}const Be="fp16";async function Yt(e,{log:t=()=>{},allowDownload:n=!0}={}){const o=m,r=x,l=_e.coremlOnDisk(e);if(!l&&!n)return _="error",v="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;_=l?"loading":"downloading",l||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let f=null;const c=await _e.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:i=>{L={model:e,file:i.file||null,pct:typeof i.pct=="number"?i.pct:L?.pct??0}},onExit:i=>{m===f&&(m=null,q=null,_="error",v=i,P?.disarm(),t(`[stt] ${i} — reloads on the next dictation`))}});if(f=async i=>({text:await c.transcribe(i)}),f.__transducer=!0,f.dispose=()=>c.dispose(),m=f,x=e,_="ready",v=null,L=null,K=Be,o&&o!==f)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(f){return v=f.message,L=null,o?(m=o,x=r,_="ready"):_="error",t(`[stt] model load failed (${f.message})${o?" — keeping previous model":""}`),!1}}async function qt(e,{log:t=()=>{},allowDownload:n=!0,licenseAccepted:o=null}={}){const r=m,l=x,f=te.indicOnDisk();if(!f&&!n)return _="error",v="model not on disk and downloads disabled",!1;_=f?"loading":"downloading",f||(L={model:e,file:null,pct:0},t(`[stt] downloading ${e} (one-time, ~1.5 GB, from Hugging Face)…`));try{f||await te.ensureIndicFiles({licenseAccepted:o,log:t,onProgress:s=>{L={model:e,file:s.file,pct:s.pct}}});const c=await te.loadRecognizer({sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:oe(),log:t}),i=async(s,u={})=>c.transcribe(s,u);if(i.identify=(s,u)=>c.identify(s,u),i.__transducer=!0,i.__indic=!0,i.dispose=()=>c.dispose(),m=i,x=e,_="ready",v=null,L=null,K="int8",r&&r!==i)try{await r.dispose?.()}catch{}return t(`[stt] ready — ${e} (Indic-Transcribe, int8, in-process, offline) — ${te.INDIC_LICENSE.attribution}`),!0}catch(c){return v=c.message,L=null,r?(m=r,x=l,_="ready"):_="error",t(`[stt] model load failed (${c.message})${r?" — keeping previous model":""}`),!1}}const Vt=30;function Ie({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:o=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof o=="number"&&o<=Vt||e==="download"?{allowDownload:!0}:null}function Ee(e,{log:t=()=>{},warmMs:n,allowDownload:o=!0}={}){const r=Ie({mode:e,onDisk:j.modelOnDisk(),ready:j.isReady(),approxMB:it(j.activeModel())});if(r&&j.init({allowDownload:r.allowDownload&&o!==!1,warmMs:n,onLog:t}),e==="off"||Se)return;const l=Ie({mode:e,onDisk:Y.modelOnDisk(),ready:Y.isReady(),approxMB:Y.SEGMENT_MODEL_APPROX_MB});l&&Y.init({allowDownload:l.allowDownload&&o!==!1,warmMs:n,onLog:t})}let Se=!1,Te=null;function Le(e={},{log:t=()=>{}}={}){e.vad!==!1&&(Te={vad:e.vad,allowDownload:e.allowDownload,warmMs:e.warmMs},($.state()==="off"||$.state()==="error")&&$.init({allowDownload:e.allowDownload!==!1,warmMs:e.warmMs,onLog:t}))}function On(e={}){if(q&&_!=="error")return q;const t=typeof e.onLog=="function"?e.onLog:()=>{};return x=e.model||Re,Se=e.segment===!1,_="loading",P=we({warmMs:e.warmMs,busy:re,log:t,unload:()=>Me({log:t})}),q=Ge(je(x,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype,licenseAccepted:e.licenseAccepted||null})).then(n=>(n&&(Ee(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),Le(e,{log:t})),n)),q}async function Rn(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(Se=t.segment===!1);const o=G(e)==="parakeet-tdt"?I.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:I.PARAKEET_DEFAULT_DTYPE):G(e)==="coreml-tdt"?Be:G(e)==="indic-canary"?"int8":t.dtype&&t.dtype!=="auto"?t.dtype:he(e)||se();if(e===x&&ce()&&K===o)return Ee(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;P??=we({warmMs:t.warmMs,busy:re,log:n,unload:()=>Me({log:n})});const r=await Ge(je(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype,licenseAccepted:t.licenseAccepted||null}));return r&&(Ee(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),Le(t,{log:n})),r}const Qt=8,Jt=12e4,Zt=6e4,en=1200,ue=12,xe=700,Ae=.008,tn=.002,nn=4;function on(e){return e>0?Math.min(Ae,Math.max(tn,e*nn)):Ae}function rn(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]=J(e,r*t,(r+1)*t);return o.sort(),o[Math.floor(n*.1)]}const Ke=30,ln=15e3,H=new Map,V=new Map;let Q=Promise.resolve();function Fn(){return H.size}const an=300,sn=3e3;function cn(e){const t=Number(e);return Number.isFinite(t)?Math.min(sn,Math.max(an,Math.round(t))):xe}function $n({lang:e,langs:t=null,translateTo:n=null,translateLoad:o=null,echo:r=null,redact:l=!1,diarize:f=!1,speakerLabel:c=null,endSilenceMs:i=xe,interims:s=!0,remote:u=null,poll:d=!1,format:b="f32"}={}){if(H.size>=Qt){const S=new Error("too many concurrent dictation sessions");throw S.code="too_many_sessions",S}const h=Array.isArray(t)?mt(t):null,M=typeof e=="string"&&e?e.slice(0,12):null,a={id:et(),format:b==="pcm16"?"pcm16":"f32",endSilenceMs:cn(i),lang:h?h.length===1?h[0]:h.length?null:M:M,langs:h,lastLang:null,lastDecoded:null,learned:new Set,translateTo:ht(n)||null,translateLoad:o||{},translations:Promise.resolve(),echo:r&&typeof r=="object"?ee.join(r.group,r.role):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!l,diarize:!!f,speakerLabel:typeof c=="string"&&c?c.slice(0,40):null,diarizer:f?new j.Diarizer:null,remote:u||null,interims:s!==!1&&!u,chunks:[],samples:0,listeners:new Set,poll:d?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return H.set(a.id,a),P?.disarm(),a.diarizer&&(j.retain(),Y.retain()),a.translateTo&&(ne.retain(),Z.retain()),$.retain(),Te&&($.state()==="off"||$.state()==="error")&&Le(Te),We(a),{id:a.id}}function fe(e){return H.get(String(e||""))||null}function Cn(e,t){const n=fe(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function W(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function Hn(e){const t=String(e||""),n=H.get(t);if(n)return n.poll?n.poll.splice(0):null;const o=V.get(t);return o?(clearTimeout(o.timer),V.delete(t),o.session.poll.splice(0)):null}function zn(e){return V.get(String(e||""))?.session||null}function We(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>gn(e.id).catch(()=>{}),Zt),e.idleTimer.unref?.()}function Un(e,t){const n=fe(e);if(!n||n.closed){const o=new Error("no such session");throw o.code="no_session",o}if(!(!(t instanceof Float32Array)||!t.length)){if(We(n),n.echo?.role==="mic"){ee.pushMic(n.echo,t),Xe(n);return}n.echo?.role==="reference"&&ee.pushReference(n.echo,t),n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,Xe(n)}}function Gn(e){const t=fe(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),Q=Q.then(()=>ke(t).catch(()=>{})),Q)}function jn(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 Xe(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+en-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,Q=Q.then(()=>ke(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function de(e,t,n){const o=e.samples-t,r=[];n&&r.push(n),o>0&&r.push(Ye(e).subarray(t)),e.chunks=r,e.samples=r.reduce((l,f)=>l+f.length,0),e.lastInterim=""}function Ye(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 un(e,t,n){const o=p/100,r=Math.max(0,e.length-t),l=Math.floor((e.length-r)/o),f=Math.max(1,Math.round(n/o));if(l<=f)return 0;const c=new Float32Array(l);for(let d=0;d<l;d++){let b=0;const h=r+d*o;for(let M=0;M<o;M++)b+=e[h+M]*e[h+M];c[d]=b/o}let i=-1,s=1/0,u=0;for(let d=0;d<f;d++)u+=c[d];for(let d=0;d+f<=l;d++)d>0&&(u+=c[d+f-1]-c[d-1]),u<s&&(s=u,i=d);return i<0?0:r+Math.round((i+f/2)*o)}function J(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 fn(e,t=Ae){const n=Math.round(.02*p);let o=0,r=e.length;for(let l=0;l+n<=e.length;l+=n)if(J(e,l,l+n)>=t){o=l;break}for(let l=e.length-n;l>=0;l-=n)if(J(e,l,l+n)>=t){r=l+n;break}return r>o?e.subarray(o,r):e}async function qe(e){try{const t=await Ne(),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]),f=await m.model({...r,decoder_input_ids:l}),c={};for(const[i,s]of Object.entries(n.lang_to_id))c[i.slice(2,-2)]=Number(f.logits.data[s]);return c}catch{return null}}async function dn(e){const t=await qe(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 ke(e,{flush:t=!1}={}){if(e.closed&&!t)return;if(e.echo?.role==="mic"){const g=await ee.drain(e.echo,{force:t});g.length&&(e.chunks.push(g),e.samples+=g.length,e.pushed+=g.length)}if(!e.remote&&!ce()||!e.samples)return;e.lastDecodeAt=Date.now();let n=Ye(e);const o=n.length,r=Math.max(0,(e.pushed||0)-e.samples),l=Math.round((e.endSilenceMs||xe)/1e3*p),f=rn(n);f!==null&&(e.noiseFloor==null||f<e.noiseFloor)&&(e.noiseFloor=f);const c=on(e.noiseFloor);let i=null,s=null;$.isReady()&&(e.vad||=$.createStream(),await e.vad.advance(n,r)&&(i=e.vad.speechIn(r,r+n.length,$.ONSET),n.length>l&&(s=e.vad.speechIn(r+n.length-l,r+n.length,$.OFFSET))));const u=n.length>l&&(s!==null?!s:J(n,n.length-l)<c);if(i===!1||i===null&&J(n)<c){n.length>p*5&&(e.chunks=[n.subarray(n.length-p)],e.samples=p);return}if(!e.interims&&!t&&!u&&n.length<ue*p)return;let d=null;if(!t&&!u&&o>=ue*p&&o<Ke*p){const g=un(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&&!me(x)&&!m?.__transducer;if(b&&!e.langs&&!e.lang&&!e.langTried&&n.length>=p){e.langTried=!0;const g=await dn(n);g&&(e.lang=g,W(e,{type:"language",lang:g}))}const h=t||u||o>=ue*p;let M=e.lang;if(b&&e.langs&&!e.lang){const g=e.langs.length>0,O=g?_t(e.langs):yt([...e.learned]);if(O.length===1)M=O[0];else if(M=O.includes(e.lastDecoded)?e.lastDecoded:null,(h||!M)&&n.length>=p/2){const R=await qe(n);if(R){const T=ft({scores:R,allowed:O,seconds:n.length/p,last:e.lastDecoded});M=!g&&!T.inherited&&T.confidence<St?e.lastDecoded||"en":T.lang,!g&&h&&!T.inherited&&T.confidence>=Mt&&n.length>=Et*p&&e.learned.add(T.lang)}}h&&M&&(e.lastDecoded=M)}let a="",S=null,A=null,z=null;try{if(e.remote){const g=await e.remote.transcribe(n,{lang:e.lang,langs:e.langs});a=g.text,z=g.lang||null}else{const g=m.__indic?e.langs?.length?{langs:[...new Set([...e.langs,"en"])],last:e.lastLang,choose:ie}:e.lang?{lang:e.lang}:{langs:[...Tt],last:e.lastLang,choose:ie}:me(x)?{}:{language:M||void 0,task:"transcribe"},O=m.__indic&&m.identify&&h&&g.langs&&n.length>=2*ze*p?jt(n.length,(E=>(y,k)=>J(n,y,k)>=E)(It(n))):[],R=[0,...O,n.length];let T=null;if(O.length){const E=await m.identify(n,{langs:g.langs}),y=[];for(let k=0;k+1<R.length;k++){const N=await m.identify(n.subarray(R[k],R[k+1]),{langs:g.langs});y.push({from:R[k],to:R[k+1],scores:N?.scores||{}})}if(T=Ut(y,{base:E?.scores?ie(E.scores,n.length/p):null}),T.length>1){const k=[];for(let N=0;N<T.length;N++){const w=T[N],D=w.lang&&w.lang!=="en"&&(T[N-1]?.lang==="en"||T[N+1]?.lang==="en");k.push(D?ie((await m.identify(n.subarray(w.from,w.to),{langs:g.langs}))?.scores||{},(w.to-w.from)/p):w.lang)}T=zt(T,k)}T.length<2&&(T=null)}if(T){A=[];for(const E of T){const y=await m(n.subarray(E.from,E.to),E.lang?{lang:E.lang}:{...g}),k=String(y?.text||"").trim(),N=y?.lang||E.lang||null;k&&A.push({text:k,lang:N,from:E.from,to:E.to}),N&&(g.last=N)}}else{const E=await m(n,g);a=String(E?.text||"").trim(),m.__indic&&(S=E?.lang||null),m.__indic&&a&&(A=[{text:a,lang:S,from:0,to:n.length}])}if(A&&h&&g.langs&&(A=await Gt(A,R,async(E,y,k)=>String((await m(n.subarray(E,y),{lang:k}))?.text||"").trim())),A){a=A.map(y=>y.text).join(" ");const E=new Map;for(const y of A)y.lang&&E.set(y.lang,(E.get(y.lang)||0)+(y.to-y.from));S=[...E].sort((y,k)=>k[1]-y[1])[0]?.[0]||null,(A.length<2||E.size<2)&&(A=null)}}}catch(g){W(e,{type:"error",code:"decode_failed",message:g.message,fatal:!1}),h&&de(e,o,d);return}if(!a){h&&de(e,o,d);return}{const g=Dt(a);if(g.removed&&g.removed/g.total>=vt&&g.total>=12?a="":a=g.text,a&&He(a)>Ce){const O=Nt(a);a=O.replace(/[\s\p{P}]/gu,"").length<12||He(O)>Ce?"":O}if(!a){h&&de(e,o,d);return}}const ge=o>=ue*p,be=o>=Ke*p;if(t||u||ge||be){const g=t?"flush":u?"silence":be?"overflow":"length",O=g==="flush"||g==="silence";de(e,o,d);const R=fn(n,c);if(kt(a,R?R.length:0)||e.echo?.role==="mic"&&ut(ee.verdict(e.echo,r,r+n.length)))return;let T=null,E=null;if(e.diarizer)try{const w=e.speakerLabel?null:await Y.spans(n),D=w?rt(w):[];if(D.length){const F=new Map;for(const{local:C}of at(D)){const U=st(n,D,C),le=U.length?await j.embed(U):null,ae=U.length<Fe,X=U.length<$e;F.set(C,e.diarizer.assign(le,{pinnedLabel:null,weak:ae,thin:X}))}const B=Math.round(r/p*1e3);E=D.map(C=>({startMs:B+Math.round(C.start*1e3),durationMs:Math.round((C.end-C.start)*1e3),speaker:F.get(C.local)})).filter(C=>C.speaker),T=F.get(lt(D))||null}}catch{}if(e.diarizer&&!T)try{const w=R,D=w?await j.embed(w):null,F=!!w&&w.length<Fe,B=!!w&&w.length<$e;T=e.diarizer.assign(D,{pinnedLabel:e.speakerLabel,weak:F,thin:B})}catch{}let y=null;(e.langs||e.translateTo)&&(S?y=S:z?y=z:me(x)&&!e.remote?y="en":b?y=wt(a,M||e.lang)||null:y=e.lang||dt(a,{allowed:e.langs||[],last:e.lastLang}).lang,y&&y!==e.lastLang&&(e.lastLang=y,W(e,{type:"language",lang:y})));const k=Math.round(r/p*1e3),N=A&&(e.langs||e.translateTo)?A.map((w,D)=>({text:w.text,lang:w.lang,startMs:k+Math.round(w.from/p*1e3),durationMs:Math.round((w.to-w.from)/p*1e3),last:D===A.length-1})):[{text:a,lang:y,startMs:k,durationMs:Math.round(n.length/p*1e3),last:!0}];for(const w of N){N.length>1&&w.lang&&w.lang!==e.lastLang&&(e.lastLang=w.lang,W(e,{type:"language",lang:w.lang}));const{text:D,lang:F,startMs:B}=w,C=(D.match(new RegExp("\\p{Script=Latin}","gu"))||[]).length/Math.max(1,(D.match(new RegExp("\\p{L}","gu"))||[]).length),U=Z.indictransLanguage(F)&&C<.5&&Z.state()!=="error"&&ct(),le=!!e.translateTo&&gt(F,e.translateTo)&&(U||pt(D,F)&&ne.state()!=="error"),ae=N.length>1&&E?E.filter(X=>X.startMs<B+w.durationMs&&X.startMs+X.durationMs>B):E;if(W(e,{type:"final",text:D,reason:g,endOfTurn:w.last?O:!1,durationMs:w.durationMs,startMs:B,...F?{lang:F}:{},...le?{translating:!0}:{},...T?{speaker:T}:{},...ae?.length?{turns:ae}:{}}),le){const X=e.translateTo,pe=U?Z:ne;pe.state()==="off"&&pe.init({...e.translateLoad,...U?{sessionOptions:oe()}:{}}),e.translations=e.translations.then(async()=>{await pe.ready();const De=U?await Z.translate(D,F):await ne.translate(D);W(e,{type:"translation",startMs:B,lang:F,to:X,text:De||null,...De?{}:{failed:!0}})}).catch(()=>{})}}}else a!==e.lastInterim&&(e.lastInterim=a,W(e,{type:"interim",text:a}))}async function gn(e){const t=fe(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(Q=Q.then(()=>ke(t,{flush:!0}).catch(()=>{}))),await Promise.race([t.translations,new Promise(n=>setTimeout(n,ln).unref?.())])}finally{if(W(t,{type:"end"}),t.listeners.clear(),H.delete(t.id),t.poll){const n=setTimeout(()=>V.delete(t.id),Jt);n.unref?.(),V.set(t.id,{session:t,timer:n})}t.diarizer&&(j.release(),Y.release()),t.translateTo&&(ne.release(),Z.release()),$.release(),ee.leave(t.echo),H.size===0&&ce()&&P?.arm()}return!0}function Bn(){for(const e of H.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);H.clear();for(const e of V.values())clearTimeout(e.timer);V.clear(),P?.disarm(),P=null,_="off",x=null,m=null,v=null,q=null,L=null}function In(e,t="test/fake",{warmMs:n=null,dtype:o=null}={}){m=e,x=t,_=e?"ready":"off",K=o,n!==null&&(P=we({warmMs:n,busy:re,unload:()=>Me()}),e&&P.arm())}export{Vt as AUTO_FETCH_MAX_MB,Ce as COMPRESSION_LIMIT,Ct as FROM_ENGLISH,Ht as FROM_ENGLISH_RUN_S,vt as LOOP_DROP,Bt as PAUSE_SHARE,ze as PIECE_MIN_S,Ot as PIECE_PAUSE_S,p as SAMPLE_RATE,Ft as SURE_ENGLISH,$e as THIN_SPEAKER_SAMPLES,Rt as TO_ENGLISH,$t as WEAK_ENGLISH_MIN_S,Fe as WEAK_SPEAKER_SAMPLES,Bn as _reset,In as _setPipeForTest,cn as clampEndSilence,Dt as collapseLoops,Nt as collapseRuns,He as compressionRatio,$n as createSession,Gn as decodeNow,Hn as drainEvents,gn as endSession,zn as endedSession,fe as getSession,Nn as health,On as init,ce as isReady,Ut as languageGroups,kt as looksHallucinated,Kt as modelOnDisk,rn as noiseFloorOf,jt as pauseCuts,It as pauseLevel,vn as progress,Un as pushAudio,un as quietestCut,zt as relabelGroups,Gt as respellEnglish,se as runtimeDtype,Oe as runtimeName,ie as segmentLanguage,Fn as sessionCount,Rn as setModel,on as silenceGate,Ie as speakerPlan,Dn as state,oe as sttSessionOptions,Pt as sttThreads,Cn as subscribe,jn as toFloat32,Me as unload,Pn as warmPending};
1
+ import{join as Qe}from"node:path";import{deflateSync as Je}from"node:zlib";import Ne from"node:os";import{existsSync as Ze,readdirSync as et}from"node:fs";import{randomUUID as tt}from"node:crypto";import{ensureLib as Pe,modelRoot as Oe}from"./ner-engine.js";import{runtimeDtype as se,runtimeName as Re,DTYPE_SUFFIX as nt}from"./model-runtime.js";import{verifyModelWeights as ot}from"./model-integrity.js";import{DEFAULT_STT_MODEL as Fe,isEnglishOnly as me,sttModelDtype as he,isKnownSttModel as rt,sttModelEngine as G}from"./stt-models.js";import*as I from"./parakeet-engine.js";import*as _e from"./coreml-stt-engine.js";import*as te from"./indic-engine.js";import*as j from"./diarize-engine.js";import*as Y from"./segment-engine.js";import{turnsFromSpans as lt,mainLocal as at,timeByLocal as st,audioOfLocal as it}from"@chatpanel/events/speaker-turns.js";import{diarizeApproxMB as ct}from"./diarize-models.js";import*as ne from"./translate-engine.js";import*as Z from"./indictrans-engine.js";import{rawOrtAvailable as ut}from"./ort.js";import*as $ from"./vad-engine.js";import*as ee from"./echo-pair.js";import*as we from"./aec-engine.js";import{pickSegmentLanguage as ft,detectTextLanguage as dt,needsTranslation as gt,localTranslatable as pt,normalizeLanguages as mt,normalizeLanguage as ht,decodeLanguages as _t,lineLanguage as wt,autoCandidates as yt,AUTO_LEARN_CONFIDENCE as Mt,AUTO_LEARN_SECONDS as Et,ANY_LANGUAGE_CONFIDENCE as St,AUTO_LANGUAGES as Tt}from"@chatpanel/events/speech-language.js";import*as Lt from"@chatpanel/events/speech-language.js";import{makeWarmTimer as ye}from"./warm-timer.js";const p=16e3,$e=p,Ce=3*p,xt=2,At=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 kt(e,t){if(t>xt*p)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?At.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}const bt=12,Me=3;function Dt(e){const t=String(e||"").split(/\s+/).filter(Boolean);if(t.length<Me)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 f=0,c=0;for(let i=1;i<=bt&&l+i*Me<=t.length;i++){let s=1;for(;l+(s+1)*i<=t.length&&t.slice(l+s*i,l+(s+1)*i).every((u,d)=>n(u)===n(t[l+d]));)s++;s>=Me&&(s-1)*i>f&&(f=(s-1)*i,c=i)}f?(o.push(...t.slice(l,l+c)),r+=f,l+=c+f):(o.push(t[l]),l++)}return{text:o.join(" "),removed:r,total:t.length}}const vt=.6,He=2.4;function ze(e){const t=Buffer.from(String(e||""),"utf8");return t.length<40?1:t.length/Je(t).length}function Nt(e){return String(e||"").replace(/([^\d\s]{1,8}?)\1{4,}/gu,"$1")}function Pt({cores:e=Ne.availableParallelism?.()??Ne.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 oe(e){return{intraOpNumThreads:Pt(e),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}const Ot=.12,Ue=.8,Rt=.15,Ft=.5,$t=1.2,Ge=(e,t)=>e>=Ft||e>=Rt&&!(t<$t),Ct=.999,Ht=2.5;function ie(e={},t=1/0){return Ge(e.en??0,t)?"en":Object.entries(e).sort((n,o)=>o[1]-n[1])[0]?.[0]||null}function zt(e,t=[]){const n=[];return e.forEach((o,r)=>{const l=t[r]??o.lang,f=n[n.length-1];f&&f.lang===l?f.to=o.to:n.push({from:o.from,to:o.to,lang:l})}),n}function Ut(e,{base:t=null,rate:n=p}={}){const o=e||[],r=i=>{const[s,u]=Object.entries(i.scores||{}).sort((d,b)=>b[1]-d[1])[0]||[];return s&&s!=="en"&&u>=Ct?s:null},l=new Array(o.length).fill(null);for(let i=0;i<o.length;){const s=r(o[i]);let u=i+1;if(s)for(;u<o.length&&r(o[u])===s;)u++;if(s&&(o[u-1].to-o[i].from)/n>=Ht)for(let d=i;d<u;d++)l[d]=s;i=u}const f=[];let c=t;return o.forEach((i,s)=>{l[s]?c=l[s]:c!=="en"&&Ge(i.scores?.en??0,(i.to-i.from)/n)&&(c="en");const u=f[f.length-1];u&&u.lang===c?u.to=i.to:f.push({from:i.from,to:i.to,lang:c})}),f}async function Gt(e,t,n){const{spelledEnglish:o,isSpelledEnglish:r,SPELLED_ENGLISH_MIN:l,SPELLED_SHAPE_MIN:f}=Lt;if(typeof o!="function")return e;const c=[];let i=!1;for(const s of e){const u=o(s.text);if(!s.lang||s.lang==="en"||u.english<l&&!r(s.text)){c.push(s);continue}const d=u.words>=f&&u.shaped===u.words,b=[];for(let a=0;a+1<t.length;a++)t[a]>=s.from&&t[a+1]<=s.to&&b.push([t[a],t[a+1]]);if(b.length<2||d){const a=r(s.text)?await n(s.from,s.to,"en"):"";a?(c.push({...s,text:a,lang:"en"}),i=!0):c.push(s);continue}const h=[];for(const[a,S]of b){const A=await n(a,S,s.lang),z=o(A),ge=z.words>0&&z.words-z.shaped<=(z.english>=1&&z.words>=3?1:0);h.push({from:a,to:S,text:A,near:ge,lang:r(A)?"en":s.lang})}for(let a=!0;a;)a=!1,h.forEach((S,A)=>{S.lang!=="en"&&S.near&&(h[A-1]?.lang==="en"||h[A+1]?.lang==="en")&&(S.lang="en",a=!0)});if(!h.some(a=>a.lang==="en")){c.push(s);continue}const M=[];for(const a of h){const S=M[M.length-1];S&&S.lang===a.lang?(S.to=a.to,S.n++):M.push({from:a.from,to:a.to,lang:a.lang,n:1,text:a.text})}for(const a of M){const S=a.n===1&&a.lang===s.lang?a.text:await n(a.from,a.to,a.lang);S&&c.push({from:a.from,to:a.to,lang:a.lang,text:S})}i=!0}return i?c.reduce((s,u)=>{const d=s[s.length-1];return d&&d.lang===u.lang&&d.to===u.from?s[s.length-1]={...d,to:u.to,text:`${d.text} ${u.text}`}:s.push(u),s},[]):e}function jt(e,t,{frame:n=Math.round(.03*p),minPause:o=Ot*p,minPiece:r=Ue*p}={}){const l=[];let f=0,c=-1;for(let i=0;i+n<=e;i+=n){const s=t(i,i+n)===!1;if(s&&c<0&&(c=i),(!s||i+2*n>e)&&c>=0){const u=s?i+n:i,d=Math.round((c+u)/2);u-c>=o&&d-f>=r&&e-d>=r&&(l.push(d),f=d),c=-1}}return l}const Bt=.12;function It(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]=J(e,r*t,(r+1)*t);return o.sort(),Math.max(1e-4,o[Math.floor(n*.9)]*Bt)}let _="off",x=null,m=null,v=null,q=null,L=null,K=null,P=null;function Kt(e=x||Fe,t=he(e)||se()){if(G(e)==="parakeet-tdt")return I.parakeetOnDisk(e,I.parakeetDtype(t));if(G(e)==="coreml-tdt")return _e.coremlOnDisk(e);if(G(e)==="indic-canary")return te.indicOnDisk();const n=Qe(Oe(),...e.split("/"),"onnx");if(!Ze(n))return!1;const o=nt[t]??"";try{const r=et(n);return r.includes(`encoder_model${o}.onnx`)&&r.some(l=>l===`decoder_model_merged${o}.onnx`||l===`decoder_model${o}.onnx`)}catch{return!1}}function bn(){return _}function ce(){return _==="ready"&&!!m}function Dn(){return L}function vn(){return{configured:_!=="off",ok:ce(),state:_,model:x,dtype:K,runtime:Re(),error:v,warmMs:P?.warmMs??null,vad:$.state()}}function Nn(){return!!P?.pending()}function re(){return H.size>0||_==="loading"||_==="downloading"}async function Ee({log:e=()=>{}}={}){if(re())return!1;P?.disarm();const t=m;if(m=null,q=null,K=null,L=null,v=null,_="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 je(e){return e.then(t=>(t&&!re()&&P?.arm(),t))}async function Be(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null,licenseAccepted:r=null}={}){if(G(e)==="parakeet-tdt")return Wt(e,{log:t,allowDownload:n,dtype:o});if(G(e)==="coreml-tdt")return Yt(e,{log:t,allowDownload:n});if(G(e)==="indic-canary")return qt(e,{log:t,allowDownload:n,licenseAccepted:r});const l=m,f=x;let c;try{c=await Pe()}catch(h){return _="error",v=`engine load failed: ${h.message}`,t(`[stt] transformers.js not available (${h.message}) — dictation falls back to the browser engine`),!1}const s=(o&&o!=="auto"?o:null)||he(e)||se(),u=Kt(e,s);if(c.env.allowRemoteModels=u?!1:!!n,!u&&!n)return _="error",v="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const d=c.env.remoteHost,b=!rt(e);if(!u&&b)try{c.env.remoteHost="https://huggingface.co/"}catch{}_=u?"loading":"downloading",u||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${b?", from Hugging Face":""})…`));try{const h=a=>{if(!a)return;const S=typeof a.progress=="number"?Math.round(a.progress):L?.pct??0;a.status==="progress"||a.status==="download"||a.status==="initiate"?L={model:e,file:a.file||L?.file||null,pct:S}:a.status==="done"&&a.file&&t(`[stt] fetched ${a.file}`)};let M;try{M=await c.pipeline("automatic-speech-recognition",e,{dtype:s,progress_callback:h,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:oe()}})}catch(a){if(u||b||!n)throw a;t(`[stt] mirror fetch failed (${String(a.message).slice(0,80)}) — retrying from Hugging Face…`),c.env.remoteHost="https://huggingface.co/",c.env.allowRemoteModels=!0,M=await c.pipeline("automatic-speech-recognition",e,{dtype:s,progress_callback:h,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:oe()}})}if(!u)try{ot(e,{modelsDir:Oe(),log:t})}catch(a){try{await M.dispose?.()}catch{}throw a}if(m=M,x=e,_="ready",v=null,L=null,K=s,l&&l!==M)try{await l.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${s} (in-process, offline) — local dictation active`),!0}catch(h){return v=h.message,L=null,l?(m=l,x=f,_="ready"):_="error",t(`[stt] model load failed (${h.message})${l?" — keeping previous model":""}`),!1}finally{try{c.env.remoteHost=d}catch{}}}async function Wt(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null}={}){const r=m,l=x,f=I.parakeetDtype(o&&o!=="auto"?o:Xt()),c=I.parakeetOnDisk(e,f);if(!c&&!n)return _="error",v="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;_=c?"loading":"downloading",c||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const i=await I.loadRecognizer({modelId:e,dtype:f,allowDownload:n,log:t,sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:oe(),onProgress:u=>{L={model:e,file:u.file||null,pct:typeof u.pct=="number"?u.pct:L?.pct??0}}}),s=async u=>({text:await i.transcribe(u)});if(s.__transducer=!0,s.dispose=()=>i.dispose(),m=s,x=e,_="ready",v=null,L=null,K=f,r&&r!==s)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${f} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(i){return v=i.message,L=null,r?(m=r,x=l,_="ready"):_="error",t(`[stt] model load failed (${i.message})${r?" — keeping previous model":""}`),!1}}function Xt(){return I.PARAKEET_DEFAULT_DTYPE}const Ie="fp16";async function Yt(e,{log:t=()=>{},allowDownload:n=!0}={}){const o=m,r=x,l=_e.coremlOnDisk(e);if(!l&&!n)return _="error",v="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;_=l?"loading":"downloading",l||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let f=null;const c=await _e.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:i=>{L={model:e,file:i.file||null,pct:typeof i.pct=="number"?i.pct:L?.pct??0}},onExit:i=>{m===f&&(m=null,q=null,_="error",v=i,P?.disarm(),t(`[stt] ${i} — reloads on the next dictation`))}});if(f=async i=>({text:await c.transcribe(i)}),f.__transducer=!0,f.dispose=()=>c.dispose(),m=f,x=e,_="ready",v=null,L=null,K=Ie,o&&o!==f)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(f){return v=f.message,L=null,o?(m=o,x=r,_="ready"):_="error",t(`[stt] model load failed (${f.message})${o?" — keeping previous model":""}`),!1}}async function qt(e,{log:t=()=>{},allowDownload:n=!0,licenseAccepted:o=null}={}){const r=m,l=x,f=te.indicOnDisk();if(!f&&!n)return _="error",v="model not on disk and downloads disabled",!1;_=f?"loading":"downloading",f||(L={model:e,file:null,pct:0},t(`[stt] downloading ${e} (one-time, ~1.5 GB, from Hugging Face)…`));try{f||await te.ensureIndicFiles({licenseAccepted:o,log:t,onProgress:s=>{L={model:e,file:s.file,pct:s.pct}}});const c=await te.loadRecognizer({sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:oe(),log:t}),i=async(s,u={})=>c.transcribe(s,u);if(i.identify=(s,u)=>c.identify(s,u),i.__transducer=!0,i.__indic=!0,i.dispose=()=>c.dispose(),m=i,x=e,_="ready",v=null,L=null,K="int8",r&&r!==i)try{await r.dispose?.()}catch{}return t(`[stt] ready — ${e} (Indic-Transcribe, int8, in-process, offline) — ${te.INDIC_LICENSE.attribution}`),!0}catch(c){return v=c.message,L=null,r?(m=r,x=l,_="ready"):_="error",t(`[stt] model load failed (${c.message})${r?" — keeping previous model":""}`),!1}}const Vt=30;function Ke({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:o=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof o=="number"&&o<=Vt||e==="download"?{allowDownload:!0}:null}function Se(e,{log:t=()=>{},warmMs:n,allowDownload:o=!0}={}){const r=Ke({mode:e,onDisk:j.modelOnDisk(),ready:j.isReady(),approxMB:ct(j.activeModel())});if(r&&j.init({allowDownload:r.allowDownload&&o!==!1,warmMs:n,onLog:t}),e==="off"||Te)return;const l=Ke({mode:e,onDisk:Y.modelOnDisk(),ready:Y.isReady(),approxMB:Y.SEGMENT_MODEL_APPROX_MB});l&&Y.init({allowDownload:l.allowDownload&&o!==!1,warmMs:n,onLog:t})}let Te=!1,Le=null;function xe(e={},{log:t=()=>{}}={}){e.vad!==!1&&(Le={vad:e.vad,allowDownload:e.allowDownload,warmMs:e.warmMs},($.state()==="off"||$.state()==="error")&&$.init({allowDownload:e.allowDownload!==!1,warmMs:e.warmMs,onLog:t}))}function Pn(e={}){if(q&&_!=="error")return q;const t=typeof e.onLog=="function"?e.onLog:()=>{};return x=e.model||Fe,Te=e.segment===!1,_="loading",P=ye({warmMs:e.warmMs,busy:re,log:t,unload:()=>Ee({log:t})}),q=je(Be(x,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype,licenseAccepted:e.licenseAccepted||null})).then(n=>(n&&(Se(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),xe(e,{log:t})),n)),q}async function On(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(Te=t.segment===!1);const o=G(e)==="parakeet-tdt"?I.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:I.PARAKEET_DEFAULT_DTYPE):G(e)==="coreml-tdt"?Ie:G(e)==="indic-canary"?"int8":t.dtype&&t.dtype!=="auto"?t.dtype:he(e)||se();if(e===x&&ce()&&K===o)return Se(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;P??=ye({warmMs:t.warmMs,busy:re,log:n,unload:()=>Ee({log:n})});const r=await je(Be(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype,licenseAccepted:t.licenseAccepted||null}));return r&&(Se(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),xe(t,{log:n})),r}const Qt=8,Jt=12e4,Zt=6e4,en=1200,ue=12,Ae=700,ke=.008,tn=.002,nn=4;function on(e){return e>0?Math.min(ke,Math.max(tn,e*nn)):ke}function rn(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]=J(e,r*t,(r+1)*t);return o.sort(),o[Math.floor(n*.1)]}const We=30,ln=15e3,H=new Map,V=new Map;let Q=Promise.resolve();function Rn(){return H.size}const an=300,sn=3e3;function cn(e){const t=Number(e);return Number.isFinite(t)?Math.min(sn,Math.max(an,Math.round(t))):Ae}function Fn({lang:e,langs:t=null,translateTo:n=null,translateLoad:o=null,echo:r=null,redact:l=!1,diarize:f=!1,speakerLabel:c=null,endSilenceMs:i=Ae,interims:s=!0,remote:u=null,poll:d=!1,format:b="f32"}={}){if(H.size>=Qt){const S=new Error("too many concurrent dictation sessions");throw S.code="too_many_sessions",S}const h=Array.isArray(t)?mt(t):null,M=typeof e=="string"&&e?e.slice(0,12):null,a={id:tt(),format:b==="pcm16"?"pcm16":"f32",endSilenceMs:cn(i),lang:h?h.length===1?h[0]:h.length?null:M:M,langs:h,lastLang:null,lastDecoded:null,learned:new Set,translateTo:ht(n)||null,translateLoad:o||{},translations:Promise.resolve(),echo:r&&typeof r=="object"?ee.join(r.group,r.role):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!l,diarize:!!f,speakerLabel:typeof c=="string"&&c?c.slice(0,40):null,diarizer:f?new j.Diarizer:null,remote:u||null,interims:s!==!1&&!u,chunks:[],samples:0,listeners:new Set,poll:d?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return H.set(a.id,a),P?.disarm(),a.diarizer&&(j.retain(),Y.retain()),a.translateTo&&(ne.retain(),Z.retain()),a.echo&&we.retain(),$.retain(),Le&&($.state()==="off"||$.state()==="error")&&xe(Le),Xe(a),{id:a.id}}function fe(e){return H.get(String(e||""))||null}function $n(e,t){const n=fe(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function W(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function Cn(e){const t=String(e||""),n=H.get(t);if(n)return n.poll?n.poll.splice(0):null;const o=V.get(t);return o?(clearTimeout(o.timer),V.delete(t),o.session.poll.splice(0)):null}function Hn(e){return V.get(String(e||""))?.session||null}function Xe(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>gn(e.id).catch(()=>{}),Zt),e.idleTimer.unref?.()}function zn(e,t){const n=fe(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(Xe(n),n.echo?.role==="mic"){ee.pushMic(n.echo,t),Ye(n);return}n.echo?.role==="reference"&&ee.pushReference(n.echo,t),n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,Ye(n)}}function Un(e){const t=fe(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),Q=Q.then(()=>be(t).catch(()=>{})),Q)}function Gn(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 Ye(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+en-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,Q=Q.then(()=>be(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function de(e,t,n){const o=e.samples-t,r=[];n&&r.push(n),o>0&&r.push(qe(e).subarray(t)),e.chunks=r,e.samples=r.reduce((l,f)=>l+f.length,0),e.lastInterim=""}function qe(e){const t=new Float32Array(e.samples);let n=0;for(const o of e.chunks)t.set(o,n),n+=o.length;return t}function un(e,t,n){const o=p/100,r=Math.max(0,e.length-t),l=Math.floor((e.length-r)/o),f=Math.max(1,Math.round(n/o));if(l<=f)return 0;const c=new Float32Array(l);for(let d=0;d<l;d++){let b=0;const h=r+d*o;for(let M=0;M<o;M++)b+=e[h+M]*e[h+M];c[d]=b/o}let i=-1,s=1/0,u=0;for(let d=0;d<f;d++)u+=c[d];for(let d=0;d+f<=l;d++)d>0&&(u+=c[d+f-1]-c[d-1]),u<s&&(s=u,i=d);return i<0?0:r+Math.round((i+f/2)*o)}function J(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 fn(e,t=ke){const n=Math.round(.02*p);let o=0,r=e.length;for(let l=0;l+n<=e.length;l+=n)if(J(e,l,l+n)>=t){o=l;break}for(let l=e.length-n;l>=0;l-=n)if(J(e,l,l+n)>=t){r=l+n;break}return r>o?e.subarray(o,r):e}async function Ve(e){try{const t=await Pe(),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]),f=await m.model({...r,decoder_input_ids:l}),c={};for(const[i,s]of Object.entries(n.lang_to_id))c[i.slice(2,-2)]=Number(f.logits.data[s]);return c}catch{return null}}async function dn(e){const t=await Ve(e);if(!t)return null;let n=null,o=-1/0;for(const[r,l]of Object.entries(t))l>o&&(o=l,n=r);return n}async function be(e,{flush:t=!1}={}){if(e.closed&&!t)return;if(e.echo?.role==="mic"){const g=await ee.drain(e.echo,{force:t});g.length&&(e.chunks.push(g),e.samples+=g.length,e.pushed+=g.length)}if(!e.remote&&!ce()||!e.samples)return;e.lastDecodeAt=Date.now();let n=qe(e);const o=n.length,r=Math.max(0,(e.pushed||0)-e.samples),l=Math.round((e.endSilenceMs||Ae)/1e3*p),f=rn(n);f!==null&&(e.noiseFloor==null||f<e.noiseFloor)&&(e.noiseFloor=f);const c=on(e.noiseFloor);let i=null,s=null;$.isReady()&&(e.vad||=$.createStream(),await e.vad.advance(n,r)&&(i=e.vad.speechIn(r,r+n.length,$.ONSET),n.length>l&&(s=e.vad.speechIn(r+n.length-l,r+n.length,$.OFFSET))));const u=n.length>l&&(s!==null?!s:J(n,n.length-l)<c);if(i===!1||i===null&&J(n)<c){n.length>p*5&&(e.chunks=[n.subarray(n.length-p)],e.samples=p);return}if(!e.interims&&!t&&!u&&n.length<ue*p)return;let d=null;if(!t&&!u&&o>=ue*p&&o<We*p){const g=un(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&&!me(x)&&!m?.__transducer;if(b&&!e.langs&&!e.lang&&!e.langTried&&n.length>=p){e.langTried=!0;const g=await dn(n);g&&(e.lang=g,W(e,{type:"language",lang:g}))}const h=t||u||o>=ue*p;let M=e.lang;if(b&&e.langs&&!e.lang){const g=e.langs.length>0,O=g?_t(e.langs):yt([...e.learned]);if(O.length===1)M=O[0];else if(M=O.includes(e.lastDecoded)?e.lastDecoded:null,(h||!M)&&n.length>=p/2){const R=await Ve(n);if(R){const T=ft({scores:R,allowed:O,seconds:n.length/p,last:e.lastDecoded});M=!g&&!T.inherited&&T.confidence<St?e.lastDecoded||"en":T.lang,!g&&h&&!T.inherited&&T.confidence>=Mt&&n.length>=Et*p&&e.learned.add(T.lang)}}h&&M&&(e.lastDecoded=M)}let a="",S=null,A=null,z=null;try{if(e.remote){const g=await e.remote.transcribe(n,{lang:e.lang,langs:e.langs});a=g.text,z=g.lang||null}else{const g=m.__indic?e.langs?.length?{langs:[...new Set([...e.langs,"en"])],last:e.lastLang,choose:ie}:e.lang?{lang:e.lang}:{langs:[...Tt],last:e.lastLang,choose:ie}:me(x)?{}:{language:M||void 0,task:"transcribe"},O=m.__indic&&m.identify&&h&&g.langs&&n.length>=2*Ue*p?jt(n.length,(E=>(y,k)=>J(n,y,k)>=E)(It(n))):[],R=[0,...O,n.length];let T=null;if(O.length){const E=await m.identify(n,{langs:g.langs}),y=[];for(let k=0;k+1<R.length;k++){const N=await m.identify(n.subarray(R[k],R[k+1]),{langs:g.langs});y.push({from:R[k],to:R[k+1],scores:N?.scores||{}})}if(T=Ut(y,{base:E?.scores?ie(E.scores,n.length/p):null}),T.length>1){const k=[];for(let N=0;N<T.length;N++){const w=T[N],D=w.lang&&w.lang!=="en"&&(T[N-1]?.lang==="en"||T[N+1]?.lang==="en");k.push(D?ie((await m.identify(n.subarray(w.from,w.to),{langs:g.langs}))?.scores||{},(w.to-w.from)/p):w.lang)}T=zt(T,k)}T.length<2&&(T=null)}if(T){A=[];for(const E of T){const y=await m(n.subarray(E.from,E.to),E.lang?{lang:E.lang}:{...g}),k=String(y?.text||"").trim(),N=y?.lang||E.lang||null;k&&A.push({text:k,lang:N,from:E.from,to:E.to}),N&&(g.last=N)}}else{const E=await m(n,g);a=String(E?.text||"").trim(),m.__indic&&(S=E?.lang||null),m.__indic&&a&&(A=[{text:a,lang:S,from:0,to:n.length}])}if(A&&h&&g.langs&&(A=await Gt(A,R,async(E,y,k)=>String((await m(n.subarray(E,y),{lang:k}))?.text||"").trim())),A){a=A.map(y=>y.text).join(" ");const E=new Map;for(const y of A)y.lang&&E.set(y.lang,(E.get(y.lang)||0)+(y.to-y.from));S=[...E].sort((y,k)=>k[1]-y[1])[0]?.[0]||null,(A.length<2||E.size<2)&&(A=null)}}}catch(g){W(e,{type:"error",code:"decode_failed",message:g.message,fatal:!1}),h&&de(e,o,d);return}if(!a){h&&de(e,o,d);return}{const g=Dt(a);if(g.removed&&g.removed/g.total>=vt&&g.total>=12?a="":a=g.text,a&&ze(a)>He){const O=Nt(a);a=O.replace(/[\s\p{P}]/gu,"").length<12||ze(O)>He?"":O}if(!a){h&&de(e,o,d);return}}const ge=o>=ue*p,De=o>=We*p;if(t||u||ge||De){const g=t?"flush":u?"silence":De?"overflow":"length",O=g==="flush"||g==="silence";de(e,o,d);const R=fn(n,c);if(kt(a,R?R.length:0)||e.echo?.role==="mic"&&we.mostlyEcho(ee.verdict(e.echo,r,r+n.length)))return;let T=null,E=null;if(e.diarizer)try{const w=e.speakerLabel?null:await Y.spans(n),D=w?lt(w):[];if(D.length){const F=new Map;for(const{local:C}of st(D)){const U=it(n,D,C),le=U.length?await j.embed(U):null,ae=U.length<$e,X=U.length<Ce;F.set(C,e.diarizer.assign(le,{pinnedLabel:null,weak:ae,thin:X}))}const B=Math.round(r/p*1e3);E=D.map(C=>({startMs:B+Math.round(C.start*1e3),durationMs:Math.round((C.end-C.start)*1e3),speaker:F.get(C.local)})).filter(C=>C.speaker),T=F.get(at(D))||null}}catch{}if(e.diarizer&&!T)try{const w=R,D=w?await j.embed(w):null,F=!!w&&w.length<$e,B=!!w&&w.length<Ce;T=e.diarizer.assign(D,{pinnedLabel:e.speakerLabel,weak:F,thin:B})}catch{}let y=null;(e.langs||e.translateTo)&&(S?y=S:z?y=z:me(x)&&!e.remote?y="en":b?y=wt(a,M||e.lang)||null:y=e.lang||dt(a,{allowed:e.langs||[],last:e.lastLang}).lang,y&&y!==e.lastLang&&(e.lastLang=y,W(e,{type:"language",lang:y})));const k=Math.round(r/p*1e3),N=A&&(e.langs||e.translateTo)?A.map((w,D)=>({text:w.text,lang:w.lang,startMs:k+Math.round(w.from/p*1e3),durationMs:Math.round((w.to-w.from)/p*1e3),last:D===A.length-1})):[{text:a,lang:y,startMs:k,durationMs:Math.round(n.length/p*1e3),last:!0}];for(const w of N){N.length>1&&w.lang&&w.lang!==e.lastLang&&(e.lastLang=w.lang,W(e,{type:"language",lang:w.lang}));const{text:D,lang:F,startMs:B}=w,C=(D.match(new RegExp("\\p{Script=Latin}","gu"))||[]).length/Math.max(1,(D.match(new RegExp("\\p{L}","gu"))||[]).length),U=Z.indictransLanguage(F)&&C<.5&&Z.state()!=="error"&&ut(),le=!!e.translateTo&&gt(F,e.translateTo)&&(U||pt(D,F)&&ne.state()!=="error"),ae=N.length>1&&E?E.filter(X=>X.startMs<B+w.durationMs&&X.startMs+X.durationMs>B):E;if(W(e,{type:"final",text:D,reason:g,endOfTurn:w.last?O:!1,durationMs:w.durationMs,startMs:B,...F?{lang:F}:{},...le?{translating:!0}:{},...T?{speaker:T}:{},...ae?.length?{turns:ae}:{}}),le){const X=e.translateTo,pe=U?Z:ne;pe.state()==="off"&&pe.init({...e.translateLoad,...U?{sessionOptions:oe()}:{}}),e.translations=e.translations.then(async()=>{await pe.ready();const ve=U?await Z.translate(D,F):await ne.translate(D);W(e,{type:"translation",startMs:B,lang:F,to:X,text:ve||null,...ve?{}:{failed:!0}})}).catch(()=>{})}}}else a!==e.lastInterim&&(e.lastInterim=a,W(e,{type:"interim",text:a}))}async function gn(e){const t=fe(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(Q=Q.then(()=>be(t,{flush:!0}).catch(()=>{}))),await Promise.race([t.translations,new Promise(n=>setTimeout(n,ln).unref?.())])}finally{if(W(t,{type:"end"}),t.listeners.clear(),H.delete(t.id),t.poll){const n=setTimeout(()=>V.delete(t.id),Jt);n.unref?.(),V.set(t.id,{session:t,timer:n})}t.diarizer&&(j.release(),Y.release()),t.translateTo&&(ne.release(),Z.release()),t.echo&&we.release(),$.release(),ee.leave(t.echo),H.size===0&&ce()&&P?.arm()}return!0}function jn(){for(const e of H.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);H.clear();for(const e of V.values())clearTimeout(e.timer);V.clear(),P?.disarm(),P=null,_="off",x=null,m=null,v=null,q=null,L=null}function Bn(e,t="test/fake",{warmMs:n=null,dtype:o=null}={}){m=e,x=t,_=e?"ready":"off",K=o,n!==null&&(P=ye({warmMs:n,busy:re,unload:()=>Ee()}),e&&P.arm())}export{Vt as AUTO_FETCH_MAX_MB,He as COMPRESSION_LIMIT,Ct as FROM_ENGLISH,Ht as FROM_ENGLISH_RUN_S,vt as LOOP_DROP,Bt as PAUSE_SHARE,Ue as PIECE_MIN_S,Ot as PIECE_PAUSE_S,p as SAMPLE_RATE,Ft as SURE_ENGLISH,Ce as THIN_SPEAKER_SAMPLES,Rt as TO_ENGLISH,$t as WEAK_ENGLISH_MIN_S,$e as WEAK_SPEAKER_SAMPLES,jn as _reset,Bn as _setPipeForTest,cn as clampEndSilence,Dt as collapseLoops,Nt as collapseRuns,ze as compressionRatio,Fn as createSession,Un as decodeNow,Cn as drainEvents,gn as endSession,Hn as endedSession,fe as getSession,vn as health,Pn as init,ce as isReady,Ut as languageGroups,kt as looksHallucinated,Kt as modelOnDisk,rn as noiseFloorOf,jt as pauseCuts,It as pauseLevel,Dn as progress,zn as pushAudio,un as quietestCut,zt as relabelGroups,Gt as respellEnglish,se as runtimeDtype,Re as runtimeName,ie as segmentLanguage,Rn as sessionCount,On as setModel,on as silenceGate,Ke as speakerPlan,bn as state,oe as sttSessionOptions,Pt as sttThreads,$n as subscribe,Gn as toFloat32,Ee as unload,Nn as warmPending};
@@ -1 +1 @@
1
- import{verifyFresh as $}from"./model-integrity.js";import{existsSync as b,readdirSync as k}from"node:fs";import{join as P}from"node:path";import{ensureLib as T,modelRoot as A,withModelSource as E}from"./ner-engine.js";import{runtimeDtype as h,DTYPE_SUFFIX as R}from"./model-runtime.js";import{makeWarmTimer as F}from"./warm-timer.js";const D="Xenova/opus-mt-mul-en",v=112,O=1200;let t="off",p=D,c=null,f=null,u=null,i=null,s=null,y=0,m=0,w=Promise.resolve(),_=null;function Y(){return p}function q(){return t}function x(){return t==="ready"&&!!c}function z(){return i}function G(){return{configured:t!=="off",ok:x(),state:t,model:p,error:f,approxMB:v,onDisk:L(),warmMs:s?.warmMs??null}}function g(){return y>0||m>0||t==="loading"||t==="downloading"}function J(){m++,s?.disarm()}function K(){m=Math.max(0,m-1),m===0&&y===0&&x()&&s?.arm()}async function X({log:e=()=>{}}={}){if(g())return!1;s?.disarm();const n=c;if(c=null,_=null,u=null,i=null,f=null,t="off",n){try{await n.dispose?.()}catch{}e("[translate] idle — model unloaded (reloads on the next translated meeting)")}return!0}function L(e=p,n=h()){const d=P(A(),...e.split("/"),"onnx");if(!b(d))return!1;const r=R[n]??"";try{const o=k(d);return o.includes(`encoder_model${r}.onnx`)&&o.some(l=>l===`decoder_model_merged${r}.onnx`||l===`decoder_model${r}.onnx`)}catch{return!1}}async function B({log:e=()=>{},allowDownload:n=!0}={}){let d;try{d=await T()}catch(l){return t="error",f=l.message,e(`[translate] engine unavailable (${l.message})`),!1}const r=p,o=L(r);if(!o&&!n)return t="error",f="model not on disk and downloads disabled",!1;t=o?"loading":"downloading",o||(i={model:r,file:null,pct:0},e(`[translate] downloading ${r} (one-time, ~${v} MB)…`));try{const l=a=>{if(!a)return;const S=typeof a.progress=="number"?Math.round(a.progress):i?.pct??0;(a.status==="progress"||a.status==="download"||a.status==="initiate")&&(i={model:r,file:a.file||i?.file||null,pct:S})},M=await E({host:o?null:"https://huggingface.co/",allowRemote:!o},a=>a.pipeline("translation",r,{dtype:h(),progress_callback:l}));return await $(!o,r,{modelsDir:A(),log:e,dispose:()=>M.dispose?.()}),c=M,t="ready",f=null,i=null,e(`[translate] ready — ${r} @ ${h()} (meeting lines into English, in-process, offline)`),!0}catch(l){return f=l.message,i=null,t="error",e(`[translate] load failed (${l.message}) — lines stay in the language they were spoken in`),!1}}function I(e){return e.then(n=>(n&&!g()&&s?.arm(),n))}function Q(e={}){if(u&&t!=="error")return u;t="loading";const n=typeof e.onLog=="function"?e.onLog:()=>{};return s=F({warmMs:e.warmMs,busy:g,log:n,unload:()=>X({log:n})}),u=I(B({log:n,allowDownload:e.allowDownload!==!1})),u}function V(){return u?u.then(()=>x(),()=>!1):Promise.resolve(x())}function Z(e){const n=String(e||"").trim().slice(0,O);if(!n||!x())return Promise.resolve(null);y++,s?.disarm();const d=w.then(async()=>{try{if(_)return await _(n)??null;const r=await c(n,{max_new_tokens:400});return String((Array.isArray(r)?r[0]:r)?.translation_text||"").trim()||null}catch{return null}});return w=d.catch(()=>null),d.finally(()=>{y--,g()||s?.arm()})}function ee(){s?.disarm(),s=null,m=0,y=0,t="off",p=D,c=null,_=null,f=null,u=null,i=null,w=Promise.resolve()}function ne(e){_=e||null,c=e?{dispose:async()=>{}}:null,t=e?"ready":"off"}export{D as DEFAULT_TRANSLATE_MODEL,v as TRANSLATE_MODEL_APPROX_MB,ee as _reset,ne as _setForTest,Y as activeModel,G as health,Q as init,x as isReady,L as modelOnDisk,z as progress,V as ready,K as release,J as retain,q as state,Z as translate,X as unload};
1
+ import{verifyFresh as $}from"./model-integrity.js";import{existsSync as b,readdirSync as k}from"node:fs";import{join as P}from"node:path";import{ensureLib as T,modelRoot as A,withModelSource as E}from"./ner-engine.js";import{runtimeDtype as h,DTYPE_SUFFIX as R}from"./model-runtime.js";import{makeWarmTimer as F}from"./warm-timer.js";import{engineLoadOptions as O}from"./ort.js";const D="Xenova/opus-mt-mul-en",L=112,X=1200;let t="off",p=D,c=null,f=null,u=null,a=null,i=null,y=0,m=0,w=Promise.resolve(),_=null;function z(){return p}function G(){return t}function g(){return t==="ready"&&!!c}function J(){return a}function K(){return{configured:t!=="off",ok:g(),state:t,model:p,error:f,approxMB:L,onDisk:v(),warmMs:i?.warmMs??null}}function x(){return y>0||m>0||t==="loading"||t==="downloading"}function Q(){m++,i?.disarm()}function V(){m=Math.max(0,m-1),m===0&&y===0&&g()&&i?.arm()}async function B({log:e=()=>{}}={}){if(x())return!1;i?.disarm();const n=c;if(c=null,_=null,u=null,a=null,f=null,t="off",n){try{await n.dispose?.()}catch{}e("[translate] idle — model unloaded (reloads on the next translated meeting)")}return!0}function v(e=p,n=h()){const d=P(A(),...e.split("/"),"onnx");if(!b(d))return!1;const r=R[n]??"";try{const o=k(d);return o.includes(`encoder_model${r}.onnx`)&&o.some(l=>l===`decoder_model_merged${r}.onnx`||l===`decoder_model${r}.onnx`)}catch{return!1}}async function I({log:e=()=>{},allowDownload:n=!0}={}){let d;try{d=await T()}catch(l){return t="error",f=l.message,e(`[translate] engine unavailable (${l.message})`),!1}const r=p,o=v(r);if(!o&&!n)return t="error",f="model not on disk and downloads disabled",!1;t=o?"loading":"downloading",o||(a={model:r,file:null,pct:0},e(`[translate] downloading ${r} (one-time, ~${L} MB)…`));try{const l=s=>{if(!s)return;const S=typeof s.progress=="number"?Math.round(s.progress):a?.pct??0;(s.status==="progress"||s.status==="download"||s.status==="initiate")&&(a={model:r,file:s.file||a?.file||null,pct:S})},M=await E({host:o?null:"https://huggingface.co/",allowRemote:!o},s=>s.pipeline("translation",r,{dtype:h(),progress_callback:l,...O()}));return await $(!o,r,{modelsDir:A(),log:e,dispose:()=>M.dispose?.()}),c=M,t="ready",f=null,a=null,e(`[translate] ready — ${r} @ ${h()} (meeting lines into English, in-process, offline)`),!0}catch(l){return f=l.message,a=null,t="error",e(`[translate] load failed (${l.message}) — lines stay in the language they were spoken in`),!1}}function N(e){return e.then(n=>(n&&!x()&&i?.arm(),n))}function Z(e={}){if(u&&t!=="error")return u;t="loading";const n=typeof e.onLog=="function"?e.onLog:()=>{};return i=F({warmMs:e.warmMs,busy:x,log:n,unload:()=>B({log:n})}),u=N(I({log:n,allowDownload:e.allowDownload!==!1})),u}function ee(){return u?u.then(()=>g(),()=>!1):Promise.resolve(g())}function ne(e){const n=String(e||"").trim().slice(0,X);if(!n||!g())return Promise.resolve(null);y++,i?.disarm();const d=w.then(async()=>{try{if(_)return await _(n)??null;const r=await c(n,{max_new_tokens:400});return String((Array.isArray(r)?r[0]:r)?.translation_text||"").trim()||null}catch{return null}});return w=d.catch(()=>null),d.finally(()=>{y--,x()||i?.arm()})}function te(){i?.disarm(),i=null,m=0,y=0,t="off",p=D,c=null,_=null,f=null,u=null,a=null,w=Promise.resolve()}function re(e){_=e||null,c=e?{dispose:async()=>{}}:null,t=e?"ready":"off"}export{D as DEFAULT_TRANSLATE_MODEL,L as TRANSLATE_MODEL_APPROX_MB,te as _reset,re as _setForTest,z as activeModel,K as health,Z as init,g as isReady,v as modelOnDisk,J as progress,ee as ready,V as release,Q as retain,G as state,ne as translate,B as unload};
package/src/tts-engine.js CHANGED
@@ -1 +1 @@
1
- import{verifyFresh as rt}from"./model-integrity.js";import{modelFetch as ot}from"./model-sources.js";import{join as L}from"node:path";import{existsSync as B,mkdirSync as st,readFileSync as it,writeFileSync as lt,renameSync as at,statSync as C}from"node:fs";import{ensureLib as ut,modelRoot as G}from"./ner-engine.js";import{runtimeDtype as N,runtimeName as q,DTYPE_SUFFIX as ct}from"./model-runtime.js";import{DEFAULT_TTS_MODEL as P,DEFAULT_TTS_VOICE as J,STYLE_DIM as U,ttsModelDtype as K,isKnownTtsModel as ft,isValidVoiceId as Q,voiceLang as pt,ttsModelEngine as Z,ttsModel as I}from"./tts-models.js";import{bundleOnDisk as dt}from"./pocket-tts-engine.js";import{makeWarmTimer as j}from"./warm-timer.js";const O=24e3;let f="off",m=null,R=0,h=null,y=null,v=null,A=null,T=null,_=null,D=null,d=null,x=null,g=null,k=null,b=O;const H=new Map,ht={style_text_to_speech_2:"style-tts2",vits:"vits",speecht5:"speecht5"},M="pocket-tts",wt="Xenova/speecht5_hifigan";function mt(){return d==="speecht5"||d===M}function Vt(){return d===M}function Rt(){return g?.builtinVoices?.()||[]}async function Ht({allowDownload:t=!0,log:e=()=>{}}={}){if(m?.arm(),g)return g;const{PocketTTS:n,bundleOnDisk:r,DEFAULT_BUNDLE:o}=await import("./pocket-tts-engine.js");if(!r(o)&&!t)return null;if(k)return k;const i=new n;return await i.load(o,{log:e}),k=i,i}function zt(){return d}function Bt(){return b}function yt(){return d==="style-tts2"}function Ct(){return f}function V(){return f==="ready"&&!!y}function Nt(){return _}function Kt(){return{configured:f!=="off",ok:V(),state:f,model:h,dtype:A,runtime:q(),error:T,arch:d,sampleRate:b,voices:yt(),customVoices:mt(),warmMs:m?.warmMs??null}}function jt(){return!!m?.pending()}function F(){return R>0||f==="loading"||f==="downloading"}async function W({log:t=()=>{}}={}){if(F())return!1;m?.disarm();const e=!!(y||g||k),n=[y,x,g,k];y=null,v=null,x=null,g=null,k=null,d=null,A=null,D=null,_=null,T=null,f="off",b=O,H.clear();for(const r of new Set(n))if(r)try{await r.dispose?.()}catch{}return e&&t(`[tts] idle for ${Math.round((m?.warmMs||0)/6e4)} min — model unloaded (reloads on next speech)`),!0}function gt(t){return t.then(e=>(e&&!F()&&m?.arm(),e))}function X(t){return L(G(),...String(t).split("/"))}function _t(t=h||P,e=K(t)||N()){if(Z(t)===M)return dt(I(t)?.bundle);const n=X(t),r=ct[e]??"",o=[L(n,"onnx",`model${r}.onnx`),L(n,"tokenizer.json")];try{return o.every(i=>B(i)&&C(i).size>0)}catch{return!1}}function Wt(t,e=h||P){if(!Q(t))return!1;const n=L(X(e),"voices",`${t}.bin`);try{return B(n)&&C(n).size>0}catch{return!1}}function Xt(t={}){const e=t.tts||{};if(e.enabled===!1){f="off";return}h=e.model||P,m=j({warmMs:e.warmMs,busy:F,unload:()=>W()})}async function Tt(t,{log:e=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(Z(t)===M)return Et(t,{log:e,allowDownload:n});const o=y,i=h;let c;try{c=await ut()}catch(l){return f="error",T=`engine load failed: ${l.message}`,e(`[tts] transformers.js not available (${l.message}) — read-aloud falls back to browser speech`),!1}const p=(r&&r!=="auto"?r:null)||K(t)||N(),s=_t(t,p);if(c.env.allowRemoteModels=s?!1:!!n,!s&&!n)return f="error",T="model not on disk and downloads disabled",e(`[tts] model ${t} not installed and downloads disabled`),!1;const u=c.env.remoteHost;if(!s&&(!!1||!ft(t)))try{c.env.remoteHost="https://huggingface.co/"}catch{}f=s?"loading":"downloading",s||(_={model:t,file:null,pct:0},e(`[tts] downloading voice model ${t} (one-time)…`));try{const l=await import("@huggingface/transformers");let E="";try{const $=await l.AutoConfig.from_pretrained(t);E=String($?.model_type||"").toLowerCase()}catch{}const S=ht[E]||(E?null:"style-tts2");if(!S)throw new Error(`unsupported TTS architecture "${E}" — this engine drives Kokoro (style_text_to_speech_2) and VITS/MMS`);const Y=$=>{$?.status==="progress"&&$.file&&(_={model:t,file:$.file,pct:Math.round($.progress||0)})},et=S==="vits"?l.VitsModel:S==="speecht5"?l.SpeechT5ForTextToSpeech:l.StyleTextToSpeech2Model,[z,nt]=await Promise.all([et.from_pretrained(t,{dtype:p,progress_callback:Y}),l.AutoTokenizer.from_pretrained(t)]);return x=S==="speecht5"?await l.SpeechT5HifiGan.from_pretrained(wt,{dtype:p,progress_callback:Y}):null,await rt(!s,t,{modelsDir:G(),log:e,dispose:async()=>{await z?.dispose?.(),await x?.dispose?.(),x=null}}),y=z,v=nt,h=t,A=p,d=S,b=Number(z?.config?.sampling_rate)||(S==="style-tts2"?O:16e3),f="ready",T=null,_=null,e(`[tts] ready — model ${t} @ ${p} (${S}, ${b} Hz, ${q()}, offline) — local speech active`),!0}catch(l){return y=o,h=i,f=o?"ready":"error",T=l.message,_=null,e(`[tts] model load failed (${l.message})`),!1}finally{try{c.env.remoteHost=u}catch{}}}async function Et(t,{log:e=()=>{},allowDownload:n=!0}={}){const r=d,o=g,i=h,{PocketTTS:c,bundleOnDisk:w,DEFAULT_BUNDLE:p,SAMPLE_RATE:s}=await import("./pocket-tts-engine.js"),u=I(t)?.bundle||p;if(!w(u)&&!n)return f="error",T="model not on disk and downloads disabled",!1;f=w(u)?"loading":"downloading",f==="downloading"&&(_={model:t,file:null,pct:0});try{const a=new c;return await a.load(u,{log:e,onProgress:({file:l,pct:E})=>{_={model:t,file:l,pct:E}}}),g=a,y=a,v=null,x=null,h=t,d=M,A="int8",b=s,f="ready",T=null,_=null,!0}catch(a){return g=o,d=r,h=i,f=o||y?"ready":"error",T=a.message,_=null,e(`[pocket-tts] load failed (${a.message})`),!1}}async function St(t,{onLog:e=()=>{},allowDownload:n=!0,dtype:r="auto"}={}){const o=r&&r!=="auto"?r:K(t)||N();return t===h&&V()&&A===o?!0:(m??=j({warmMs:void 0,busy:F,unload:()=>W()}),D=gt(Tt(t,{log:e,allowDownload:n,dtype:r})),D)}async function Yt({onLog:t=()=>{},allowDownload:e=!0,model:n=null,dtype:r="auto"}={}){return V()?!0:D||St(n||h||P,{onLog:t,allowDownload:e,dtype:r})}async function xt(t,{allowDownload:e=!0,log:n=()=>{}}={}){if(!Q(t))throw new Error(`invalid voice id: ${t}`);const r=H.get(t);if(r)return r;const o=L(X(h||P),"voices"),i=L(o,`${t}.bin`);if(!(B(i)&&C(i).size>0)){if(!e)throw new Error(`voice ${t} not on disk and downloads disabled`);st(o,{recursive:!0});const p=`https://huggingface.co/${h||P}/resolve/main/voices/${t}.bin`,s=await ot()(p,{redirect:"follow"});if(!s.ok)throw new Error(`fetch voice ${t} → HTTP ${s.status}`);const u=`${i}.part`;lt(u,Buffer.from(await s.arrayBuffer())),at(u,i),n(`[tts] fetched voice ${t}`)}const c=it(i),w=new Float32Array(c.buffer,c.byteOffset,Math.floor(c.byteLength/4));return H.set(t,w),w}function Mt(t,e=300){const n=(o,i)=>{if(o.length<=e)return[o];if(!i.length){const u=[];for(let a=0;a<o.length;a+=e)u.push(o.slice(a,a+e).trim());return u.filter(Boolean)}const[c,...w]=i,p=[];let s="";for(const u of o.split(c)){const a=u.trim();if(!a)continue;const l=s?`${s} ${a}`:a;l.length>e&&s?(p.push(...n(s,w)),s=a):s=l}return s&&p.push(...n(s,w)),p},r=[];for(const o of String(t).split(/(?<=[.!?])\s+|\n{2,}/)){const i=o.trim();i&&r.push(...n(i,[/(?<=[,;:])\s+/,/\s+/]))}return r}async function tt(t,{voice:e=J,speed:n=1,speakerEmbedding:r=null}={}){if(!V())throw new Error("tts model not ready");const o=await import("@huggingface/transformers");if(d==="vits"){const l=v(String(t));return(await y(l)).waveform.data}if(d===M){const l=r?.data?.length?r:e;if(!l)throw new Error("this model needs a voice — pick a built-in one or record your own");return g.synth(String(t),{voice:l})}if(d==="speecht5"){if(!r||r.length!==512)throw new Error("this model needs a saved voice — record one in Settings → Text-to-speech");const{input_ids:l}=v(String(t)),E=new o.Tensor("float32",Float32Array.from(r),[1,512]),{waveform:S}=await y.generate_speech(l,E,{vocoder:x});return S.data}const{phonemize:i}=await import("phonemizer"),c=(await i(String(t),pt(e))).join(" "),{input_ids:w}=v(c,{truncation:!0}),p=await xt(e),s=Math.min(Math.max(w.dims.at(-1)-2,0),Math.floor(p.length/U)-1),u=p.slice(s*U,s*U+U);return(await y({input_ids:w,style:new o.Tensor("float32",u,[1,U]),speed:new o.Tensor("float32",[n],[1])})).waveform.data}async function Gt(t,e={}){R++,m?.disarm();try{return await vt(t,e)}finally{R--,!F()&&V()&&m?.arm()}}async function vt(t,{voice:e=J,speed:n=1,speakerEmbedding:r=null,onChunk:o=null}={}){if(d===M)return tt(t,{voice:e,speed:n,speakerEmbedding:r});const i=Mt(t),c=[];for(const u of i){const a=await tt(u,{voice:e,speed:n,speakerEmbedding:r});c.push(a),o?.(a)}if(c.length===1)return c[0];const w=c.reduce((u,a)=>u+a.length,0),p=new Float32Array(w);let s=0;for(const u of c)p.set(u,s),s+=u.length;return p}function qt(t,e=O){const n=Buffer.alloc(44+t.length*2);n.write("RIFF",0),n.writeUInt32LE(36+t.length*2,4),n.write("WAVE",8),n.write("fmt ",12),n.writeUInt32LE(16,16),n.writeUInt16LE(1,20),n.writeUInt16LE(1,22),n.writeUInt32LE(e,24),n.writeUInt32LE(e*2,28),n.writeUInt16LE(2,32),n.writeUInt16LE(16,34),n.write("data",36),n.writeUInt32LE(t.length*2,40);for(let r=0;r<t.length;r++){const o=Math.max(-1,Math.min(1,t[r]));n.writeInt16LE(Math.round(o*32767),44+r*2)}return n}function Jt(t,{warmMs:e=null}={}){y=t,g=t,d=t?M:null,h=t?"test/fake":null,f=t?"ready":"off",e!==null&&(m=j({warmMs:e,busy:F,unload:()=>W()}),t&&m.arm())}function Qt(){m?.disarm(),m=null,R=0,f="off",h=null,y=null,v=null,A=null,T=null,_=null,D=null,d=null,b=O,x=null,g=null,k=null,H.clear()}export{M as POCKET_ARCH,O as SAMPLE_RATE,wt as SPEECHT5_VOCODER,ht as SUPPORTED_ARCH,Qt as _reset,Jt as _setForTest,zt as arch,Rt as builtinVoices,Kt as health,Xt as init,Vt as isPocket,V as isReady,X as modelDir,_t as modelOnDisk,Ht as pocketForEncoding,Nt as progress,Yt as ready,Bt as sampleRate,St as setModel,Mt as splitSentences,Ct as state,mt as supportsCustomVoices,yt as supportsVoices,Gt as synth,tt as synthChunk,qt as toWav,W as unload,Wt as voiceOnDisk,jt as warmPending};
1
+ import{verifyFresh as ot}from"./model-integrity.js";import{modelFetch as st}from"./model-sources.js";import{join as $}from"node:path";import{existsSync as B,mkdirSync as it,readFileSync as lt,writeFileSync as at,renameSync as ut,statSync as C}from"node:fs";import{ensureLib as ct,modelRoot as G}from"./ner-engine.js";import{runtimeDtype as N,runtimeName as q,DTYPE_SUFFIX as ft}from"./model-runtime.js";import{DEFAULT_TTS_MODEL as P,DEFAULT_TTS_VOICE as J,STYLE_DIM as U,ttsModelDtype as K,isKnownTtsModel as pt,isValidVoiceId as Q,voiceLang as dt,ttsModelEngine as Z,ttsModel as I}from"./tts-models.js";import{bundleOnDisk as ht}from"./pocket-tts-engine.js";import{makeWarmTimer as j}from"./warm-timer.js";import{engineLoadOptions as tt}from"./ort.js";const O=24e3;let f="off",w=null,R=0,h=null,y=null,v=null,A=null,T=null,_=null,D=null,d=null,x=null,g=null,k=null,b=O;const H=new Map,mt={style_text_to_speech_2:"style-tts2",vits:"vits",speecht5:"speecht5"},M="pocket-tts",wt="Xenova/speecht5_hifigan";function yt(){return d==="speecht5"||d===M}function Ht(){return d===M}function zt(){return g?.builtinVoices?.()||[]}async function Bt({allowDownload:t=!0,log:e=()=>{}}={}){if(w?.arm(),g)return g;const{PocketTTS:n,bundleOnDisk:r,DEFAULT_BUNDLE:o}=await import("./pocket-tts-engine.js");if(!r(o)&&!t)return null;if(k)return k;const i=new n;return await i.load(o,{log:e}),k=i,i}function Ct(){return d}function Nt(){return b}function gt(){return d==="style-tts2"}function Kt(){return f}function V(){return f==="ready"&&!!y}function jt(){return _}function Wt(){return{configured:f!=="off",ok:V(),state:f,model:h,dtype:A,runtime:q(),error:T,arch:d,sampleRate:b,voices:gt(),customVoices:yt(),warmMs:w?.warmMs??null}}function Xt(){return!!w?.pending()}function F(){return R>0||f==="loading"||f==="downloading"}async function W({log:t=()=>{}}={}){if(F())return!1;w?.disarm();const e=!!(y||g||k),n=[y,x,g,k];y=null,v=null,x=null,g=null,k=null,d=null,A=null,D=null,_=null,T=null,f="off",b=O,H.clear();for(const r of new Set(n))if(r)try{await r.dispose?.()}catch{}return e&&t(`[tts] idle for ${Math.round((w?.warmMs||0)/6e4)} min — model unloaded (reloads on next speech)`),!0}function _t(t){return t.then(e=>(e&&!F()&&w?.arm(),e))}function X(t){return $(G(),...String(t).split("/"))}function Tt(t=h||P,e=K(t)||N()){if(Z(t)===M)return ht(I(t)?.bundle);const n=X(t),r=ft[e]??"",o=[$(n,"onnx",`model${r}.onnx`),$(n,"tokenizer.json")];try{return o.every(i=>B(i)&&C(i).size>0)}catch{return!1}}function Yt(t,e=h||P){if(!Q(t))return!1;const n=$(X(e),"voices",`${t}.bin`);try{return B(n)&&C(n).size>0}catch{return!1}}function Gt(t={}){const e=t.tts||{};if(e.enabled===!1){f="off";return}h=e.model||P,w=j({warmMs:e.warmMs,busy:F,unload:()=>W()})}async function Et(t,{log:e=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(Z(t)===M)return St(t,{log:e,allowDownload:n});const o=y,i=h;let c;try{c=await ct()}catch(l){return f="error",T=`engine load failed: ${l.message}`,e(`[tts] transformers.js not available (${l.message}) — read-aloud falls back to browser speech`),!1}const p=(r&&r!=="auto"?r:null)||K(t)||N(),s=Tt(t,p);if(c.env.allowRemoteModels=s?!1:!!n,!s&&!n)return f="error",T="model not on disk and downloads disabled",e(`[tts] model ${t} not installed and downloads disabled`),!1;const u=c.env.remoteHost;if(!s&&(!!1||!pt(t)))try{c.env.remoteHost="https://huggingface.co/"}catch{}f=s?"loading":"downloading",s||(_={model:t,file:null,pct:0},e(`[tts] downloading voice model ${t} (one-time)…`));try{const l=await import("@huggingface/transformers");let E="";try{const L=await l.AutoConfig.from_pretrained(t);E=String(L?.model_type||"").toLowerCase()}catch{}const S=mt[E]||(E?null:"style-tts2");if(!S)throw new Error(`unsupported TTS architecture "${E}" — this engine drives Kokoro (style_text_to_speech_2) and VITS/MMS`);const Y=L=>{L?.status==="progress"&&L.file&&(_={model:t,file:L.file,pct:Math.round(L.progress||0)})},nt=S==="vits"?l.VitsModel:S==="speecht5"?l.SpeechT5ForTextToSpeech:l.StyleTextToSpeech2Model,[z,rt]=await Promise.all([nt.from_pretrained(t,{dtype:p,progress_callback:Y,...tt({share:2})}),l.AutoTokenizer.from_pretrained(t)]);return x=S==="speecht5"?await l.SpeechT5HifiGan.from_pretrained(wt,{dtype:p,progress_callback:Y,...tt({share:2})}):null,await ot(!s,t,{modelsDir:G(),log:e,dispose:async()=>{await z?.dispose?.(),await x?.dispose?.(),x=null}}),y=z,v=rt,h=t,A=p,d=S,b=Number(z?.config?.sampling_rate)||(S==="style-tts2"?O:16e3),f="ready",T=null,_=null,e(`[tts] ready — model ${t} @ ${p} (${S}, ${b} Hz, ${q()}, offline) — local speech active`),!0}catch(l){return y=o,h=i,f=o?"ready":"error",T=l.message,_=null,e(`[tts] model load failed (${l.message})`),!1}finally{try{c.env.remoteHost=u}catch{}}}async function St(t,{log:e=()=>{},allowDownload:n=!0}={}){const r=d,o=g,i=h,{PocketTTS:c,bundleOnDisk:m,DEFAULT_BUNDLE:p,SAMPLE_RATE:s}=await import("./pocket-tts-engine.js"),u=I(t)?.bundle||p;if(!m(u)&&!n)return f="error",T="model not on disk and downloads disabled",!1;f=m(u)?"loading":"downloading",f==="downloading"&&(_={model:t,file:null,pct:0});try{const a=new c;return await a.load(u,{log:e,onProgress:({file:l,pct:E})=>{_={model:t,file:l,pct:E}}}),g=a,y=a,v=null,x=null,h=t,d=M,A="int8",b=s,f="ready",T=null,_=null,!0}catch(a){return g=o,d=r,h=i,f=o||y?"ready":"error",T=a.message,_=null,e(`[pocket-tts] load failed (${a.message})`),!1}}async function xt(t,{onLog:e=()=>{},allowDownload:n=!0,dtype:r="auto"}={}){const o=r&&r!=="auto"?r:K(t)||N();return t===h&&V()&&A===o?!0:(w??=j({warmMs:void 0,busy:F,unload:()=>W()}),D=_t(Et(t,{log:e,allowDownload:n,dtype:r})),D)}async function qt({onLog:t=()=>{},allowDownload:e=!0,model:n=null,dtype:r="auto"}={}){return V()?!0:D||xt(n||h||P,{onLog:t,allowDownload:e,dtype:r})}async function Mt(t,{allowDownload:e=!0,log:n=()=>{}}={}){if(!Q(t))throw new Error(`invalid voice id: ${t}`);const r=H.get(t);if(r)return r;const o=$(X(h||P),"voices"),i=$(o,`${t}.bin`);if(!(B(i)&&C(i).size>0)){if(!e)throw new Error(`voice ${t} not on disk and downloads disabled`);it(o,{recursive:!0});const p=`https://huggingface.co/${h||P}/resolve/main/voices/${t}.bin`,s=await st()(p,{redirect:"follow"});if(!s.ok)throw new Error(`fetch voice ${t} → HTTP ${s.status}`);const u=`${i}.part`;at(u,Buffer.from(await s.arrayBuffer())),ut(u,i),n(`[tts] fetched voice ${t}`)}const c=lt(i),m=new Float32Array(c.buffer,c.byteOffset,Math.floor(c.byteLength/4));return H.set(t,m),m}function vt(t,e=300){const n=(o,i)=>{if(o.length<=e)return[o];if(!i.length){const u=[];for(let a=0;a<o.length;a+=e)u.push(o.slice(a,a+e).trim());return u.filter(Boolean)}const[c,...m]=i,p=[];let s="";for(const u of o.split(c)){const a=u.trim();if(!a)continue;const l=s?`${s} ${a}`:a;l.length>e&&s?(p.push(...n(s,m)),s=a):s=l}return s&&p.push(...n(s,m)),p},r=[];for(const o of String(t).split(/(?<=[.!?])\s+|\n{2,}/)){const i=o.trim();i&&r.push(...n(i,[/(?<=[,;:])\s+/,/\s+/]))}return r}async function et(t,{voice:e=J,speed:n=1,speakerEmbedding:r=null}={}){if(!V())throw new Error("tts model not ready");const o=await import("@huggingface/transformers");if(d==="vits"){const l=v(String(t));return(await y(l)).waveform.data}if(d===M){const l=r?.data?.length?r:e;if(!l)throw new Error("this model needs a voice — pick a built-in one or record your own");return g.synth(String(t),{voice:l})}if(d==="speecht5"){if(!r||r.length!==512)throw new Error("this model needs a saved voice — record one in Settings → Text-to-speech");const{input_ids:l}=v(String(t)),E=new o.Tensor("float32",Float32Array.from(r),[1,512]),{waveform:S}=await y.generate_speech(l,E,{vocoder:x});return S.data}const{phonemize:i}=await import("phonemizer"),c=(await i(String(t),dt(e))).join(" "),{input_ids:m}=v(c,{truncation:!0}),p=await Mt(e),s=Math.min(Math.max(m.dims.at(-1)-2,0),Math.floor(p.length/U)-1),u=p.slice(s*U,s*U+U);return(await y({input_ids:m,style:new o.Tensor("float32",u,[1,U]),speed:new o.Tensor("float32",[n],[1])})).waveform.data}async function Jt(t,e={}){R++,w?.disarm();try{return await kt(t,e)}finally{R--,!F()&&V()&&w?.arm()}}async function kt(t,{voice:e=J,speed:n=1,speakerEmbedding:r=null,onChunk:o=null}={}){if(d===M)return et(t,{voice:e,speed:n,speakerEmbedding:r});const i=vt(t),c=[];for(const u of i){const a=await et(u,{voice:e,speed:n,speakerEmbedding:r});c.push(a),o?.(a)}if(c.length===1)return c[0];const m=c.reduce((u,a)=>u+a.length,0),p=new Float32Array(m);let s=0;for(const u of c)p.set(u,s),s+=u.length;return p}function Qt(t,e=O){const n=Buffer.alloc(44+t.length*2);n.write("RIFF",0),n.writeUInt32LE(36+t.length*2,4),n.write("WAVE",8),n.write("fmt ",12),n.writeUInt32LE(16,16),n.writeUInt16LE(1,20),n.writeUInt16LE(1,22),n.writeUInt32LE(e,24),n.writeUInt32LE(e*2,28),n.writeUInt16LE(2,32),n.writeUInt16LE(16,34),n.write("data",36),n.writeUInt32LE(t.length*2,40);for(let r=0;r<t.length;r++){const o=Math.max(-1,Math.min(1,t[r]));n.writeInt16LE(Math.round(o*32767),44+r*2)}return n}function Zt(t,{warmMs:e=null}={}){y=t,g=t,d=t?M:null,h=t?"test/fake":null,f=t?"ready":"off",e!==null&&(w=j({warmMs:e,busy:F,unload:()=>W()}),t&&w.arm())}function It(){w?.disarm(),w=null,R=0,f="off",h=null,y=null,v=null,A=null,T=null,_=null,D=null,d=null,b=O,x=null,g=null,k=null,H.clear()}export{M as POCKET_ARCH,O as SAMPLE_RATE,wt as SPEECHT5_VOCODER,mt as SUPPORTED_ARCH,It as _reset,Zt as _setForTest,Ct as arch,zt as builtinVoices,Wt as health,Gt as init,Ht as isPocket,V as isReady,X as modelDir,Tt as modelOnDisk,Bt as pocketForEncoding,jt as progress,qt as ready,Nt as sampleRate,xt as setModel,vt as splitSentences,Kt as state,yt as supportsCustomVoices,gt as supportsVoices,Jt as synth,et as synthChunk,Qt as toWav,W as unload,Yt as voiceOnDisk,Xt as warmPending};
package/src/vad-engine.js CHANGED
@@ -1 +1 @@
1
- import{verifyFresh as b}from"./model-integrity.js";import{existsSync as k}from"node:fs";import{join as F}from"node:path";import{ensureLib as O,modelRoot as v,withModelSource as S}from"./ner-engine.js";import{makeWarmTimer as R}from"./warm-timer.js";const h="onnx-community/silero-vad",U=2.2,D=16e3,s=512,V=.5,C=.35,N=.05,P=40,I=62;let o="off",f=null,M=null,d=null,g=null,w=null,c=null,x=0,y=0,_=null;function H(){return o}function L(){return o==="ready"&&(!!f||!!_)}function J(){return w}function Q(){return{configured:o!=="off",ok:L(),state:o,model:h,error:d,warmMs:c?.warmMs??null}}function A(){return y>0||x>0||o==="loading"||o==="downloading"}function Y(){x++,c?.disarm()}function Z(){x=Math.max(0,x-1),x===0&&y===0&&L()&&c?.arm()}function B(){return k(F(v(),...h.split("/"),"onnx","model.onnx"))}async function G({log:e=()=>{}}={}){if(A())return!1;c?.disarm();const n=f;if(f=null,g=null,w=null,d=null,o="off",n){try{await n.dispose?.()}catch{}e("[vad] idle — model unloaded")}return!0}async function W({log:e=()=>{},allowDownload:n=!0}={}){try{M=await O()}catch(r){return o="error",d=r.message,!1}const t=B();if(!t&&!n)return o="error",d="model not on disk and downloads disabled",!1;o=t?"loading":"downloading",t||(w={model:h,file:null,pct:0},e(`[vad] downloading ${h} (one-time, ~2 MB)…`));try{return f=await S({host:t?null:"https://huggingface.co/",allowRemote:!t},r=>r.AutoModel.from_pretrained(h,{config:{model_type:"custom"},dtype:"fp32"})),await b(!t,h,{modelsDir:v(),log:e,dispose:async()=>{await f?.dispose?.(),f=null}}),o="ready",d=null,w=null,e("[vad] ready — Silero VAD on levelled audio decides what is speech (the energy gate is the fallback)"),!0}catch(r){return d=r.message,w=null,o="error",e(`[vad] load failed (${r.message}) — the energy gate decides, as before`),!1}}function ee(e={}){if(g&&o!=="error")return g;o="loading";const n=typeof e.onLog=="function"?e.onLog:()=>{};return c=R({warmMs:e.warmMs,busy:A,log:n,unload:()=>G({log:n})}),g=W({log:n,allowDownload:e.allowDownload!==!1}).then(t=>(t&&!A()&&c?.arm(),t)),g}function j(e){if(!e.length)return 1;const n=[...e].sort((r,E)=>r-E),t=n[Math.floor(n.length*.9)]||0;return t>0?Math.min(P,Math.max(1,N/t)):1}function te(){let e=null,n=0;const t=new Map,r=[],E=Math.ceil(90*D/s);async function T(l){let i=0;for(let u=0;u<l.length;u++)i+=l[u]*l[u];r.push(Math.sqrt(i/l.length)),r.length>I&&r.shift();const p=j(r),a=p===1?l:l.map(u=>u*p);if(_)return _(a);e||=new M.Tensor("float32",new Float32Array(256),[2,1,128]);const m=await f({input:new M.Tensor("float32",a,[1,s]),sr:new M.Tensor("int64",[BigInt(D)],[]),state:e});return e=m.stateN,Number(m.output.data[0])}return{async advance(l,i){if(!L())return!1;const p=i+l.length;n<i&&(n=Math.ceil(i/s)*s),y++;try{for(;n+s<=p;n+=s){const a=n-i;t.set(n/s,await T(l.slice(a,a+s)))}}catch{return!1}finally{y--}for(const a of t.keys()){if(t.size<=E)break;t.delete(a)}return!0},speechIn(l,i,p=V){let a=!1;for(let m=Math.floor(l/s);m*s<i;m++){const u=t.get(m);if(u!==void 0&&(a=!0,u>=p))return!0}return a?!1:null},_probs:t}}function ne(){c?.disarm(),c=null,x=0,y=0,o="off",f=null,_=null,d=null,g=null,w=null}function oe(e){_=e||null,o=e?"ready":"off"}export{h as DEFAULT_VAD_MODEL,s as FRAME,P as LEVEL_MAX_GAIN,N as LEVEL_TARGET,I as LEVEL_WINDOW,C as OFFSET,V as ONSET,D as SAMPLE_RATE,U as VAD_MODEL_APPROX_MB,ne as _reset,oe as _setForTest,te as createStream,Q as health,ee as init,L as isReady,j as levelGain,B as modelOnDisk,J as progress,Z as release,Y as retain,H as state,G as unload};
1
+ import{verifyFresh as b}from"./model-integrity.js";import{existsSync as k}from"node:fs";import{join as O}from"node:path";import{ensureLib as F,modelRoot as v,withModelSource as S}from"./ner-engine.js";import{makeWarmTimer as R}from"./warm-timer.js";import{engineLoadOptions as V}from"./ort.js";const h="onnx-community/silero-vad",H=2.2,D=16e3,i=512,N=.5,J=.35,P=.05,I=40,B=62;let o="off",f=null,M=null,c=null,g=null,w=null,d=null,x=0,y=0,_=null;function Q(){return o}function L(){return o==="ready"&&(!!f||!!_)}function Y(){return w}function Z(){return{configured:o!=="off",ok:L(),state:o,model:h,error:c,warmMs:d?.warmMs??null}}function A(){return y>0||x>0||o==="loading"||o==="downloading"}function ee(){x++,d?.disarm()}function te(){x=Math.max(0,x-1),x===0&&y===0&&L()&&d?.arm()}function G(){return k(O(v(),...h.split("/"),"onnx","model.onnx"))}async function W({log:e=()=>{}}={}){if(A())return!1;d?.disarm();const n=f;if(f=null,g=null,w=null,c=null,o="off",n){try{await n.dispose?.()}catch{}e("[vad] idle — model unloaded")}return!0}async function j({log:e=()=>{},allowDownload:n=!0}={}){try{M=await F()}catch(r){return o="error",c=r.message,!1}const t=G();if(!t&&!n)return o="error",c="model not on disk and downloads disabled",!1;o=t?"loading":"downloading",t||(w={model:h,file:null,pct:0},e(`[vad] downloading ${h} (one-time, ~2 MB)…`));try{return f=await S({host:t?null:"https://huggingface.co/",allowRemote:!t},r=>r.AutoModel.from_pretrained(h,{config:{model_type:"custom"},dtype:"fp32",...V({threads:1})})),await b(!t,h,{modelsDir:v(),log:e,dispose:async()=>{await f?.dispose?.(),f=null}}),o="ready",c=null,w=null,e("[vad] ready — Silero VAD on levelled audio decides what is speech (the energy gate is the fallback)"),!0}catch(r){return c=r.message,w=null,o="error",e(`[vad] load failed (${r.message}) — the energy gate decides, as before`),!1}}function ne(e={}){if(g&&o!=="error")return g;o="loading";const n=typeof e.onLog=="function"?e.onLog:()=>{};return d=R({warmMs:e.warmMs,busy:A,log:n,unload:()=>W({log:n})}),g=j({log:n,allowDownload:e.allowDownload!==!1}).then(t=>(t&&!A()&&d?.arm(),t)),g}function X(e){if(!e.length)return 1;const n=[...e].sort((r,E)=>r-E),t=n[Math.floor(n.length*.9)]||0;return t>0?Math.min(I,Math.max(1,P/t)):1}function oe(){let e=null,n=0;const t=new Map,r=[],E=Math.ceil(90*D/i);async function T(l){let s=0;for(let u=0;u<l.length;u++)s+=l[u]*l[u];r.push(Math.sqrt(s/l.length)),r.length>B&&r.shift();const p=X(r),a=p===1?l:l.map(u=>u*p);if(_)return _(a);e||=new M.Tensor("float32",new Float32Array(256),[2,1,128]);const m=await f({input:new M.Tensor("float32",a,[1,i]),sr:new M.Tensor("int64",[BigInt(D)],[]),state:e});return e=m.stateN,Number(m.output.data[0])}return{async advance(l,s){if(!L())return!1;const p=s+l.length;n<s&&(n=Math.ceil(s/i)*i),y++;try{for(;n+i<=p;n+=i){const a=n-s;t.set(n/i,await T(l.slice(a,a+i)))}}catch{return!1}finally{y--}for(const a of t.keys()){if(t.size<=E)break;t.delete(a)}return!0},speechIn(l,s,p=N){let a=!1;for(let m=Math.floor(l/i);m*i<s;m++){const u=t.get(m);if(u!==void 0&&(a=!0,u>=p))return!0}return a?!1:null},_probs:t}}function re(){d?.disarm(),d=null,x=0,y=0,o="off",f=null,_=null,c=null,g=null,w=null}function le(e){_=e||null,o=e?"ready":"off"}export{h as DEFAULT_VAD_MODEL,i as FRAME,I as LEVEL_MAX_GAIN,P as LEVEL_TARGET,B as LEVEL_WINDOW,J as OFFSET,N as ONSET,D as SAMPLE_RATE,H as VAD_MODEL_APPROX_MB,re as _reset,le as _setForTest,oe as createStream,Z as health,ne as init,L as isReady,X as levelGain,G as modelOnDisk,Y as progress,te as release,ee as retain,Q as state,W as unload};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.137.1";export{o as VERSION};
1
+ const o="0.139.1";export{o as VERSION};