@chatpanel/gateway 0.117.0 → 0.118.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/stt-engine.js CHANGED
@@ -1 +1 @@
1
- import{join as Qe}from"node:path";import{deflateSync as Je}from"node:zlib";import ve from"node:os";import{existsSync as Ze,readdirSync as et}from"node:fs";import{randomUUID as tt}from"node:crypto";import{ensureLib as Ne,modelRoot as Oe}from"./ner-engine.js";import{runtimeDtype as ie,runtimeName as Pe,DTYPE_SUFFIX as nt}from"./model-runtime.js";import{verifyModelWeights as ot}from"./model-integrity.js";import{DEFAULT_STT_MODEL as Re,isEnglishOnly as me,sttModelDtype as he,isKnownSttModel as rt,sttModelEngine as z}from"./stt-models.js";import*as B from"./parakeet-engine.js";import*as _e from"./coreml-stt-engine.js";import*as ne from"./indic-engine.js";import*as U from"./diarize-engine.js";import*as Y from"./segment-engine.js";import{turnsFromSpans as lt,mainLocal as at,timeByLocal as st,audioOfLocal as it}from"@chatpanel/events/speaker-turns.js";import{diarizeApproxMB as ct}from"./diarize-models.js";import*as oe from"./translate-engine.js";import*as Z from"./indictrans-engine.js";import{rawOrtAvailable as ut}from"./ort.js";import*as R from"./vad-engine.js";import*as ee from"./echo-pair.js";import{mostlyEcho as ft}from"./aec-engine.js";import{pickSegmentLanguage as dt,detectTextLanguage as gt,needsTranslation as pt,localTranslatable as mt,normalizeLanguages as ht,normalizeLanguage as _t,decodeLanguages as wt,lineLanguage as yt,autoCandidates as Mt,AUTO_LEARN_CONFIDENCE as Tt,AUTO_LEARN_SECONDS as St,ANY_LANGUAGE_CONFIDENCE as Et,AUTO_LANGUAGES as Lt}from"@chatpanel/events/speech-language.js";import{makeWarmTimer as we}from"./warm-timer.js";const p=16e3,Fe=p,Ce=3*p,At=2,xt=new Set(["thank you","thanks","thank you for watching","thanks for watching","you","uh","um","hmm","hm","mm","amen","bye","okay","ok","yeah","oh","the","that","so","and","i","a","me","we","yes","no","thank you very much","subtitles by the amara.org community","you you"]);function bt(e,t){if(t>At*p)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?xt.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}const kt=12,ye=3;function Dt(e){const t=String(e||"").split(/\s+/).filter(Boolean);if(t.length<ye)return{text:String(e||"").trim(),removed:0,total:t.length};const n=l=>l.toLowerCase().replace(/[^\p{L}\p{N}']/gu,""),o=[];let r=0;for(let l=0;l<t.length;){let i=0,s=0;for(let a=1;a<=kt&&l+a*ye<=t.length;a++){let c=1;for(;l+(c+1)*a<=t.length&&t.slice(l+c*a,l+(c+1)*a).every((u,g)=>n(u)===n(t[l+g]));)c++;c>=ye&&(c-1)*a>i&&(i=(c-1)*a,s=a)}i?(o.push(...t.slice(l,l+s)),r+=i,l+=s+i):(o.push(t[l]),l++)}return{text:o.join(" "),removed:r,total:t.length}}const vt=.6,$e=2.4;function He(e){const t=Buffer.from(String(e||""),"utf8");return t.length<40?1:t.length/Je(t).length}function Nt(e){return String(e||"").replace(/([^\d\s]{1,8}?)\1{4,}/gu,"$1")}function Ot({cores:e=ve.availableParallelism?.()??ve.cpus().length,env:t=process.env}={}){const n=Number(t.CHATPANEL_STT_THREADS);return Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(4,Math.floor(e/2)))}function re(e){return{intraOpNumThreads:Ot(e),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}const Pt=.12,ze=.8,Ue=.15,Rt=.999,Ft=2.5;function ce(e={}){return(e.en??0)>=Ue?"en":Object.entries(e).sort((t,n)=>n[1]-t[1])[0]?.[0]||null}function Ct(e,t=[]){const n=[];return e.forEach((o,r)=>{const l=t[r]??o.lang,i=n[n.length-1];i&&i.lang===l?i.to=o.to:n.push({from:o.from,to:o.to,lang:l})}),n}function $t(e,{base:t=null,rate:n=p}={}){const o=e||[],r=a=>{const[c,u]=Object.entries(a.scores||{}).sort((g,A)=>A[1]-g[1])[0]||[];return c&&c!=="en"&&u>=Rt?c:null},l=new Array(o.length).fill(null);for(let a=0;a<o.length;){const c=r(o[a]);let u=a+1;if(c)for(;u<o.length&&r(o[u])===c;)u++;if(c&&(o[u-1].to-o[a].from)/n>=Ft)for(let g=a;g<u;g++)l[g]=c;a=u}const i=[];let s=t;return o.forEach((a,c)=>{l[c]?s=l[c]:s!=="en"&&(a.scores?.en??0)>=Ue&&(s="en");const u=i[i.length-1];u&&u.lang===s?u.to=a.to:i.push({from:a.from,to:a.to,lang:s})}),i}function Ht(e,t,{frame:n=Math.round(.03*p),minPause:o=Pt*p,minPiece:r=ze*p}={}){const l=[];let i=0,s=-1;for(let a=0;a+n<=e;a+=n){const c=t(a,a+n)===!1;if(c&&s<0&&(s=a),(!c||a+2*n>e)&&s>=0){const u=c?a+n:a,g=Math.round((s+u)/2);u-s>=o&&g-i>=r&&e-g>=r&&(l.push(g),i=g),s=-1}}return l}const zt=.12;function Ut(e,t=Math.round(.03*p)){const n=Math.floor(e.length/t);if(n<3)return 0;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=Q(e,r*t,(r+1)*t);return o.sort(),Math.max(1e-4,o[Math.floor(n*.9)]*zt)}let m="off",E=null,h=null,D=null,q=null,T=null,X=null,N=null;function Gt(e=E||Re,t=he(e)||ie()){if(z(e)==="parakeet-tdt")return B.parakeetOnDisk(e,B.parakeetDtype(t));if(z(e)==="coreml-tdt")return _e.coremlOnDisk(e);if(z(e)==="indic-canary")return ne.indicOnDisk();const n=Qe(Oe(),...e.split("/"),"onnx");if(!Ze(n))return!1;const o=nt[t]??"";try{const r=et(n);return r.includes(`encoder_model${o}.onnx`)&&r.some(l=>l===`decoder_model_merged${o}.onnx`||l===`decoder_model${o}.onnx`)}catch{return!1}}function An(){return m}function ue(){return m==="ready"&&!!h}function xn(){return T}function bn(){return{configured:m!=="off",ok:ue(),state:m,model:E,dtype:X,runtime:Pe(),error:D,warmMs:N?.warmMs??null,vad:R.state()}}function kn(){return!!N?.pending()}function le(){return C.size>0||m==="loading"||m==="downloading"}async function Me({log:e=()=>{}}={}){if(le())return!1;N?.disarm();const t=h;if(h=null,q=null,X=null,T=null,D=null,m="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((N?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function Ge(e){return e.then(t=>(t&&!le()&&N?.arm(),t))}async function je(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null,licenseAccepted:r=null}={}){if(z(e)==="parakeet-tdt")return jt(e,{log:t,allowDownload:n,dtype:o});if(z(e)==="coreml-tdt")return Xt(e,{log:t,allowDownload:n});if(z(e)==="indic-canary")return Kt(e,{log:t,allowDownload:n,licenseAccepted:r});const l=h,i=E;let s;try{s=await Ne()}catch(L){return m="error",D=`engine load failed: ${L.message}`,t(`[stt] transformers.js not available (${L.message}) — dictation falls back to the browser engine`),!1}const c=(o&&o!=="auto"?o:null)||he(e)||ie(),u=Gt(e,c);if(s.env.allowRemoteModels=u?!1:!!n,!u&&!n)return m="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const g=s.env.remoteHost,A=!rt(e);if(!u&&A)try{s.env.remoteHost="https://huggingface.co/"}catch{}m=u?"loading":"downloading",u||(T={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${A?", from Hugging Face":""})…`));try{const L=d=>{if(!d)return;const J=typeof d.progress=="number"?Math.round(d.progress):T?.pct??0;d.status==="progress"||d.status==="download"||d.status==="initiate"?T={model:e,file:d.file||T?.file||null,pct:J}:d.status==="done"&&d.file&&t(`[stt] fetched ${d.file}`)};let w;try{w=await s.pipeline("automatic-speech-recognition",e,{dtype:c,progress_callback:L,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:re()}})}catch(d){if(u||A||!n)throw d;t(`[stt] mirror fetch failed (${String(d.message).slice(0,80)}) — retrying from Hugging Face…`),s.env.remoteHost="https://huggingface.co/",s.env.allowRemoteModels=!0,w=await s.pipeline("automatic-speech-recognition",e,{dtype:c,progress_callback:L,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:re()}})}if(!u)try{ot(e,{modelsDir:Oe(),log:t})}catch(d){try{await w.dispose?.()}catch{}throw d}if(h=w,E=e,m="ready",D=null,T=null,X=c,l&&l!==w)try{await l.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${c} (in-process, offline) — local dictation active`),!0}catch(L){return D=L.message,T=null,l?(h=l,E=i,m="ready"):m="error",t(`[stt] model load failed (${L.message})${l?" — keeping previous model":""}`),!1}finally{try{s.env.remoteHost=g}catch{}}}async function jt(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null}={}){const r=h,l=E,i=B.parakeetDtype(o&&o!=="auto"?o:Bt()),s=B.parakeetOnDisk(e,i);if(!s&&!n)return m="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;m=s?"loading":"downloading",s||(T={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const a=await B.loadRecognizer({modelId:e,dtype:i,allowDownload:n,log:t,sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:re(),onProgress:u=>{T={model:e,file:u.file||null,pct:typeof u.pct=="number"?u.pct:T?.pct??0}}}),c=async u=>({text:await a.transcribe(u)});if(c.__transducer=!0,c.dispose=()=>a.dispose(),h=c,E=e,m="ready",D=null,T=null,X=i,r&&r!==c)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(a){return D=a.message,T=null,r?(h=r,E=l,m="ready"):m="error",t(`[stt] model load failed (${a.message})${r?" — keeping previous model":""}`),!1}}function Bt(){return B.PARAKEET_DEFAULT_DTYPE}const Be="fp16";async function Xt(e,{log:t=()=>{},allowDownload:n=!0}={}){const o=h,r=E,l=_e.coremlOnDisk(e);if(!l&&!n)return m="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;m=l?"loading":"downloading",l||(T={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let i=null;const s=await _e.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:a=>{T={model:e,file:a.file||null,pct:typeof a.pct=="number"?a.pct:T?.pct??0}},onExit:a=>{h===i&&(h=null,q=null,m="error",D=a,N?.disarm(),t(`[stt] ${a} — reloads on the next dictation`))}});if(i=async a=>({text:await s.transcribe(a)}),i.__transducer=!0,i.dispose=()=>s.dispose(),h=i,E=e,m="ready",D=null,T=null,X=Be,o&&o!==i)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} (Core ML on the Neural Engine, helper ${s.version}, windows ${s.windows.join("/")} s, offline) — local dictation active`),!0}catch(i){return D=i.message,T=null,o?(h=o,E=r,m="ready"):m="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}async function Kt(e,{log:t=()=>{},allowDownload:n=!0,licenseAccepted:o=null}={}){const r=h,l=E,i=ne.indicOnDisk();if(!i&&!n)return m="error",D="model not on disk and downloads disabled",!1;m=i?"loading":"downloading",i||(T={model:e,file:null,pct:0},t(`[stt] downloading ${e} (one-time, ~1.5 GB, from Hugging Face)…`));try{i||await ne.ensureIndicFiles({licenseAccepted:o,log:t,onProgress:c=>{T={model:e,file:c.file,pct:c.pct}}});const s=await ne.loadRecognizer({sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:re(),log:t}),a=async(c,u={})=>s.transcribe(c,u);if(a.identify=(c,u)=>s.identify(c,u),a.__transducer=!0,a.__indic=!0,a.dispose=()=>s.dispose(),h=a,E=e,m="ready",D=null,T=null,X="int8",r&&r!==a)try{await r.dispose?.()}catch{}return t(`[stt] ready — ${e} (Indic-Transcribe, int8, in-process, offline) — ${ne.INDIC_LICENSE.attribution}`),!0}catch(s){return D=s.message,T=null,r?(h=r,E=l,m="ready"):m="error",t(`[stt] model load failed (${s.message})${r?" — keeping previous model":""}`),!1}}const Wt=30;function Xe({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:o=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof o=="number"&&o<=Wt||e==="download"?{allowDownload:!0}:null}function Te(e,{log:t=()=>{},warmMs:n,allowDownload:o=!0}={}){const r=Xe({mode:e,onDisk:U.modelOnDisk(),ready:U.isReady(),approxMB:ct(U.activeModel())});if(r&&U.init({allowDownload:r.allowDownload&&o!==!1,warmMs:n,onLog:t}),e==="off"||Se)return;const l=Xe({mode:e,onDisk:Y.modelOnDisk(),ready:Y.isReady(),approxMB:Y.SEGMENT_MODEL_APPROX_MB});l&&Y.init({allowDownload:l.allowDownload&&o!==!1,warmMs:n,onLog:t})}let Se=!1,Ee=null;function Le(e={},{log:t=()=>{}}={}){e.vad!==!1&&(Ee={vad:e.vad,allowDownload:e.allowDownload,warmMs:e.warmMs},(R.state()==="off"||R.state()==="error")&&R.init({allowDownload:e.allowDownload!==!1,warmMs:e.warmMs,onLog:t}))}function Dn(e={}){if(q&&m!=="error")return q;const t=typeof e.onLog=="function"?e.onLog:()=>{};return E=e.model||Re,Se=e.segment===!1,m="loading",N=we({warmMs:e.warmMs,busy:le,log:t,unload:()=>Me({log:t})}),q=Ge(je(E,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype,licenseAccepted:e.licenseAccepted||null})).then(n=>(n&&(Te(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),Le(e,{log:t})),n)),q}async function vn(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(Se=t.segment===!1);const o=z(e)==="parakeet-tdt"?B.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:B.PARAKEET_DEFAULT_DTYPE):z(e)==="coreml-tdt"?Be:z(e)==="indic-canary"?"int8":t.dtype&&t.dtype!=="auto"?t.dtype:he(e)||ie();if(e===E&&ue()&&X===o)return Te(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;N??=we({warmMs:t.warmMs,busy:le,log:n,unload:()=>Me({log:n})});const r=await Ge(je(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype,licenseAccepted:t.licenseAccepted||null}));return r&&(Te(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),Le(t,{log:n})),r}const Yt=8,qt=12e4,It=6e4,Vt=1200,fe=12,Ae=700,xe=.008,Qt=.002,Jt=4;function Zt(e){return e>0?Math.min(xe,Math.max(Qt,e*Jt)):xe}function en(e){const t=Math.round(.1*p),n=Math.floor(e.length/t);if(n<5)return null;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=Q(e,r*t,(r+1)*t);return o.sort(),o[Math.floor(n*.1)]}const Ke=30,tn=15e3,C=new Map,I=new Map;let V=Promise.resolve();function Nn(){return C.size}const nn=300,on=3e3;function rn(e){const t=Number(e);return Number.isFinite(t)?Math.min(on,Math.max(nn,Math.round(t))):Ae}function On({lang:e,langs:t=null,translateTo:n=null,translateLoad:o=null,echo:r=null,redact:l=!1,diarize:i=!1,speakerLabel:s=null,endSilenceMs:a=Ae,interims:c=!0,remote:u=null,poll:g=!1}={}){if(C.size>=Yt){const d=new Error("too many concurrent dictation sessions");throw d.code="too_many_sessions",d}const A=Array.isArray(t)?ht(t):null,L=typeof e=="string"&&e?e.slice(0,12):null,w={id:tt(),endSilenceMs:rn(a),lang:A?A.length===1?A[0]:A.length?null:L:L,langs:A,lastLang:null,lastDecoded:null,learned:new Set,translateTo:_t(n)||null,translateLoad:o||{},translations:Promise.resolve(),echo:r&&typeof r=="object"?ee.join(r.group,r.role):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!l,diarize:!!i,speakerLabel:typeof s=="string"&&s?s.slice(0,40):null,diarizer:i?new U.Diarizer:null,remote:u||null,interims:c!==!1&&!u,chunks:[],samples:0,listeners:new Set,poll:g?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return C.set(w.id,w),N?.disarm(),w.diarizer&&(U.retain(),Y.retain()),w.translateTo&&(oe.retain(),Z.retain()),R.retain(),Ee&&(R.state()==="off"||R.state()==="error")&&Le(Ee),We(w),{id:w.id}}function de(e){return C.get(String(e||""))||null}function Pn(e,t){const n=de(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function K(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function Rn(e){const t=String(e||""),n=C.get(t);if(n)return n.poll?n.poll.splice(0):null;const o=I.get(t);return o?(clearTimeout(o.timer),I.delete(t),o.session.poll.splice(0)):null}function Fn(e){return I.get(String(e||""))?.session||null}function We(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>cn(e.id).catch(()=>{}),It),e.idleTimer.unref?.()}function Cn(e,t){const n=de(e);if(!n||n.closed){const o=new Error("no such session");throw o.code="no_session",o}if(!(!(t instanceof Float32Array)||!t.length)){if(We(n),n.echo?.role==="mic"){ee.pushMic(n.echo,t),Ye(n);return}n.echo?.role==="reference"&&ee.pushReference(n.echo,t),n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,Ye(n)}}function $n(e){const t=de(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),V=V.then(()=>be(t).catch(()=>{})),V)}function Hn(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let o=0;o<n.length;o++)n[o]=e.readFloatLE(o*4);return n}function Ye(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+Vt-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,V=V.then(()=>be(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function qe(e){const t=new Float32Array(e.samples);let n=0;for(const o of e.chunks)t.set(o,n),n+=o.length;return t}function ln(e,t,n){const o=p/100,r=Math.max(0,e.length-t),l=Math.floor((e.length-r)/o),i=Math.max(1,Math.round(n/o));if(l<=i)return 0;const s=new Float32Array(l);for(let g=0;g<l;g++){let A=0;const L=r+g*o;for(let w=0;w<o;w++)A+=e[L+w]*e[L+w];s[g]=A/o}let a=-1,c=1/0,u=0;for(let g=0;g<i;g++)u+=s[g];for(let g=0;g+i<=l;g++)g>0&&(u+=s[g+i-1]-s[g-1]),u<c&&(c=u,a=g);return a<0?0:r+Math.round((a+i/2)*o)}function Q(e,t=0,n=e.length){let o=0;const r=Math.max(1,n-t);for(let l=t;l<n;l++)o+=e[l]*e[l];return Math.sqrt(o/r)}function an(e,t=xe){const n=Math.round(.02*p);let o=0,r=e.length;for(let l=0;l+n<=e.length;l+=n)if(Q(e,l,l+n)>=t){o=l;break}for(let l=e.length-n;l>=0;l-=n)if(Q(e,l,l+n)>=t){r=l+n;break}return r>o?e.subarray(o,r):e}async function Ie(e){try{const t=await Ne(),n=h?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const o=e.length>p*8?e.subarray(0,p*8):e,r=await h.processor(o),l=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),i=await h.model({...r,decoder_input_ids:l}),s={};for(const[a,c]of Object.entries(n.lang_to_id))s[a.slice(2,-2)]=Number(i.logits.data[c]);return s}catch{return null}}async function sn(e){const t=await Ie(e);if(!t)return null;let n=null,o=-1/0;for(const[r,l]of Object.entries(t))l>o&&(o=l,n=r);return n}async function be(e,{flush:t=!1}={}){if(e.closed&&!t)return;if(e.echo?.role==="mic"){const f=await ee.drain(e.echo,{force:t});f.length&&(e.chunks.push(f),e.samples+=f.length,e.pushed+=f.length)}if(!e.remote&&!ue()||!e.samples)return;e.lastDecodeAt=Date.now();let n=qe(e);const o=n.length,r=Math.max(0,(e.pushed||0)-e.samples),l=Math.round((e.endSilenceMs||Ae)/1e3*p),i=en(n);i!==null&&(e.noiseFloor==null||i<e.noiseFloor)&&(e.noiseFloor=i);const s=Zt(e.noiseFloor);let a=null,c=null;R.isReady()&&(e.vad||=R.createStream(),await e.vad.advance(n,r)&&(a=e.vad.speechIn(r,r+n.length,R.ONSET),n.length>l&&(c=e.vad.speechIn(r+n.length-l,r+n.length,R.OFFSET))));const u=n.length>l&&(c!==null?!c:Q(n,n.length-l)<s);if(a===!1||a===null&&Q(n)<s){n.length>p*5&&(e.chunks=[n.subarray(n.length-p)],e.samples=p);return}if(!e.interims&&!t&&!u&&n.length<fe*p)return;let g=null;if(!t&&!u&&o>=fe*p&&o<Ke*p){const f=ln(n,3*p,Math.round(.2*p));f>0&&f<n.length&&(g=n.subarray(f),n=n.subarray(0,f))}const A=!e.remote&&!me(E)&&!h?.__transducer;if(A&&!e.langs&&!e.lang&&!e.langTried&&n.length>=p){e.langTried=!0;const f=await sn(n);f&&(e.lang=f,K(e,{type:"language",lang:f}))}const L=t||u||o>=fe*p;let w=e.lang;if(A&&e.langs&&!e.lang){const f=e.langs.length>0,O=f?wt(e.langs):Mt([...e.learned]);if(O.length===1)w=O[0];else if(w=O.includes(e.lastDecoded)?e.lastDecoded:null,(L||!w)&&n.length>=p/2){const b=await Ie(n);if(b){const M=dt({scores:b,allowed:O,seconds:n.length/p,last:e.lastDecoded});w=!f&&!M.inherited&&M.confidence<Et?e.lastDecoded||"en":M.lang,!f&&L&&!M.inherited&&M.confidence>=Tt&&n.length>=St*p&&e.learned.add(M.lang)}}L&&w&&(e.lastDecoded=w)}let d="",J=null,$=null,ge=null;try{if(e.remote){const f=await e.remote.transcribe(n,{lang:e.lang,langs:e.langs});d=f.text,ge=f.lang||null}else{const f=h.__indic?e.langs?.length?{langs:[...new Set([...e.langs,"en"])],last:e.lastLang,choose:ce}:e.lang?{lang:e.lang}:{langs:[...Lt],last:e.lastLang,choose:ce}:me(E)?{}:{language:w||void 0,task:"transcribe"},O=h.__indic&&h.identify&&L&&f.langs&&n.length>=2*ze*p?Ht(n.length,(M=>(_,v)=>Q(n,_,v)>=M)(Ut(n))):[];let b=null;if(O.length){const M=await h.identify(n,{langs:f.langs}),_=[0,...O,n.length],v=[];for(let k=0;k+1<_.length;k++){const S=await h.identify(n.subarray(_[k],_[k+1]),{langs:f.langs});v.push({from:_[k],to:_[k+1],scores:S?.scores||{}})}if(b=$t(v,{base:M?.scores?ce(M.scores):null}),b.length>1){const k=[];for(let S=0;S<b.length;S++){const G=b[S],te=G.lang&&G.lang!=="en"&&(b[S-1]?.lang==="en"||b[S+1]?.lang==="en");k.push(te?ce((await h.identify(n.subarray(G.from,G.to),{langs:f.langs}))?.scores||{}):G.lang)}b=Ct(b,k)}b.length<2&&(b=null)}if(b){$=[];for(const _ of b){const v=await h(n.subarray(_.from,_.to),_.lang?{lang:_.lang}:{...f}),k=String(v?.text||"").trim(),S=v?.lang||_.lang||null;k&&$.push({text:k,lang:S,from:_.from,to:_.to}),S&&(f.last=S)}d=$.map(_=>_.text).join(" ");const M=new Map;for(const _ of $)_.lang&&M.set(_.lang,(M.get(_.lang)||0)+(_.to-_.from));J=[...M].sort((_,v)=>v[1]-_[1])[0]?.[0]||null,($.length<2||M.size<2)&&($=null)}else{const M=await h(n,f);d=String(M?.text||"").trim(),h.__indic&&(J=M?.lang||null)}}}catch(f){K(e,{type:"error",code:"decode_failed",message:f.message,fatal:!1});return}if(!d)return;{const f=Dt(d);if(f.removed&&f.removed/f.total>=vt&&f.total>=12?d="":d=f.text,d&&He(d)>$e){const O=Nt(d);d=O.replace(/[\s\p{P}]/gu,"").length<12||He(O)>$e?"":O}if(!d)return}const Ve=o>=fe*p,ke=o>=Ke*p;if(t||u||Ve||ke){const f=t?"flush":u?"silence":ke?"overflow":"length",O=f==="flush"||f==="silence",b=e.samples-o,M=[];g&&M.push(g),b>0&&M.push(qe(e).subarray(o)),e.chunks=M,e.samples=M.reduce((y,x)=>y+x.length,0),e.lastInterim="";const _=an(n,s);if(bt(d,_?_.length:0)||e.echo?.role==="mic"&&ft(ee.verdict(e.echo,r,r+n.length)))return;let v=null,k=null;if(e.diarizer)try{const y=e.speakerLabel?null:await Y.spans(n),x=y?lt(y):[];if(x.length){const P=new Map;for(const{local:F}of st(x)){const H=it(n,x,F),ae=H.length?await U.embed(H):null,se=H.length<Fe,W=H.length<Ce;P.set(F,e.diarizer.assign(ae,{pinnedLabel:null,weak:se,thin:W}))}const j=Math.round(r/p*1e3);k=x.map(F=>({startMs:j+Math.round(F.start*1e3),durationMs:Math.round((F.end-F.start)*1e3),speaker:P.get(F.local)})).filter(F=>F.speaker),v=P.get(at(x))||null}}catch{}if(e.diarizer&&!v)try{const y=_,x=y?await U.embed(y):null,P=!!y&&y.length<Fe,j=!!y&&y.length<Ce;v=e.diarizer.assign(x,{pinnedLabel:e.speakerLabel,weak:P,thin:j})}catch{}let S=null;(e.langs||e.translateTo)&&(J?S=J:ge?S=ge:me(E)&&!e.remote?S="en":A?S=yt(d,w||e.lang)||null:S=e.lang||gt(d,{allowed:e.langs||[],last:e.lastLang}).lang,S&&S!==e.lastLang&&(e.lastLang=S,K(e,{type:"language",lang:S})));const G=Math.round(r/p*1e3),te=$&&(e.langs||e.translateTo)?$.map((y,x)=>({text:y.text,lang:y.lang,startMs:G+Math.round(y.from/p*1e3),durationMs:Math.round((y.to-y.from)/p*1e3),last:x===$.length-1})):[{text:d,lang:S,startMs:G,durationMs:Math.round(n.length/p*1e3),last:!0}];for(const y of te){te.length>1&&y.lang&&y.lang!==e.lastLang&&(e.lastLang=y.lang,K(e,{type:"language",lang:y.lang}));const{text:x,lang:P,startMs:j}=y,F=(x.match(new RegExp("\\p{Script=Latin}","gu"))||[]).length/Math.max(1,(x.match(new RegExp("\\p{L}","gu"))||[]).length),H=Z.indictransLanguage(P)&&F<.5&&Z.state()!=="error"&&ut(),ae=!!e.translateTo&&pt(P,e.translateTo)&&(H||mt(x,P)&&oe.state()!=="error"),se=te.length>1&&k?k.filter(W=>W.startMs<j+y.durationMs&&W.startMs+W.durationMs>j):k;if(K(e,{type:"final",text:x,reason:f,endOfTurn:y.last?O:!1,durationMs:y.durationMs,startMs:j,...P?{lang:P}:{},...ae?{translating:!0}:{},...v?{speaker:v}:{},...se?.length?{turns:se}:{}}),ae){const W=e.translateTo,pe=H?Z:oe;pe.state()==="off"&&pe.init({...e.translateLoad,...H?{sessionOptions:re()}:{}}),e.translations=e.translations.then(async()=>{await pe.ready();const De=H?await Z.translate(x,P):await oe.translate(x);K(e,{type:"translation",startMs:j,lang:P,to:W,text:De||null,...De?{}:{failed:!0}})}).catch(()=>{})}}}else d!==e.lastInterim&&(e.lastInterim=d,K(e,{type:"interim",text:d}))}async function cn(e){const t=de(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(V=V.then(()=>be(t,{flush:!0}).catch(()=>{}))),await Promise.race([t.translations,new Promise(n=>setTimeout(n,tn).unref?.())])}finally{if(K(t,{type:"end"}),t.listeners.clear(),C.delete(t.id),t.poll){const n=setTimeout(()=>I.delete(t.id),qt);n.unref?.(),I.set(t.id,{session:t,timer:n})}t.diarizer&&(U.release(),Y.release()),t.translateTo&&(oe.release(),Z.release()),R.release(),ee.leave(t.echo),C.size===0&&ue()&&N?.arm()}return!0}function zn(){for(const e of C.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);C.clear();for(const e of I.values())clearTimeout(e.timer);I.clear(),N?.disarm(),N=null,m="off",E=null,h=null,D=null,q=null,T=null}function Un(e,t="test/fake",{warmMs:n=null,dtype:o=null}={}){h=e,E=t,m=e?"ready":"off",X=o,n!==null&&(N=we({warmMs:n,busy:le,unload:()=>Me()}),e&&N.arm())}export{Wt as AUTO_FETCH_MAX_MB,$e as COMPRESSION_LIMIT,Rt as FROM_ENGLISH,Ft as FROM_ENGLISH_RUN_S,vt as LOOP_DROP,zt as PAUSE_SHARE,ze as PIECE_MIN_S,Pt as PIECE_PAUSE_S,p as SAMPLE_RATE,Ce as THIN_SPEAKER_SAMPLES,Ue as TO_ENGLISH,Fe as WEAK_SPEAKER_SAMPLES,zn as _reset,Un as _setPipeForTest,rn as clampEndSilence,Dt as collapseLoops,Nt as collapseRuns,He as compressionRatio,On as createSession,$n as decodeNow,Rn as drainEvents,cn as endSession,Fn as endedSession,de as getSession,bn as health,Dn as init,ue as isReady,$t as languageGroups,bt as looksHallucinated,Gt as modelOnDisk,en as noiseFloorOf,Ht as pauseCuts,Ut as pauseLevel,xn as progress,Cn as pushAudio,ln as quietestCut,Ct as relabelGroups,ie as runtimeDtype,Pe as runtimeName,ce as segmentLanguage,Nn as sessionCount,vn as setModel,Zt as silenceGate,Xe as speakerPlan,An as state,re as sttSessionOptions,Ot as sttThreads,Pn as subscribe,Hn as toFloat32,Me as unload,kn as warmPending};
1
+ import{join as Qe}from"node:path";import{deflateSync as Je}from"node:zlib";import ve from"node:os";import{existsSync as Ze,readdirSync as et}from"node:fs";import{randomUUID as tt}from"node:crypto";import{ensureLib as Ne,modelRoot as Oe}from"./ner-engine.js";import{runtimeDtype as ie,runtimeName as Pe,DTYPE_SUFFIX as nt}from"./model-runtime.js";import{verifyModelWeights as ot}from"./model-integrity.js";import{DEFAULT_STT_MODEL as Re,isEnglishOnly as me,sttModelDtype as he,isKnownSttModel as rt,sttModelEngine as G}from"./stt-models.js";import*as K from"./parakeet-engine.js";import*as _e from"./coreml-stt-engine.js";import*as ne 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 oe from"./translate-engine.js";import*as Z from"./indictrans-engine.js";import{rawOrtAvailable as ut}from"./ort.js";import*as R from"./vad-engine.js";import*as ee from"./echo-pair.js";import{mostlyEcho as ft}from"./aec-engine.js";import{pickSegmentLanguage as dt,detectTextLanguage as gt,needsTranslation as pt,localTranslatable as mt,normalizeLanguages as ht,normalizeLanguage as _t,decodeLanguages as wt,lineLanguage as yt,autoCandidates as Mt,AUTO_LEARN_CONFIDENCE as Tt,AUTO_LEARN_SECONDS as St,ANY_LANGUAGE_CONFIDENCE as Et,AUTO_LANGUAGES as Lt}from"@chatpanel/events/speech-language.js";import{makeWarmTimer as we}from"./warm-timer.js";const g=16e3,Fe=g,Ce=3*g,At=2,xt=new Set(["thank you","thanks","thank you for watching","thanks for watching","you","uh","um","hmm","hm","mm","amen","bye","okay","ok","yeah","oh","the","that","so","and","i","a","me","we","yes","no","thank you very much","subtitles by the amara.org community","you you"]);function kt(e,t){if(t>At*g)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?xt.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}const 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 i=0,s=0;for(let a=1;a<=bt&&l+a*ye<=t.length;a++){let c=1;for(;l+(c+1)*a<=t.length&&t.slice(l+c*a,l+(c+1)*a).every((u,p)=>n(u)===n(t[l+p]));)c++;c>=ye&&(c-1)*a>i&&(i=(c-1)*a,s=a)}i?(o.push(...t.slice(l,l+s)),r+=i,l+=s+i):(o.push(t[l]),l++)}return{text:o.join(" "),removed:r,total:t.length}}const vt=.6,$e=2.4;function He(e){const t=Buffer.from(String(e||""),"utf8");return t.length<40?1:t.length/Je(t).length}function Nt(e){return String(e||"").replace(/([^\d\s]{1,8}?)\1{4,}/gu,"$1")}function Ot({cores:e=ve.availableParallelism?.()??ve.cpus().length,env:t=process.env}={}){const n=Number(t.CHATPANEL_STT_THREADS);return Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(4,Math.floor(e/2)))}function re(e){return{intraOpNumThreads:Ot(e),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}const Pt=.12,ze=.8,Rt=.15,Ft=.5,Ct=1.2,Ue=(e,t)=>e>=Ft||e>=Rt&&!(t<Ct),$t=.999,Ht=2.5;function ce(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,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 Ut(e,{base:t=null,rate:n=g}={}){const o=e||[],r=a=>{const[c,u]=Object.entries(a.scores||{}).sort((p,v)=>v[1]-p[1])[0]||[];return c&&c!=="en"&&u>=$t?c:null},l=new Array(o.length).fill(null);for(let a=0;a<o.length;){const c=r(o[a]);let u=a+1;if(c)for(;u<o.length&&r(o[u])===c;)u++;if(c&&(o[u-1].to-o[a].from)/n>=Ht)for(let p=a;p<u;p++)l[p]=c;a=u}const i=[];let s=t;return o.forEach((a,c)=>{l[c]?s=l[c]:s!=="en"&&Ue(a.scores?.en??0,(a.to-a.from)/n)&&(s="en");const u=i[i.length-1];u&&u.lang===s?u.to=a.to:i.push({from:a.from,to:a.to,lang:s})}),i}function Gt(e,t,{frame:n=Math.round(.03*g),minPause:o=Pt*g,minPiece:r=ze*g}={}){const l=[];let i=0,s=-1;for(let a=0;a+n<=e;a+=n){const c=t(a,a+n)===!1;if(c&&s<0&&(s=a),(!c||a+2*n>e)&&s>=0){const u=c?a+n:a,p=Math.round((s+u)/2);u-s>=o&&p-i>=r&&e-p>=r&&(l.push(p),i=p),s=-1}}return l}const jt=.12;function Bt(e,t=Math.round(.03*g)){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)]*jt)}let m="off",L=null,h=null,b=null,q=null,M=null,W=null,N=null;function Kt(e=L||Re,t=he(e)||ie()){if(G(e)==="parakeet-tdt")return K.parakeetOnDisk(e,K.parakeetDtype(t));if(G(e)==="coreml-tdt")return _e.coremlOnDisk(e);if(G(e)==="indic-canary")return ne.indicOnDisk();const n=Qe(Oe(),...e.split("/"),"onnx");if(!Ze(n))return!1;const o=nt[t]??"";try{const r=et(n);return r.includes(`encoder_model${o}.onnx`)&&r.some(l=>l===`decoder_model_merged${o}.onnx`||l===`decoder_model${o}.onnx`)}catch{return!1}}function bn(){return m}function ue(){return m==="ready"&&!!h}function Dn(){return M}function vn(){return{configured:m!=="off",ok:ue(),state:m,model:L,dtype:W,runtime:Pe(),error:b,warmMs:N?.warmMs??null,vad:R.state()}}function Nn(){return!!N?.pending()}function le(){return $.size>0||m==="loading"||m==="downloading"}async function Me({log:e=()=>{}}={}){if(le())return!1;N?.disarm();const t=h;if(h=null,q=null,W=null,M=null,b=null,m="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((N?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function Ge(e){return e.then(t=>(t&&!le()&&N?.arm(),t))}async function je(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null,licenseAccepted:r=null}={}){if(G(e)==="parakeet-tdt")return Wt(e,{log:t,allowDownload:n,dtype:o});if(G(e)==="coreml-tdt")return It(e,{log:t,allowDownload:n});if(G(e)==="indic-canary")return Yt(e,{log:t,allowDownload:n,licenseAccepted:r});const l=h,i=L;let s;try{s=await Ne()}catch(T){return m="error",b=`engine load failed: ${T.message}`,t(`[stt] transformers.js not available (${T.message}) — dictation falls back to the browser engine`),!1}const c=(o&&o!=="auto"?o:null)||he(e)||ie(),u=Kt(e,c);if(s.env.allowRemoteModels=u?!1:!!n,!u&&!n)return m="error",b="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const p=s.env.remoteHost,v=!rt(e);if(!u&&v)try{s.env.remoteHost="https://huggingface.co/"}catch{}m=u?"loading":"downloading",u||(M={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${v?", from Hugging Face":""})…`));try{const T=f=>{if(!f)return;const H=typeof f.progress=="number"?Math.round(f.progress):M?.pct??0;f.status==="progress"||f.status==="download"||f.status==="initiate"?M={model:e,file:f.file||M?.file||null,pct:H}:f.status==="done"&&f.file&&t(`[stt] fetched ${f.file}`)};let S;try{S=await s.pipeline("automatic-speech-recognition",e,{dtype:c,progress_callback:T,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:re()}})}catch(f){if(u||v||!n)throw f;t(`[stt] mirror fetch failed (${String(f.message).slice(0,80)}) — retrying from Hugging Face…`),s.env.remoteHost="https://huggingface.co/",s.env.allowRemoteModels=!0,S=await s.pipeline("automatic-speech-recognition",e,{dtype:c,progress_callback:T,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:re()}})}if(!u)try{ot(e,{modelsDir:Oe(),log:t})}catch(f){try{await S.dispose?.()}catch{}throw f}if(h=S,L=e,m="ready",b=null,M=null,W=c,l&&l!==S)try{await l.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${c} (in-process, offline) — local dictation active`),!0}catch(T){return b=T.message,M=null,l?(h=l,L=i,m="ready"):m="error",t(`[stt] model load failed (${T.message})${l?" — keeping previous model":""}`),!1}finally{try{s.env.remoteHost=p}catch{}}}async function Wt(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null}={}){const r=h,l=L,i=K.parakeetDtype(o&&o!=="auto"?o:Xt()),s=K.parakeetOnDisk(e,i);if(!s&&!n)return m="error",b="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;m=s?"loading":"downloading",s||(M={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const a=await K.loadRecognizer({modelId:e,dtype:i,allowDownload:n,log:t,sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:re(),onProgress:u=>{M={model:e,file:u.file||null,pct:typeof u.pct=="number"?u.pct:M?.pct??0}}}),c=async u=>({text:await a.transcribe(u)});if(c.__transducer=!0,c.dispose=()=>a.dispose(),h=c,L=e,m="ready",b=null,M=null,W=i,r&&r!==c)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(a){return b=a.message,M=null,r?(h=r,L=l,m="ready"):m="error",t(`[stt] model load failed (${a.message})${r?" — keeping previous model":""}`),!1}}function Xt(){return K.PARAKEET_DEFAULT_DTYPE}const Be="fp16";async function It(e,{log:t=()=>{},allowDownload:n=!0}={}){const o=h,r=L,l=_e.coremlOnDisk(e);if(!l&&!n)return m="error",b="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;m=l?"loading":"downloading",l||(M={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let i=null;const s=await _e.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:a=>{M={model:e,file:a.file||null,pct:typeof a.pct=="number"?a.pct:M?.pct??0}},onExit:a=>{h===i&&(h=null,q=null,m="error",b=a,N?.disarm(),t(`[stt] ${a} — reloads on the next dictation`))}});if(i=async a=>({text:await s.transcribe(a)}),i.__transducer=!0,i.dispose=()=>s.dispose(),h=i,L=e,m="ready",b=null,M=null,W=Be,o&&o!==i)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} (Core ML on the Neural Engine, helper ${s.version}, windows ${s.windows.join("/")} s, offline) — local dictation active`),!0}catch(i){return b=i.message,M=null,o?(h=o,L=r,m="ready"):m="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}async function Yt(e,{log:t=()=>{},allowDownload:n=!0,licenseAccepted:o=null}={}){const r=h,l=L,i=ne.indicOnDisk();if(!i&&!n)return m="error",b="model not on disk and downloads disabled",!1;m=i?"loading":"downloading",i||(M={model:e,file:null,pct:0},t(`[stt] downloading ${e} (one-time, ~1.5 GB, from Hugging Face)…`));try{i||await ne.ensureIndicFiles({licenseAccepted:o,log:t,onProgress:c=>{M={model:e,file:c.file,pct:c.pct}}});const s=await ne.loadRecognizer({sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:re(),log:t}),a=async(c,u={})=>s.transcribe(c,u);if(a.identify=(c,u)=>s.identify(c,u),a.__transducer=!0,a.__indic=!0,a.dispose=()=>s.dispose(),h=a,L=e,m="ready",b=null,M=null,W="int8",r&&r!==a)try{await r.dispose?.()}catch{}return t(`[stt] ready — ${e} (Indic-Transcribe, int8, in-process, offline) — ${ne.INDIC_LICENSE.attribution}`),!0}catch(s){return b=s.message,M=null,r?(h=r,L=l,m="ready"):m="error",t(`[stt] model load failed (${s.message})${r?" — keeping previous model":""}`),!1}}const qt=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<=qt||e==="download"?{allowDownload:!0}:null}function Te(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"||Se)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 Se=!1,Ee=null;function Le(e={},{log:t=()=>{}}={}){e.vad!==!1&&(Ee={vad:e.vad,allowDownload:e.allowDownload,warmMs:e.warmMs},(R.state()==="off"||R.state()==="error")&&R.init({allowDownload:e.allowDownload!==!1,warmMs:e.warmMs,onLog:t}))}function On(e={}){if(q&&m!=="error")return q;const t=typeof e.onLog=="function"?e.onLog:()=>{};return L=e.model||Re,Se=e.segment===!1,m="loading",N=we({warmMs:e.warmMs,busy:le,log:t,unload:()=>Me({log:t})}),q=Ge(je(L,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype,licenseAccepted:e.licenseAccepted||null})).then(n=>(n&&(Te(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),Le(e,{log:t})),n)),q}async function Pn(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"?K.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:K.PARAKEET_DEFAULT_DTYPE):G(e)==="coreml-tdt"?Be:G(e)==="indic-canary"?"int8":t.dtype&&t.dtype!=="auto"?t.dtype:he(e)||ie();if(e===L&&ue()&&W===o)return Te(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;N??=we({warmMs:t.warmMs,busy:le,log:n,unload:()=>Me({log:n})});const r=await Ge(je(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype,licenseAccepted:t.licenseAccepted||null}));return r&&(Te(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),Le(t,{log:n})),r}const Vt=8,Qt=12e4,Jt=6e4,Zt=1200,fe=12,Ae=700,xe=.008,en=.002,tn=4;function nn(e){return e>0?Math.min(xe,Math.max(en,e*tn)):xe}function on(e){const t=Math.round(.1*g),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,rn=15e3,$=new Map,V=new Map;let Q=Promise.resolve();function Rn(){return $.size}const ln=300,an=3e3;function sn(e){const t=Number(e);return Number.isFinite(t)?Math.min(an,Math.max(ln,Math.round(t))):Ae}function Fn({lang:e,langs:t=null,translateTo:n=null,translateLoad:o=null,echo:r=null,redact:l=!1,diarize:i=!1,speakerLabel:s=null,endSilenceMs:a=Ae,interims:c=!0,remote:u=null,poll:p=!1,format:v="f32"}={}){if($.size>=Vt){const H=new Error("too many concurrent dictation sessions");throw H.code="too_many_sessions",H}const T=Array.isArray(t)?ht(t):null,S=typeof e=="string"&&e?e.slice(0,12):null,f={id:tt(),format:v==="pcm16"?"pcm16":"f32",endSilenceMs:sn(a),lang:T?T.length===1?T[0]:T.length?null:S:S,langs:T,lastLang:null,lastDecoded:null,learned:new Set,translateTo:_t(n)||null,translateLoad:o||{},translations:Promise.resolve(),echo:r&&typeof r=="object"?ee.join(r.group,r.role):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!l,diarize:!!i,speakerLabel:typeof s=="string"&&s?s.slice(0,40):null,diarizer:i?new j.Diarizer:null,remote:u||null,interims:c!==!1&&!u,chunks:[],samples:0,listeners:new Set,poll:p?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return $.set(f.id,f),N?.disarm(),f.diarizer&&(j.retain(),Y.retain()),f.translateTo&&(oe.retain(),Z.retain()),R.retain(),Ee&&(R.state()==="off"||R.state()==="error")&&Le(Ee),Xe(f),{id:f.id}}function de(e){return $.get(String(e||""))||null}function Cn(e,t){const n=de(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function X(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function $n(e){const t=String(e||""),n=$.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(()=>dn(e.id).catch(()=>{}),Jt),e.idleTimer.unref?.()}function zn(e,t){const n=de(e);if(!n||n.closed){const o=new Error("no such session");throw o.code="no_session",o}if(!(!(t instanceof Float32Array)||!t.length)){if(Xe(n),n.echo?.role==="mic"){ee.pushMic(n.echo,t),Ie(n);return}n.echo?.role==="reference"&&ee.pushReference(n.echo,t),n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,Ie(n)}}function Un(e){const t=de(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),Q=Q.then(()=>ke(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 Ie(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+Zt-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,Q=Q.then(()=>ke(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}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 cn(e,t,n){const o=g/100,r=Math.max(0,e.length-t),l=Math.floor((e.length-r)/o),i=Math.max(1,Math.round(n/o));if(l<=i)return 0;const s=new Float32Array(l);for(let p=0;p<l;p++){let v=0;const T=r+p*o;for(let S=0;S<o;S++)v+=e[T+S]*e[T+S];s[p]=v/o}let a=-1,c=1/0,u=0;for(let p=0;p<i;p++)u+=s[p];for(let p=0;p+i<=l;p++)p>0&&(u+=s[p+i-1]-s[p-1]),u<c&&(c=u,a=p);return a<0?0:r+Math.round((a+i/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 un(e,t=xe){const n=Math.round(.02*g);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=h?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const o=e.length>g*8?e.subarray(0,g*8):e,r=await h.processor(o),l=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),i=await h.model({...r,decoder_input_ids:l}),s={};for(const[a,c]of Object.entries(n.lang_to_id))s[a.slice(2,-2)]=Number(i.logits.data[c]);return s}catch{return null}}async function fn(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 d=await ee.drain(e.echo,{force:t});d.length&&(e.chunks.push(d),e.samples+=d.length,e.pushed+=d.length)}if(!e.remote&&!ue()||!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||Ae)/1e3*g),i=on(n);i!==null&&(e.noiseFloor==null||i<e.noiseFloor)&&(e.noiseFloor=i);const s=nn(e.noiseFloor);let a=null,c=null;R.isReady()&&(e.vad||=R.createStream(),await e.vad.advance(n,r)&&(a=e.vad.speechIn(r,r+n.length,R.ONSET),n.length>l&&(c=e.vad.speechIn(r+n.length-l,r+n.length,R.OFFSET))));const u=n.length>l&&(c!==null?!c:J(n,n.length-l)<s);if(a===!1||a===null&&J(n)<s){n.length>g*5&&(e.chunks=[n.subarray(n.length-g)],e.samples=g);return}if(!e.interims&&!t&&!u&&n.length<fe*g)return;let p=null;if(!t&&!u&&o>=fe*g&&o<We*g){const d=cn(n,3*g,Math.round(.2*g));d>0&&d<n.length&&(p=n.subarray(d),n=n.subarray(0,d))}const v=!e.remote&&!me(L)&&!h?.__transducer;if(v&&!e.langs&&!e.lang&&!e.langTried&&n.length>=g){e.langTried=!0;const d=await fn(n);d&&(e.lang=d,X(e,{type:"language",lang:d}))}const T=t||u||o>=fe*g;let S=e.lang;if(v&&e.langs&&!e.lang){const d=e.langs.length>0,O=d?wt(e.langs):Mt([...e.learned]);if(O.length===1)S=O[0];else if(S=O.includes(e.lastDecoded)?e.lastDecoded:null,(T||!S)&&n.length>=g/2){const x=await qe(n);if(x){const y=dt({scores:x,allowed:O,seconds:n.length/g,last:e.lastDecoded});S=!d&&!y.inherited&&y.confidence<Et?e.lastDecoded||"en":y.lang,!d&&T&&!y.inherited&&y.confidence>=Tt&&n.length>=St*g&&e.learned.add(y.lang)}}T&&S&&(e.lastDecoded=S)}let f="",H=null,z=null,ge=null;try{if(e.remote){const d=await e.remote.transcribe(n,{lang:e.lang,langs:e.langs});f=d.text,ge=d.lang||null}else{const d=h.__indic?e.langs?.length?{langs:[...new Set([...e.langs,"en"])],last:e.lastLang,choose:ce}:e.lang?{lang:e.lang}:{langs:[...Lt],last:e.lastLang,choose:ce}:me(L)?{}:{language:S||void 0,task:"transcribe"},O=h.__indic&&h.identify&&T&&d.langs&&n.length>=2*ze*g?Gt(n.length,(y=>(_,D)=>J(n,_,D)>=y)(Bt(n))):[];let x=null;if(O.length){const y=await h.identify(n,{langs:d.langs}),_=[0,...O,n.length],D=[];for(let k=0;k+1<_.length;k++){const E=await h.identify(n.subarray(_[k],_[k+1]),{langs:d.langs});D.push({from:_[k],to:_[k+1],scores:E?.scores||{}})}if(x=Ut(D,{base:y?.scores?ce(y.scores,n.length/g):null}),x.length>1){const k=[];for(let E=0;E<x.length;E++){const C=x[E],te=C.lang&&C.lang!=="en"&&(x[E-1]?.lang==="en"||x[E+1]?.lang==="en");k.push(te?ce((await h.identify(n.subarray(C.from,C.to),{langs:d.langs}))?.scores||{},(C.to-C.from)/g):C.lang)}x=zt(x,k)}x.length<2&&(x=null)}if(x){z=[];for(const _ of x){const D=await h(n.subarray(_.from,_.to),_.lang?{lang:_.lang}:{...d}),k=String(D?.text||"").trim(),E=D?.lang||_.lang||null;k&&z.push({text:k,lang:E,from:_.from,to:_.to}),E&&(d.last=E)}f=z.map(_=>_.text).join(" ");const y=new Map;for(const _ of z)_.lang&&y.set(_.lang,(y.get(_.lang)||0)+(_.to-_.from));H=[...y].sort((_,D)=>D[1]-_[1])[0]?.[0]||null,(z.length<2||y.size<2)&&(z=null)}else{const y=await h(n,d);f=String(y?.text||"").trim(),h.__indic&&(H=y?.lang||null)}}}catch(d){X(e,{type:"error",code:"decode_failed",message:d.message,fatal:!1});return}if(!f)return;{const d=Dt(f);if(d.removed&&d.removed/d.total>=vt&&d.total>=12?f="":f=d.text,f&&He(f)>$e){const O=Nt(f);f=O.replace(/[\s\p{P}]/gu,"").length<12||He(O)>$e?"":O}if(!f)return}const Ve=o>=fe*g,be=o>=We*g;if(t||u||Ve||be){const d=t?"flush":u?"silence":be?"overflow":"length",O=d==="flush"||d==="silence",x=e.samples-o,y=[];p&&y.push(p),x>0&&y.push(Ye(e).subarray(o)),e.chunks=y,e.samples=y.reduce((w,A)=>w+A.length,0),e.lastInterim="";const _=un(n,s);if(kt(f,_?_.length:0)||e.echo?.role==="mic"&&ft(ee.verdict(e.echo,r,r+n.length)))return;let D=null,k=null;if(e.diarizer)try{const w=e.speakerLabel?null:await Y.spans(n),A=w?lt(w):[];if(A.length){const P=new Map;for(const{local:F}of st(A)){const U=it(n,A,F),ae=U.length?await j.embed(U):null,se=U.length<Fe,I=U.length<Ce;P.set(F,e.diarizer.assign(ae,{pinnedLabel:null,weak:se,thin:I}))}const B=Math.round(r/g*1e3);k=A.map(F=>({startMs:B+Math.round(F.start*1e3),durationMs:Math.round((F.end-F.start)*1e3),speaker:P.get(F.local)})).filter(F=>F.speaker),D=P.get(at(A))||null}}catch{}if(e.diarizer&&!D)try{const w=_,A=w?await j.embed(w):null,P=!!w&&w.length<Fe,B=!!w&&w.length<Ce;D=e.diarizer.assign(A,{pinnedLabel:e.speakerLabel,weak:P,thin:B})}catch{}let E=null;(e.langs||e.translateTo)&&(H?E=H:ge?E=ge:me(L)&&!e.remote?E="en":v?E=yt(f,S||e.lang)||null:E=e.lang||gt(f,{allowed:e.langs||[],last:e.lastLang}).lang,E&&E!==e.lastLang&&(e.lastLang=E,X(e,{type:"language",lang:E})));const C=Math.round(r/g*1e3),te=z&&(e.langs||e.translateTo)?z.map((w,A)=>({text:w.text,lang:w.lang,startMs:C+Math.round(w.from/g*1e3),durationMs:Math.round((w.to-w.from)/g*1e3),last:A===z.length-1})):[{text:f,lang:E,startMs:C,durationMs:Math.round(n.length/g*1e3),last:!0}];for(const w of te){te.length>1&&w.lang&&w.lang!==e.lastLang&&(e.lastLang=w.lang,X(e,{type:"language",lang:w.lang}));const{text:A,lang:P,startMs:B}=w,F=(A.match(new RegExp("\\p{Script=Latin}","gu"))||[]).length/Math.max(1,(A.match(new RegExp("\\p{L}","gu"))||[]).length),U=Z.indictransLanguage(P)&&F<.5&&Z.state()!=="error"&&ut(),ae=!!e.translateTo&&pt(P,e.translateTo)&&(U||mt(A,P)&&oe.state()!=="error"),se=te.length>1&&k?k.filter(I=>I.startMs<B+w.durationMs&&I.startMs+I.durationMs>B):k;if(X(e,{type:"final",text:A,reason:d,endOfTurn:w.last?O:!1,durationMs:w.durationMs,startMs:B,...P?{lang:P}:{},...ae?{translating:!0}:{},...D?{speaker:D}:{},...se?.length?{turns:se}:{}}),ae){const I=e.translateTo,pe=U?Z:oe;pe.state()==="off"&&pe.init({...e.translateLoad,...U?{sessionOptions:re()}:{}}),e.translations=e.translations.then(async()=>{await pe.ready();const De=U?await Z.translate(A,P):await oe.translate(A);X(e,{type:"translation",startMs:B,lang:P,to:I,text:De||null,...De?{}:{failed:!0}})}).catch(()=>{})}}}else f!==e.lastInterim&&(e.lastInterim=f,X(e,{type:"interim",text:f}))}async function dn(e){const t=de(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(Q=Q.then(()=>ke(t,{flush:!0}).catch(()=>{}))),await Promise.race([t.translations,new Promise(n=>setTimeout(n,rn).unref?.())])}finally{if(X(t,{type:"end"}),t.listeners.clear(),$.delete(t.id),t.poll){const n=setTimeout(()=>V.delete(t.id),Qt);n.unref?.(),V.set(t.id,{session:t,timer:n})}t.diarizer&&(j.release(),Y.release()),t.translateTo&&(oe.release(),Z.release()),R.release(),ee.leave(t.echo),$.size===0&&ue()&&N?.arm()}return!0}function jn(){for(const e of $.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);$.clear();for(const e of V.values())clearTimeout(e.timer);V.clear(),N?.disarm(),N=null,m="off",L=null,h=null,b=null,q=null,M=null}function Bn(e,t="test/fake",{warmMs:n=null,dtype:o=null}={}){h=e,L=t,m=e?"ready":"off",W=o,n!==null&&(N=we({warmMs:n,busy:le,unload:()=>Me()}),e&&N.arm())}export{qt as AUTO_FETCH_MAX_MB,$e as COMPRESSION_LIMIT,$t as FROM_ENGLISH,Ht as FROM_ENGLISH_RUN_S,vt as LOOP_DROP,jt as PAUSE_SHARE,ze as PIECE_MIN_S,Pt as PIECE_PAUSE_S,g as SAMPLE_RATE,Ft as SURE_ENGLISH,Ce as THIN_SPEAKER_SAMPLES,Rt as TO_ENGLISH,Ct as WEAK_ENGLISH_MIN_S,Fe as WEAK_SPEAKER_SAMPLES,jn as _reset,Bn as _setPipeForTest,sn as clampEndSilence,Dt as collapseLoops,Nt as collapseRuns,He as compressionRatio,Fn as createSession,Un as decodeNow,$n as drainEvents,dn as endSession,Hn as endedSession,de as getSession,vn as health,On as init,ue as isReady,Ut as languageGroups,kt as looksHallucinated,Kt as modelOnDisk,on as noiseFloorOf,Gt as pauseCuts,Bt as pauseLevel,Dn as progress,zn as pushAudio,cn as quietestCut,zt as relabelGroups,ie as runtimeDtype,Pe as runtimeName,ce as segmentLanguage,Rn as sessionCount,Pn as setModel,nn as silenceGate,Ke as speakerPlan,bn as state,re as sttSessionOptions,Ot as sttThreads,Cn as subscribe,Gn as toFloat32,Me as unload,Nn as warmPending};
package/src/stt-models.js CHANGED
@@ -1 +1 @@
1
- const d="istupakov/parakeet-tdt-0.6b-v3-onnx",n=Object.freeze({id:"indic-open-model-license",version:"1.0",name:"Indic Open Model License v1.0",url:"https://github.com/Bodhan-AI/bodhan-model-info/blob/main/licenses/indic-open-model-license/v1/Indic_Open_Model_License.md",summary:["Free to use, including commercially, when it runs on your own computer — as it does in Chap.","You may not run it as a service or API for other people without Bodhan AI's written approval.","Not for mass surveillance, deceptive automated calls, impersonating someone's voice, or other prohibited uses (section 10).","Provided as is, with no warranty. Built by Bodhan AI (IIT Madras) on NVIDIA Canary (CC-BY-4.0)."],attribution:"Built with Indic-Transcribe from Bodhan AI / AI4Bharat"});function c(e){return e?`${e.id}@${e.version}`:null}const a=[{id:"onnx-community/whisper-tiny.en",label:"Tiny (English)",lang:"English",tier:"light",approxMB:150,ramMB:400,note:"Fastest, lightest. English only — great for quick dictation on any machine."},{id:"onnx-community/whisper-base",label:"Base (multilingual)",lang:"99 languages (auto-detected)",tier:"balanced",approxMB:300,ramMB:700,note:"Small and quick to install. Detects the spoken language automatically; good accuracy at real-time speed."},{id:"onnx-community/whisper-small",label:"Small (multilingual)",lang:"99 languages (auto-detected)",tier:"accurate",approxMB:950,ramMB:1600,note:"Noticeably more accurate; needs a faster CPU to keep up in real time."},{id:"onnx-community/whisper-large-v3-turbo",label:"Large v3 Turbo (multilingual)",lang:"99 languages (auto-detected)",tier:"max",approxMB:1600,ramMB:3200,note:"Best accuracy. For powerful machines; use the native (npm) gateway for speed."},{id:"istupakov/parakeet-tdt-0.6b-v3-onnx",label:"Parakeet TDT 0.6B v3 (multilingual, fast)",lang:"25 European languages (auto-detected)",tier:"accurate",engine:"parakeet-tdt",recommended:!0,approxMB:690,ramMB:1600,note:"Recommended — NVIDIA Parakeet transducer. Several× faster than Whisper at similar or better accuracy, English + 24 EU languages. One-time download; best on the native (npm) gateway."},{id:"ConwayResearch/Underdog-Bark-3.0",label:"Parakeet TDT 0.6B v3 for the Neural Engine (English)",lang:"English",tier:"light",engine:"coreml-tdt",platforms:["darwin-arm64"],approxMB:200,ramMB:500,note:"The same Parakeet model, repacked for the Apple Neural Engine: a 200 MB download and the fastest dictation on a Mac. English only. Needs the Apple helper."},{id:"bodhan-ai/indic-transcribe-core",label:"Indic-Transcribe (Indian languages)",lang:"25 Indian languages + Indian English (detected line by line, mixed speech)",tier:"accurate",engine:"indic-canary",requiresNative:!0,approxMB:1530,ramMB:2600,license:n,attribution:n.attribution,note:"Best for Telugu, Hindi, Tamil and the other Indian languages, with Indian English and mixed speech: each line is identified and written in its own script. By Bodhan AI (IIT Madras) on NVIDIA Canary; free to use on your own computer under its licence."}],u="istupakov/parakeet-tdt-0.6b-v3-onnx";function p(e){return i(e)?.engine||"whisper"}function m(e,{platform:t=process.platform,arch:o=process.arch,helper:r=!1,native:l=!globalThis.__CHATPANEL_WASM_PATHS__}={}){return Array.isArray(e?.platforms)&&!e.platforms.includes(`${t}-${o}`)?"Needs a Mac with Apple Silicon.":e?.requiresNative&&!l?"Needs the npm gateway — the standalone binary cannot run it.":e?.engine==="coreml-tdt"&&!r?"Needs the Apple helper — Install it on the Apple on-device row (Runtime).":null}function h(e){return a.some(t=>t.id===e)}function i(e){return a.find(t=>t.id===e)||null}function g(e){return/\.en$/.test(String(e||""))}function b(e){return i(e)?.dtype||null}function f(e){const t=String(e||"");return/^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(t)&&!t.includes("..")}const s=[{id:"auto",label:"Auto (recommended)",note:"q8 on the native gateway, fp32 on the WASM binary."},{id:"q8",label:"q8 — fast, balanced",note:"Int8. Best speed/quality trade-off (native default)."},{id:"q4",label:"q4 — smallest & fastest",note:"4-bit. Least memory; slightly lower accuracy."},{id:"int8",label:"int8",note:"Alternative int8 export."},{id:"fp16",label:"fp16 — more accurate",note:"Half precision. Larger, a bit slower."},{id:"fp32",label:"fp32 — most accurate (slow)",note:"Full precision. Largest + slowest; the only one that loads on the WASM binary."}];function y(e){return s.some(t=>t.id===e)}export{d as DEFAULT_STT_MODEL,n as INDIC_LICENSE,u as RECOMMENDED_STT_MODEL,s as STT_DTYPES,a as STT_MODEL_CATALOG,g as isEnglishOnly,h as isKnownSttModel,f as isValidCustomSttId,y as isValidDtype,c as licenseAcceptance,i as sttModel,b as sttModelDtype,p as sttModelEngine,m as sttModelUnavailable};
1
+ const c="istupakov/parakeet-tdt-0.6b-v3-onnx",n=Object.freeze({id:"indic-open-model-license",version:"1.0",name:"Indic Open Model License v1.0",url:"https://github.com/Bodhan-AI/bodhan-model-info/blob/main/licenses/indic-open-model-license/v1/Indic_Open_Model_License.md",summary:["Free to use, including commercially, when it runs on your own computer — as it does in Chap.","You may not run it as a service or API for other people without Bodhan AI's written approval.","Not for mass surveillance, deceptive automated calls, impersonating someone's voice, or other prohibited uses (section 10).","Provided as is, with no warranty. Built by Bodhan AI (IIT Madras) on NVIDIA Canary (CC-BY-4.0)."],attribution:"Built with Indic-Transcribe from Bodhan AI / AI4Bharat"});function d(e){return e?`${e.id}@${e.version}`:null}const a=[{id:"onnx-community/whisper-tiny.en",label:"Tiny (English)",lang:"English",tier:"light",approxMB:150,ramMB:400,note:"Fastest, lightest. English only — great for quick dictation on any machine."},{id:"onnx-community/whisper-base",label:"Base (multilingual)",lang:"99 languages (auto-detected)",tier:"balanced",approxMB:300,ramMB:700,note:"Small and quick to install. Detects the spoken language automatically; good accuracy at real-time speed."},{id:"onnx-community/whisper-small",label:"Small (multilingual)",lang:"99 languages (auto-detected)",tier:"accurate",approxMB:950,ramMB:1600,note:"Noticeably more accurate; needs a faster CPU to keep up in real time."},{id:"onnx-community/whisper-large-v3-turbo",label:"Large v3 Turbo (multilingual)",lang:"99 languages (auto-detected)",tier:"max",approxMB:1600,ramMB:3200,note:"Best accuracy. For powerful machines; use the native (npm) gateway for speed."},{id:"istupakov/parakeet-tdt-0.6b-v3-onnx",label:"Parakeet TDT 0.6B v3 (multilingual, fast)",lang:"25 European languages (auto-detected)",tier:"accurate",engine:"parakeet-tdt",recommended:!0,approxMB:690,ramMB:1600,note:"Recommended — NVIDIA Parakeet transducer. Several× faster than Whisper at similar or better accuracy, English + 24 EU languages. One-time download; best on the native (npm) gateway."},{id:"ConwayResearch/Underdog-Bark-3.0",label:"Parakeet TDT 0.6B v3 for the Neural Engine (English)",lang:"English",tier:"light",engine:"coreml-tdt",platforms:["darwin-arm64"],approxMB:200,ramMB:500,licence:"cc-by-nc-4.0",nonCommercial:!0,note:"The same Parakeet model, repacked for the Apple Neural Engine: a 200 MB download and the fastest dictation on a Mac. English only. Needs the Apple helper. Non-commercial licence (CC-BY-NC 4.0) — for personal use."},{id:"bodhan-ai/indic-transcribe-core",label:"Indic-Transcribe (Indian languages)",lang:"25 Indian languages + Indian English (detected line by line, mixed speech)",tier:"accurate",engine:"indic-canary",requiresNative:!0,approxMB:1530,ramMB:2600,license:n,attribution:n.attribution,note:"Best for Telugu, Hindi, Tamil and the other Indian languages, with Indian English and mixed speech: each line is identified and written in its own script. By Bodhan AI (IIT Madras) on NVIDIA Canary; free to use on your own computer under its licence."}],u="istupakov/parakeet-tdt-0.6b-v3-onnx";function p(e){return i(e)?.engine||"whisper"}function m(e,{platform:t=process.platform,arch:o=process.arch,helper:r=!1,native:l=!globalThis.__CHATPANEL_WASM_PATHS__}={}){return Array.isArray(e?.platforms)&&!e.platforms.includes(`${t}-${o}`)?"Needs a Mac with Apple Silicon.":e?.requiresNative&&!l?"Needs the npm gateway — the standalone binary cannot run it.":e?.engine==="coreml-tdt"&&!r?"Needs the Apple helper — Install it on the Apple on-device row (Runtime).":null}function h(e){return a.some(t=>t.id===e)}function i(e){return a.find(t=>t.id===e)||null}function g(e){return/\.en$/.test(String(e||""))}function b(e){return i(e)?.dtype||null}function f(e){const t=String(e||"");return/^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(t)&&!t.includes("..")}const s=[{id:"auto",label:"Auto (recommended)",note:"q8 on the native gateway, fp32 on the WASM binary."},{id:"q8",label:"q8 — fast, balanced",note:"Int8. Best speed/quality trade-off (native default)."},{id:"q4",label:"q4 — smallest & fastest",note:"4-bit. Least memory; slightly lower accuracy."},{id:"int8",label:"int8",note:"Alternative int8 export."},{id:"fp16",label:"fp16 — more accurate",note:"Half precision. Larger, a bit slower."},{id:"fp32",label:"fp32 — most accurate (slow)",note:"Full precision. Largest + slowest; the only one that loads on the WASM binary."}];function y(e){return s.some(t=>t.id===e)}export{c as DEFAULT_STT_MODEL,n as INDIC_LICENSE,u as RECOMMENDED_STT_MODEL,s as STT_DTYPES,a as STT_MODEL_CATALOG,g as isEnglishOnly,h as isKnownSttModel,f as isValidCustomSttId,y as isValidDtype,d as licenseAcceptance,i as sttModel,b as sttModelDtype,p as sttModelEngine,m as sttModelUnavailable};
@@ -1 +1 @@
1
- import{existsSync as S,readdirSync as $}from"node:fs";import{join as b}from"node:path";import{ensureLib as k,modelRoot as v,withModelSource as P}from"./ner-engine.js";import{runtimeDtype as h,DTYPE_SUFFIX as T}from"./model-runtime.js";import{makeWarmTimer as E}from"./warm-timer.js";const M="Xenova/opus-mt-mul-en",A=112,R=1200;let t="off",p=M,c=null,f=null,u=null,i=null,l=null,_=0,m=0,w=Promise.resolve(),g=null;function H(){return p}function W(){return t}function x(){return t==="ready"&&!!c}function Y(){return i}function q(){return{configured:t!=="off",ok:x(),state:t,model:p,error:f,approxMB:A,onDisk:D(),warmMs:l?.warmMs??null}}function y(){return _>0||m>0||t==="loading"||t==="downloading"}function z(){m++,l?.disarm()}function G(){m=Math.max(0,m-1),m===0&&_===0&&x()&&l?.arm()}async function F({log:e=()=>{}}={}){if(y())return!1;l?.disarm();const n=c;if(c=null,g=null,u=null,i=null,f=null,t="off",n){try{await n.dispose?.()}catch{}e("[translate] idle — model unloaded (reloads on the next translated meeting)")}return!0}function D(e=p,n=h()){const d=b(v(),...e.split("/"),"onnx");if(!S(d))return!1;const r=T[n]??"";try{const a=$(d);return a.includes(`encoder_model${r}.onnx`)&&a.some(o=>o===`decoder_model_merged${r}.onnx`||o===`decoder_model${r}.onnx`)}catch{return!1}}async function O({log:e=()=>{},allowDownload:n=!0}={}){let d;try{d=await k()}catch(o){return t="error",f=o.message,e(`[translate] engine unavailable (${o.message})`),!1}const r=p,a=D(r);if(!a&&!n)return t="error",f="model not on disk and downloads disabled",!1;t=a?"loading":"downloading",a||(i={model:r,file:null,pct:0},e(`[translate] downloading ${r} (one-time, ~${A} MB)…`));try{const o=s=>{if(!s)return;const L=typeof s.progress=="number"?Math.round(s.progress):i?.pct??0;(s.status==="progress"||s.status==="download"||s.status==="initiate")&&(i={model:r,file:s.file||i?.file||null,pct:L})};return c=await P({host:a?null:"https://huggingface.co/",allowRemote:!a},s=>s.pipeline("translation",r,{dtype:h(),progress_callback:o})),t="ready",f=null,i=null,e(`[translate] ready — ${r} @ ${h()} (meeting lines into English, in-process, offline)`),!0}catch(o){return f=o.message,i=null,t="error",e(`[translate] load failed (${o.message}) — lines stay in the language they were spoken in`),!1}}function X(e){return e.then(n=>(n&&!y()&&l?.arm(),n))}function J(e={}){if(u&&t!=="error")return u;t="loading";const n=typeof e.onLog=="function"?e.onLog:()=>{};return l=E({warmMs:e.warmMs,busy:y,log:n,unload:()=>F({log:n})}),u=X(O({log:n,allowDownload:e.allowDownload!==!1})),u}function K(){return u?u.then(()=>x(),()=>!1):Promise.resolve(x())}function Q(e){const n=String(e||"").trim().slice(0,R);if(!n||!x())return Promise.resolve(null);_++,l?.disarm();const d=w.then(async()=>{try{if(g)return await g(n)??null;const r=await c(n,{max_new_tokens:400});return String((Array.isArray(r)?r[0]:r)?.translation_text||"").trim()||null}catch{return null}});return w=d.catch(()=>null),d.finally(()=>{_--,y()||l?.arm()})}function V(){l?.disarm(),l=null,m=0,_=0,t="off",p=M,c=null,g=null,f=null,u=null,i=null,w=Promise.resolve()}function Z(e){g=e||null,c=e?{dispose:async()=>{}}:null,t=e?"ready":"off"}export{M as DEFAULT_TRANSLATE_MODEL,A as TRANSLATE_MODEL_APPROX_MB,V as _reset,Z as _setForTest,H as activeModel,q as health,J as init,x as isReady,D as modelOnDisk,Y as progress,K as ready,G as release,z as retain,W as state,Q as translate,F as unload};
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};
package/src/tts-engine.js CHANGED
@@ -1 +1 @@
1
- import{modelFetch as nt}from"./model-sources.js";import{join as $}from"node:path";import{existsSync as z,mkdirSync as rt,readFileSync as ot,writeFileSync as st,renameSync as lt,statSync as B}from"node:fs";import{ensureLib as it,modelRoot as at}from"./ner-engine.js";import{runtimeDtype as C,runtimeName as G,DTYPE_SUFFIX as ut}from"./model-runtime.js";import{DEFAULT_TTS_MODEL as L,DEFAULT_TTS_VOICE as q,STYLE_DIM as U,ttsModelDtype as N,isKnownTtsModel as ct,isValidVoiceId as J,voiceLang as ft,ttsModelEngine as Q,ttsModel as Z}from"./tts-models.js";import{bundleOnDisk as dt}from"./pocket-tts-engine.js";import{makeWarmTimer as K}from"./warm-timer.js";const O=24e3;let f="off",w=null,R=0,h=null,y=null,M=null,P=null,T=null,_=null,A=null,p=null,D=null,g=null,k=null,v=O;const H=new Map,pt={style_text_to_speech_2:"style-tts2",vits:"vits",speecht5:"speecht5"},x="pocket-tts",ht="Xenova/speecht5_hifigan";function mt(){return p==="speecht5"||p===x}function Ut(){return p===x}function Ot(){return g?.builtinVoices?.()||[]}async function Vt({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 s=new n;return await s.load(o,{log:e}),k=s,s}function Rt(){return p}function Ht(){return v}function wt(){return p==="style-tts2"}function zt(){return f}function V(){return f==="ready"&&!!y}function Bt(){return _}function Ct(){return{configured:f!=="off",ok:V(),state:f,model:h,dtype:P,runtime:G(),error:T,arch:p,sampleRate:v,voices:wt(),customVoices:mt(),warmMs:w?.warmMs??null}}function Nt(){return!!w?.pending()}function F(){return R>0||f==="loading"||f==="downloading"}async function j({log:t=()=>{}}={}){if(F())return!1;w?.disarm();const e=!!(y||g||k),n=[y,D,g,k];y=null,M=null,D=null,g=null,k=null,p=null,P=null,A=null,_=null,T=null,f="off",v=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 yt(t){return t.then(e=>(e&&!F()&&w?.arm(),e))}function W(t){return $(at(),...String(t).split("/"))}function gt(t=h||L,e=N(t)||C()){if(Q(t)===x)return dt(Z(t)?.bundle);const n=W(t),r=ut[e]??"",o=[$(n,"onnx",`model${r}.onnx`),$(n,"tokenizer.json")];try{return o.every(s=>z(s)&&B(s).size>0)}catch{return!1}}function Kt(t,e=h||L){if(!J(t))return!1;const n=$(W(e),"voices",`${t}.bin`);try{return z(n)&&B(n).size>0}catch{return!1}}function jt(t={}){const e=t.tts||{};if(e.enabled===!1){f="off";return}h=e.model||L,w=K({warmMs:e.warmMs,busy:F,unload:()=>j()})}async function _t(t,{log:e=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(Q(t)===x)return Tt(t,{log:e,allowDownload:n});const o=y,s=h;let c;try{c=await it()}catch(i){return f="error",T=`engine load failed: ${i.message}`,e(`[tts] transformers.js not available (${i.message}) — read-aloud falls back to browser speech`),!1}const d=(r&&r!=="auto"?r:null)||N(t)||C(),l=gt(t,d);if(c.env.allowRemoteModels=l?!1:!!n,!l&&!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(!l&&(!!1||!ct(t)))try{c.env.remoteHost="https://huggingface.co/"}catch{}f=l?"loading":"downloading",l||(_={model:t,file:null,pct:0},e(`[tts] downloading voice model ${t} (one-time)…`));try{const i=await import("@huggingface/transformers");let E="";try{const b=await i.AutoConfig.from_pretrained(t);E=String(b?.model_type||"").toLowerCase()}catch{}const S=pt[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 X=b=>{b?.status==="progress"&&b.file&&(_={model:t,file:b.file,pct:Math.round(b.progress||0)})},tt=S==="vits"?i.VitsModel:S==="speecht5"?i.SpeechT5ForTextToSpeech:i.StyleTextToSpeech2Model,[Y,et]=await Promise.all([tt.from_pretrained(t,{dtype:d,progress_callback:X}),i.AutoTokenizer.from_pretrained(t)]);return D=S==="speecht5"?await i.SpeechT5HifiGan.from_pretrained(ht,{dtype:d,progress_callback:X}):null,y=Y,M=et,h=t,P=d,p=S,v=Number(Y?.config?.sampling_rate)||(S==="style-tts2"?O:16e3),f="ready",T=null,_=null,e(`[tts] ready — model ${t} @ ${d} (${S}, ${v} Hz, ${G()}, offline) — local speech active`),!0}catch(i){return y=o,h=s,f=o?"ready":"error",T=i.message,_=null,e(`[tts] model load failed (${i.message})`),!1}finally{try{c.env.remoteHost=u}catch{}}}async function Tt(t,{log:e=()=>{},allowDownload:n=!0}={}){const r=p,o=g,s=h,{PocketTTS:c,bundleOnDisk:m,DEFAULT_BUNDLE:d,SAMPLE_RATE:l}=await import("./pocket-tts-engine.js"),u=Z(t)?.bundle||d;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:i,pct:E})=>{_={model:t,file:i,pct:E}}}),g=a,y=a,M=null,D=null,h=t,p=x,P="int8",v=l,f="ready",T=null,_=null,!0}catch(a){return g=o,p=r,h=s,f=o||y?"ready":"error",T=a.message,_=null,e(`[pocket-tts] load failed (${a.message})`),!1}}async function Et(t,{onLog:e=()=>{},allowDownload:n=!0,dtype:r="auto"}={}){const o=r&&r!=="auto"?r:N(t)||C();return t===h&&V()&&P===o?!0:(w??=K({warmMs:void 0,busy:F,unload:()=>j()}),A=yt(_t(t,{log:e,allowDownload:n,dtype:r})),A)}async function Wt({onLog:t=()=>{},allowDownload:e=!0,model:n=null,dtype:r="auto"}={}){return V()?!0:A||Et(n||h||L,{onLog:t,allowDownload:e,dtype:r})}async function St(t,{allowDownload:e=!0,log:n=()=>{}}={}){if(!J(t))throw new Error(`invalid voice id: ${t}`);const r=H.get(t);if(r)return r;const o=$(W(h||L),"voices"),s=$(o,`${t}.bin`);if(!(z(s)&&B(s).size>0)){if(!e)throw new Error(`voice ${t} not on disk and downloads disabled`);rt(o,{recursive:!0});const d=`https://huggingface.co/${h||L}/resolve/main/voices/${t}.bin`,l=await nt()(d,{redirect:"follow"});if(!l.ok)throw new Error(`fetch voice ${t} → HTTP ${l.status}`);const u=`${s}.part`;st(u,Buffer.from(await l.arrayBuffer())),lt(u,s),n(`[tts] fetched voice ${t}`)}const c=ot(s),m=new Float32Array(c.buffer,c.byteOffset,Math.floor(c.byteLength/4));return H.set(t,m),m}function xt(t,e=300){const n=(o,s)=>{if(o.length<=e)return[o];if(!s.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]=s,d=[];let l="";for(const u of o.split(c)){const a=u.trim();if(!a)continue;const i=l?`${l} ${a}`:a;i.length>e&&l?(d.push(...n(l,m)),l=a):l=i}return l&&d.push(...n(l,m)),d},r=[];for(const o of String(t).split(/(?<=[.!?])\s+|\n{2,}/)){const s=o.trim();s&&r.push(...n(s,[/(?<=[,;:])\s+/,/\s+/]))}return r}async function I(t,{voice:e=q,speed:n=1,speakerEmbedding:r=null}={}){if(!V())throw new Error("tts model not ready");const o=await import("@huggingface/transformers");if(p==="vits"){const i=M(String(t));return(await y(i)).waveform.data}if(p===x){const i=r?.data?.length?r:e;if(!i)throw new Error("this model needs a voice — pick a built-in one or record your own");return g.synth(String(t),{voice:i})}if(p==="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:i}=M(String(t)),E=new o.Tensor("float32",Float32Array.from(r),[1,512]),{waveform:S}=await y.generate_speech(i,E,{vocoder:D});return S.data}const{phonemize:s}=await import("phonemizer"),c=(await s(String(t),ft(e))).join(" "),{input_ids:m}=M(c,{truncation:!0}),d=await St(e),l=Math.min(Math.max(m.dims.at(-1)-2,0),Math.floor(d.length/U)-1),u=d.slice(l*U,l*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 Xt(t,e={}){R++,w?.disarm();try{return await Mt(t,e)}finally{R--,!F()&&V()&&w?.arm()}}async function Mt(t,{voice:e=q,speed:n=1,speakerEmbedding:r=null,onChunk:o=null}={}){if(p===x)return I(t,{voice:e,speed:n,speakerEmbedding:r});const s=xt(t),c=[];for(const u of s){const a=await I(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),d=new Float32Array(m);let l=0;for(const u of c)d.set(u,l),l+=u.length;return d}function Yt(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 Gt(t,{warmMs:e=null}={}){y=t,g=t,p=t?x:null,h=t?"test/fake":null,f=t?"ready":"off",e!==null&&(w=K({warmMs:e,busy:F,unload:()=>j()}),t&&w.arm())}function qt(){w?.disarm(),w=null,R=0,f="off",h=null,y=null,M=null,P=null,T=null,_=null,A=null,p=null,v=O,D=null,g=null,k=null,H.clear()}export{x as POCKET_ARCH,O as SAMPLE_RATE,ht as SPEECHT5_VOCODER,pt as SUPPORTED_ARCH,qt as _reset,Gt as _setForTest,Rt as arch,Ot as builtinVoices,Ct as health,jt as init,Ut as isPocket,V as isReady,W as modelDir,gt as modelOnDisk,Vt as pocketForEncoding,Bt as progress,Wt as ready,Ht as sampleRate,Et as setModel,xt as splitSentences,zt as state,mt as supportsCustomVoices,wt as supportsVoices,Xt as synth,I as synthChunk,Yt as toWav,j as unload,Kt as voiceOnDisk,Nt as warmPending};
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};
package/src/tts-models.js CHANGED
@@ -1 +1 @@
1
- const r="kyutai/pocket-tts",n="onnx-community/Kokoro-82M-v1.0-ONNX",c=n,u="af_heart",i=["alba","azelma","cosette","eponine","fantine","javert","jean","marius"],m="alba";function g(e){return i.includes(String(e||""))}function p(e=!0){return e?r:n}const f=256,b=510,h=5e3,o=[{id:"onnx-community/Kokoro-82M-v1.0-ONNX",label:"Kokoro 82M (v1.0)",lang:"English (US/UK)",tier:"balanced",arch:"style-tts2",approxMB:330,ramMB:600,sampleRate:24e3,voices:!0,note:"Apache-2.0, 82M params. Natural voices at ~5× realtime on CPU. The default."},{id:"onnx-community/Kokoro-82M-v1.1-zh-ONNX",label:"Kokoro 82M (v1.1, Chinese)",lang:"Chinese + English",tier:"balanced",arch:"style-tts2",approxMB:330,ramMB:600,sampleRate:24e3,voices:!0,note:"The Mandarin-tuned Kokoro. Same engine and voice mechanism as v1.0."},{id:"kyutai/pocket-tts",label:"Pocket TTS — clone your voice",lang:"English",tier:"accurate",arch:"pocket-tts",bundle:"english_2026-04",approxMB:146,ramMB:700,sampleRate:24e3,voices:!0,customVoices:!0,recommended:!0,requiresNative:!0,note:"Kyutai Pocket TTS (MIT code, CC-BY-4.0 weights). Eight built-in voices (downloaded with the model), and it can clone yours. Fastest model here. ~200 MB. Needs the npm gateway."},{id:"Xenova/speecht5_tts",label:"SpeechT5 — your own voice",lang:"English",tier:"custom",arch:"speecht5",dtype:"fp32",approxMB:190,ramMB:500,sampleRate:16e3,voices:!1,customVoices:!0,note:"Speaks using a voice you record — but it will NOT sound like you. It borrows pitch and timbre in a general way and produces a consistent voice of its own. Kokoro sounds better if you do not need a personal voice."},{id:"Xenova/mms-tts-hin",label:"MMS TTS — Hindi",lang:"Hindi (हिन्दी)",tier:"light",arch:"vits",approxMB:40,ramMB:200,sampleRate:16e3,voices:!1,note:'Tiny single-speaker VITS. Meta’s MMS covers ~1000 languages — search "mms-tts" for yours.'}],s={a:"en-us",b:"en-gb"},l=[{id:"af_heart",label:"Heart (US, female)",lang:"en-us",gender:"female",grade:"A"},{id:"af_bella",label:"Bella (US, female)",lang:"en-us",gender:"female",grade:"A-"},{id:"bf_emma",label:"Emma (UK, female)",lang:"en-gb",gender:"female",grade:"B-"},{id:"af_nicole",label:"Nicole (US, female)",lang:"en-us",gender:"female",grade:"B-",note:"Recorded close-mic — best on headphones."},{id:"af_aoede",label:"Aoede (US, female)",lang:"en-us",gender:"female",grade:"C+"},{id:"af_kore",label:"Kore (US, female)",lang:"en-us",gender:"female",grade:"C+"},{id:"af_sarah",label:"Sarah (US, female)",lang:"en-us",gender:"female",grade:"C+"},{id:"am_michael",label:"Michael (US, male)",lang:"en-us",gender:"male",grade:"C+"},{id:"am_fenrir",label:"Fenrir (US, male)",lang:"en-us",gender:"male",grade:"C+"},{id:"am_puck",label:"Puck (US, male)",lang:"en-us",gender:"male",grade:"C+"},{id:"af_nova",label:"Nova (US, female)",lang:"en-us",gender:"female",grade:"C"},{id:"af_alloy",label:"Alloy (US, female)",lang:"en-us",gender:"female",grade:"C"},{id:"bf_isabella",label:"Isabella (UK, female)",lang:"en-gb",gender:"female",grade:"C"},{id:"bm_george",label:"George (UK, male)",lang:"en-gb",gender:"male",grade:"C"},{id:"bm_fable",label:"Fable (UK, male)",lang:"en-gb",gender:"male",grade:"C"}];function M(e){return t(e)?.arch||"style-tts2"}function T(e){return t(e)?.bundle||null}function S(e){const a=t(e);return a?a.voices!==!1:!0}function _(e){return t(e)?.customVoices===!0}function x(e){return t(e)?.requiresNative===!0}function t(e){return o.find(a=>a.id===e)||null}function v(e){return o.some(a=>a.id===e)}function y(e){return t(e)?.dtype||null}function E(e){return l.find(a=>a.id===e)||null}function C(e){return l.some(a=>a.id===e)}function U(e){return/^[a-z]{2}_[a-z0-9]+$/.test(String(e||""))}function A(e){return s[String(e||"")[0]]||"en-us"}function k(e){const a=String(e||"");return/^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(a)&&!a.includes("..")}const d=[{id:"auto",label:"Auto (recommended)",note:"q8 on the native gateway, fp32 on the WASM binary."},{id:"q8",label:"q8 — fast, balanced",note:"Int8. Best speed/quality trade-off (native default)."},{id:"q4",label:"q4 — smallest & fastest",note:"4-bit. Least memory; audibly rougher."},{id:"fp16",label:"fp16 — more accurate",note:"Half precision. Larger, a bit slower."},{id:"fp32",label:"fp32 — best quality (slow)",note:"Full precision. The only one that loads on the WASM binary."}];function K(e){return d.some(a=>a.id===e)}export{m as DEFAULT_POCKET_VOICE,c as DEFAULT_TTS_MODEL,r as DEFAULT_TTS_MODEL_NATIVE,n as DEFAULT_TTS_MODEL_WASM,u as DEFAULT_TTS_VOICE,b as MAX_PHONEME_TOKENS,h as MAX_TTS_CHARS,i as POCKET_VOICES,f as STYLE_DIM,d as TTS_DTYPES,o as TTS_MODEL_CATALOG,l as TTS_VOICES,v as isKnownTtsModel,C as isKnownVoice,g as isPocketVoice,k as isValidCustomTtsId,K as isValidTtsDtype,U as isValidVoiceId,p as resolveDefaultModel,t as ttsModel,T as ttsModelBundle,y as ttsModelDtype,M as ttsModelEngine,_ as ttsModelHasCustomVoices,S as ttsModelHasVoices,x as ttsModelRequiresNative,E as ttsVoice,A as voiceLang};
1
+ const r="kyutai/pocket-tts",n="onnx-community/Kokoro-82M-v1.0-ONNX",d=n,u="af_heart",i=["alba","azelma","cosette","eponine","fantine","javert","jean","marius"],m="alba";function g(e){return i.includes(String(e||""))}function p(e=!0){return e?r:n}const f=256,b=510,h=5e3,o=[{id:"onnx-community/Kokoro-82M-v1.0-ONNX",label:"Kokoro 82M (v1.0)",lang:"English (US/UK)",tier:"balanced",arch:"style-tts2",approxMB:330,ramMB:600,sampleRate:24e3,voices:!0,note:"Apache-2.0, 82M params. Natural voices at ~5× realtime on CPU. The default."},{id:"onnx-community/Kokoro-82M-v1.1-zh-ONNX",label:"Kokoro 82M (v1.1, Chinese)",lang:"Chinese + English",tier:"balanced",arch:"style-tts2",approxMB:330,ramMB:600,sampleRate:24e3,voices:!0,note:"The Mandarin-tuned Kokoro. Same engine and voice mechanism as v1.0."},{id:"kyutai/pocket-tts",label:"Pocket TTS — clone your voice",lang:"English",tier:"accurate",arch:"pocket-tts",bundle:"english_2026-04",approxMB:146,ramMB:700,sampleRate:24e3,voices:!0,customVoices:!0,recommended:!0,requiresNative:!0,note:"Kyutai Pocket TTS (MIT code, CC-BY-4.0 weights). Eight built-in voices (downloaded with the model), and it can clone yours. Fastest model here. ~200 MB. Needs the npm gateway."},{id:"Xenova/speecht5_tts",label:"SpeechT5 — your own voice",lang:"English",tier:"custom",arch:"speecht5",dtype:"fp32",approxMB:190,ramMB:500,sampleRate:16e3,voices:!1,customVoices:!0,note:"Speaks using a voice you record — but it will NOT sound like you. It borrows pitch and timbre in a general way and produces a consistent voice of its own. Kokoro sounds better if you do not need a personal voice."},{id:"Xenova/mms-tts-hin",label:"MMS TTS — Hindi",lang:"Hindi (हिन्दी)",tier:"light",arch:"vits",approxMB:40,ramMB:200,sampleRate:16e3,voices:!1,licence:"cc-by-nc-4.0",nonCommercial:!0,note:'Tiny single-speaker VITS. Meta’s MMS covers ~1000 languages — search "mms-tts" for yours. Non-commercial licence (CC-BY-NC 4.0) — for personal use.'}],s={a:"en-us",b:"en-gb"},l=[{id:"af_heart",label:"Heart (US, female)",lang:"en-us",gender:"female",grade:"A"},{id:"af_bella",label:"Bella (US, female)",lang:"en-us",gender:"female",grade:"A-"},{id:"bf_emma",label:"Emma (UK, female)",lang:"en-gb",gender:"female",grade:"B-"},{id:"af_nicole",label:"Nicole (US, female)",lang:"en-us",gender:"female",grade:"B-",note:"Recorded close-mic — best on headphones."},{id:"af_aoede",label:"Aoede (US, female)",lang:"en-us",gender:"female",grade:"C+"},{id:"af_kore",label:"Kore (US, female)",lang:"en-us",gender:"female",grade:"C+"},{id:"af_sarah",label:"Sarah (US, female)",lang:"en-us",gender:"female",grade:"C+"},{id:"am_michael",label:"Michael (US, male)",lang:"en-us",gender:"male",grade:"C+"},{id:"am_fenrir",label:"Fenrir (US, male)",lang:"en-us",gender:"male",grade:"C+"},{id:"am_puck",label:"Puck (US, male)",lang:"en-us",gender:"male",grade:"C+"},{id:"af_nova",label:"Nova (US, female)",lang:"en-us",gender:"female",grade:"C"},{id:"af_alloy",label:"Alloy (US, female)",lang:"en-us",gender:"female",grade:"C"},{id:"bf_isabella",label:"Isabella (UK, female)",lang:"en-gb",gender:"female",grade:"C"},{id:"bm_george",label:"George (UK, male)",lang:"en-gb",gender:"male",grade:"C"},{id:"bm_fable",label:"Fable (UK, male)",lang:"en-gb",gender:"male",grade:"C"}];function M(e){return t(e)?.arch||"style-tts2"}function T(e){return t(e)?.bundle||null}function S(e){const a=t(e);return a?a.voices!==!1:!0}function _(e){return t(e)?.customVoices===!0}function x(e){return t(e)?.requiresNative===!0}function t(e){return o.find(a=>a.id===e)||null}function v(e){return o.some(a=>a.id===e)}function y(e){return t(e)?.dtype||null}function C(e){return l.find(a=>a.id===e)||null}function E(e){return l.some(a=>a.id===e)}function U(e){return/^[a-z]{2}_[a-z0-9]+$/.test(String(e||""))}function A(e){return s[String(e||"")[0]]||"en-us"}function k(e){const a=String(e||"");return/^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(a)&&!a.includes("..")}const c=[{id:"auto",label:"Auto (recommended)",note:"q8 on the native gateway, fp32 on the WASM binary."},{id:"q8",label:"q8 — fast, balanced",note:"Int8. Best speed/quality trade-off (native default)."},{id:"q4",label:"q4 — smallest & fastest",note:"4-bit. Least memory; audibly rougher."},{id:"fp16",label:"fp16 — more accurate",note:"Half precision. Larger, a bit slower."},{id:"fp32",label:"fp32 — best quality (slow)",note:"Full precision. The only one that loads on the WASM binary."}];function N(e){return c.some(a=>a.id===e)}export{m as DEFAULT_POCKET_VOICE,d as DEFAULT_TTS_MODEL,r as DEFAULT_TTS_MODEL_NATIVE,n as DEFAULT_TTS_MODEL_WASM,u as DEFAULT_TTS_VOICE,b as MAX_PHONEME_TOKENS,h as MAX_TTS_CHARS,i as POCKET_VOICES,f as STYLE_DIM,c as TTS_DTYPES,o as TTS_MODEL_CATALOG,l as TTS_VOICES,v as isKnownTtsModel,E as isKnownVoice,g as isPocketVoice,k as isValidCustomTtsId,N as isValidTtsDtype,U as isValidVoiceId,p as resolveDefaultModel,t as ttsModel,T as ttsModelBundle,y as ttsModelDtype,M as ttsModelEngine,_ as ttsModelHasCustomVoices,S as ttsModelHasVoices,x as ttsModelRequiresNative,C as ttsVoice,A as voiceLang};
package/src/vad-engine.js CHANGED
@@ -1 +1 @@
1
- import{existsSync as v}from"node:fs";import{join as D}from"node:path";import{ensureLib as k,modelRoot as O,withModelSource as S}from"./ner-engine.js";import{makeWarmTimer as F}from"./warm-timer.js";const w="onnx-community/silero-vad",z=2.2,T=16e3,s=512,R=.5,K=.35,V=.05,N=40,P=62;let o="off",m=null,M=null,c=null,h=null,g=null,f=null,x=0,_=0,y=null;function U(){return o}function L(){return o==="ready"&&(!!m||!!y)}function C(){return g}function H(){return{configured:o!=="off",ok:L(),state:o,model:w,error:c,warmMs:f?.warmMs??null}}function A(){return _>0||x>0||o==="loading"||o==="downloading"}function J(){x++,f?.disarm()}function Q(){x=Math.max(0,x-1),x===0&&_===0&&L()&&f?.arm()}function I(){return v(D(O(),...w.split("/"),"onnx","model.onnx"))}async function B({log:e=()=>{}}={}){if(A())return!1;f?.disarm();const t=m;if(m=null,h=null,g=null,c=null,o="off",t){try{await t.dispose?.()}catch{}e("[vad] idle — model unloaded")}return!0}async function G({log:e=()=>{},allowDownload:t=!0}={}){try{M=await k()}catch(r){return o="error",c=r.message,!1}const n=I();if(!n&&!t)return o="error",c="model not on disk and downloads disabled",!1;o=n?"loading":"downloading",n||(g={model:w,file:null,pct:0},e(`[vad] downloading ${w} (one-time, ~2 MB)…`));try{return m=await S({host:n?null:"https://huggingface.co/",allowRemote:!n},r=>r.AutoModel.from_pretrained(w,{config:{model_type:"custom"},dtype:"fp32"})),o="ready",c=null,g=null,e("[vad] ready — Silero VAD on levelled audio decides what is speech (the energy gate is the fallback)"),!0}catch(r){return c=r.message,g=null,o="error",e(`[vad] load failed (${r.message}) — the energy gate decides, as before`),!1}}function Y(e={}){if(h&&o!=="error")return h;o="loading";const t=typeof e.onLog=="function"?e.onLog:()=>{};return f=F({warmMs:e.warmMs,busy:A,log:t,unload:()=>B({log:t})}),h=G({log:t,allowDownload:e.allowDownload!==!1}).then(n=>(n&&!A()&&f?.arm(),n)),h}function W(e){if(!e.length)return 1;const t=[...e].sort((r,E)=>r-E),n=t[Math.floor(t.length*.9)]||0;return n>0?Math.min(N,Math.max(1,V/n)):1}function Z(){let e=null,t=0;const n=new Map,r=[],E=Math.ceil(90*T/s);async function b(l){let i=0;for(let u=0;u<l.length;u++)i+=l[u]*l[u];r.push(Math.sqrt(i/l.length)),r.length>P&&r.shift();const d=W(r),a=d===1?l:l.map(u=>u*d);if(y)return y(a);e||=new M.Tensor("float32",new Float32Array(256),[2,1,128]);const p=await m({input:new M.Tensor("float32",a,[1,s]),sr:new M.Tensor("int64",[BigInt(T)],[]),state:e});return e=p.stateN,Number(p.output.data[0])}return{async advance(l,i){if(!L())return!1;const d=i+l.length;t<i&&(t=Math.ceil(i/s)*s),_++;try{for(;t+s<=d;t+=s){const a=t-i;n.set(t/s,await b(l.slice(a,a+s)))}}catch{return!1}finally{_--}for(const a of n.keys()){if(n.size<=E)break;n.delete(a)}return!0},speechIn(l,i,d=R){let a=!1;for(let p=Math.floor(l/s);p*s<i;p++){const u=n.get(p);if(u!==void 0&&(a=!0,u>=d))return!0}return a?!1:null},_probs:n}}function ee(){f?.disarm(),f=null,x=0,_=0,o="off",m=null,y=null,c=null,h=null,g=null}function te(e){y=e||null,o=e?"ready":"off"}export{w as DEFAULT_VAD_MODEL,s as FRAME,N as LEVEL_MAX_GAIN,V as LEVEL_TARGET,P as LEVEL_WINDOW,K as OFFSET,R as ONSET,T as SAMPLE_RATE,z as VAD_MODEL_APPROX_MB,ee as _reset,te as _setForTest,Z as createStream,H as health,Y as init,L as isReady,W as levelGain,I as modelOnDisk,C as progress,Q as release,J as retain,U as state,B as unload};
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};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.117.0";export{o as VERSION};
1
+ const o="0.118.0";export{o as VERSION};