@chatpanel/gateway 0.57.2 → 0.57.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.57.2",
3
+ "version": "0.57.4",
4
4
  "description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -23,7 +23,7 @@
23
23
  "dependencies": {
24
24
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
25
25
  "@chatpanel/bridge": "^0.32.2",
26
- "@chatpanel/events": "^0.222.0",
26
+ "@chatpanel/events": "^0.226.0",
27
27
  "@chatpanel/pii": "^0.12.0",
28
28
  "@huggingface/transformers": "^4.2.0",
29
29
  "defuddle": "^0.19.4",
@@ -1 +1 @@
1
- const o="onnx-community/wespeaker-voxceleb-resnet34-LM",t=[{id:"onnx-community/wespeaker-voxceleb-resnet34-LM",label:"WeSpeaker ResNet34 (recommended)",lang:"any",recommended:!0,approxMB:7,dim:256,threshold:.6,note:"Tells voices apart for meeting transcription (who said what). Small, fast, and the most accurate of the two."},{id:"Xenova/wavlm-base-plus-sv",label:"WavLM Base+ SV (previous default)",lang:"any",approxMB:102,dim:512,threshold:.75,note:"The earlier speaker model. Larger and slower, and it merges similar voices far more often — kept so an existing install can switch back."}];function r(e){return t.find(n=>n.id===e)||null}function a(e){return!!r(e)}function i(e){return(r(e)||r(o)).threshold}function s(e){return r(e)?.approxMB??null}export{o as DEFAULT_DIARIZE_MODEL,t as DIARIZE_MODEL_CATALOG,s as diarizeApproxMB,r as diarizeModelEntry,i as diarizeThreshold,a as isKnownDiarizeModel};
1
+ const o="onnx-community/wespeaker-voxceleb-resnet34-LM",t=[{id:"onnx-community/wespeaker-voxceleb-resnet34-LM",label:"WeSpeaker ResNet34 (recommended)",lang:"any",recommended:!0,approxMB:7,dim:256,threshold:.4,note:"Tells voices apart for meeting transcription (who said what). Small, fast, and the most accurate of the two."},{id:"Xenova/wavlm-base-plus-sv",label:"WavLM Base+ SV (previous default)",lang:"any",approxMB:102,dim:512,threshold:.75,note:"The earlier speaker model. Larger and slower, and it merges similar voices far more often — kept so an existing install can switch back."}];function r(e){return t.find(n=>n.id===e)||null}function a(e){return!!r(e)}function i(e){return(r(e)||r(o)).threshold}function s(e){return r(e)?.approxMB??null}export{o as DEFAULT_DIARIZE_MODEL,t as DIARIZE_MODEL_CATALOG,s as diarizeApproxMB,r as diarizeModelEntry,i as diarizeThreshold,a as isKnownDiarizeModel};
package/src/stt-engine.js CHANGED
@@ -1 +1 @@
1
- import{join as Z}from"node:path";import{existsSync as I,readdirSync as ee}from"node:fs";import{randomUUID as te}from"node:crypto";import{ensureLib as X,modelRoot as B}from"./ner-engine.js";import{runtimeDtype as L,runtimeName as Y,DTYPE_SUFFIX as ne}from"./model-runtime.js";import{verifyModelWeights as re}from"./model-integrity.js";import{DEFAULT_STT_MODEL as j,isEnglishOnly as W,sttModelDtype as R,isKnownSttModel as oe,sttModelEngine as z}from"./stt-models.js";import*as T from"./parakeet-engine.js";import*as E from"./diarize-engine.js";import{diarizeApproxMB as ie}from"./diarize-models.js";import{makeWarmTimer as H}from"./warm-timer.js";const p=16e3,ae=p,le=2*p,se=2,ce=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 ue(e,t){if(t>se*p)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?ce.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}let s="off",h=null,d=null,M=null,x=null,g=null,A=null,w=null;function fe(e=h||j,t=R(e)||L()){if(z(e)==="parakeet-tdt")return T.parakeetOnDisk(e,T.parakeetDtype(t));const n=Z(B(),...e.split("/"),"onnx");if(!I(n))return!1;const r=ne[t]??"";try{const o=ee(n);return o.includes(`encoder_model${r}.onnx`)&&o.some(a=>a===`decoder_model_merged${r}.onnx`||a===`decoder_model${r}.onnx`)}catch{return!1}}function He(){return s}function v(){return s==="ready"&&!!d}function Ce(){return g}function Ue(){return{configured:s!=="off",ok:v(),state:s,model:h,dtype:A,runtime:Y(),error:M,warmMs:w?.warmMs??null}}function Ke(){return!!w?.pending()}function b(){return k.size>0||s==="loading"||s==="downloading"}async function C({log:e=()=>{}}={}){if(b())return!1;w?.disarm();const t=d;if(d=null,x=null,A=null,g=null,M=null,s="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((w?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function G(e){return e.then(t=>(t&&!b()&&w?.arm(),t))}async function q(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(z(e)==="parakeet-tdt")return de(e,{log:t,allowDownload:n,dtype:r});const o=d,a=h;let l;try{l=await X()}catch(m){return s="error",M=`engine load failed: ${m.message}`,t(`[stt] transformers.js not available (${m.message}) — dictation falls back to the browser engine`),!1}const i=(r&&r!=="auto"?r:null)||R(e)||L(),c=fe(e,i);if(l.env.allowRemoteModels=c?!1:!!n,!c&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const y=l.env.remoteHost,_=!oe(e);if(!c&&_)try{l.env.remoteHost="https://huggingface.co/"}catch{}s=c?"loading":"downloading",c||(g={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${_?", from Hugging Face":""})…`));try{const m=f=>{if(!f)return;const F=typeof f.progress=="number"?Math.round(f.progress):g?.pct??0;f.status==="progress"||f.status==="download"||f.status==="initiate"?g={model:e,file:f.file||g?.file||null,pct:F}:f.status==="done"&&f.file&&t(`[stt] fetched ${f.file}`)};let S;try{S=await l.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:m})}catch(f){if(c||_||!n)throw f;t(`[stt] mirror fetch failed (${String(f.message).slice(0,80)}) — retrying from Hugging Face…`),l.env.remoteHost="https://huggingface.co/",l.env.allowRemoteModels=!0,S=await l.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:m})}if(!c)try{re(e,{modelsDir:B(),log:t})}catch(f){try{await S.dispose?.()}catch{}throw f}if(d=S,h=e,s="ready",M=null,g=null,A=i,o&&o!==S)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (in-process, offline) — local dictation active`),!0}catch(m){return M=m.message,g=null,o?(d=o,h=a,s="ready"):s="error",t(`[stt] model load failed (${m.message})${o?" — keeping previous model":""}`),!1}finally{try{l.env.remoteHost=y}catch{}}}async function de(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=d,a=h,l=T.parakeetDtype(r&&r!=="auto"?r:me()),u=T.parakeetOnDisk(e,l);if(!u&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;s=u?"loading":"downloading",u||(g={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const i=await T.loadRecognizer({modelId:e,dtype:l,allowDownload:n,log:t,onProgress:y=>{g={model:e,file:y.file||null,pct:typeof y.pct=="number"?y.pct:g?.pct??0}}}),c=async y=>({text:await i.transcribe(y)});if(c.__parakeet=!0,c.dispose=()=>i.dispose(),d=c,h=e,s="ready",M=null,g=null,A=l,o&&o!==c)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${l} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(i){return M=i.message,g=null,o?(d=o,h=a,s="ready"):s="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}function me(){return T.PARAKEET_DEFAULT_DTYPE}const pe=30;function he({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:r=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof r=="number"&&r<=pe||e==="download"?{allowDownload:!0}:null}function U(e,{log:t=()=>{},warmMs:n}={}){const r=he({mode:e,onDisk:E.modelOnDisk(),ready:E.isReady(),approxMB:ie(E.activeModel())});r&&E.init({...r,warmMs:n,onLog:t})}function Oe(e={}){if(x)return x;const t=typeof e.onLog=="function"?e.onLog:()=>{};return h=e.model||j,s="loading",w=H({warmMs:e.warmMs,busy:b,log:t,unload:()=>C({log:t})}),x=G(q(h,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype})).then(n=>(n&&U(e.speaker,{log:t,warmMs:e.warmMs}),n)),x}async function Xe(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;const r=z(e)==="parakeet-tdt"?T.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:T.PARAKEET_DEFAULT_DTYPE):t.dtype&&t.dtype!=="auto"?t.dtype:R(e)||L();if(e===h&&v()&&A===r)return U(t.speaker,{log:n,warmMs:t.warmMs}),!0;w??=H({warmMs:t.warmMs,busy:b,log:n,unload:()=>C({log:n})});const o=await G(q(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype}));return o&&U(t.speaker,{log:n,warmMs:t.warmMs}),o}const ge=4,ye=6e4,we=1200,Q=12,K=700,$=.008,_e=30,k=new Map;let P=Promise.resolve();function Be(){return k.size}const Me=300,ke=3e3;function Te(e){const t=Number(e);return Number.isFinite(t)?Math.min(ke,Math.max(Me,Math.round(t))):K}function Ye({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=K,interims:a=!0,remote:l=null}={}){if(k.size>=ge){const i=new Error("too many concurrent dictation sessions");throw i.code="too_many_sessions",i}const u={id:te(),endSilenceMs:Te(o),lang:typeof e=="string"&&e?e.slice(0,12):null,langTried:!1,redact:!!t,diarize:!!n,speakerLabel:typeof r=="string"&&r?r.slice(0,40):null,diarizer:n?new E.Diarizer:null,remote:l||null,interims:a!==!1&&!l,chunks:[],samples:0,listeners:new Set,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return k.set(u.id,u),w?.disarm(),u.diarizer&&E.retain(),V(u),{id:u.id}}function O(e){return k.get(String(e||""))||null}function je(e,t){const n=O(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function D(e,t){for(const n of e.listeners)try{n(t)}catch{}}function V(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>be(e.id).catch(()=>{}),ye),e.idleTimer.unref?.()}function We(e,t){const n=O(e);if(!n||n.closed){const r=new Error("no such session");throw r.code="no_session",r}!(t instanceof Float32Array)||!t.length||(n.chunks.push(t),n.samples+=t.length,V(n),Ee(n))}function Ge(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let r=0;r<n.length;r++)n[r]=e.readFloatLE(r*4);return n}function Ee(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+we-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,P=P.then(()=>J(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function Se(e){const t=new Float32Array(e.samples);let n=0;for(const r of e.chunks)t.set(r,n),n+=r.length;return t}function N(e,t=0,n=e.length){let r=0;const o=Math.max(1,n-t);for(let a=t;a<n;a++)r+=e[a]*e[a];return Math.sqrt(r/o)}function xe(e){const t=Math.round(.02*p);let n=0,r=e.length;for(let o=0;o+t<=e.length;o+=t)if(N(e,o,o+t)>=$){n=o;break}for(let o=e.length-t;o>=0;o-=t)if(N(e,o,o+t)>=$){r=o+t;break}return r>n?e.subarray(n,r):e}async function Ae(e){try{const t=await X(),n=d?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const r=e.length>p*8?e.subarray(0,p*8):e,o=await d.processor(r),a=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),l=await d.model({...o,decoder_input_ids:a});let u=null,i=-1/0;for(const[c,y]of Object.entries(n.lang_to_id)){const _=Number(l.logits.data[y]);_>i&&(i=_,u=c)}return u?u.slice(2,-2):null}catch{return null}}async function J(e,{flush:t=!1}={}){if(e.closed&&!t||!e.remote&&!v()||!e.samples)return;e.lastDecodeAt=Date.now();const n=Se(e),r=Math.round((e.endSilenceMs||K)/1e3*p),o=n.length>r&&N(n,n.length-r)<$;if(N(n)<$){n.length>p*5&&(e.chunks=[n.subarray(n.length-p)],e.samples=p);return}if(!e.interims&&!t&&!o&&n.length<Q*p)return;if(!e.remote&&!e.lang&&!e.langTried&&!W(h)&&!d?.__parakeet&&n.length>=p){e.langTried=!0;const i=await Ae(n);i&&(e.lang=i,D(e,{type:"language",lang:i}))}let a="";try{if(e.remote)a=(await e.remote.transcribe(n,{lang:e.lang})).text;else{const i=W(h)?{}:{language:e.lang||void 0,task:"transcribe"},c=await d(n,i);a=String(c?.text||"").trim()}}catch(i){D(e,{type:"error",code:"decode_failed",message:i.message,fatal:!1});return}if(!a)return;const l=n.length>=Q*p,u=n.length>=_e*p;if(t||o||l||u){const i=t?"flush":o?"silence":u?"overflow":"length",c=i==="flush"||i==="silence";e.chunks=[],e.samples=0,e.lastInterim="";const y=xe(n);if(ue(a,y?y.length:0))return;let _=null;if(e.diarizer)try{const m=e.speakerLabel?null:y,S=m?await E.embed(m):null,f=!!m&&m.length<ae,F=!!m&&m.length<le;_=e.diarizer.assign(S,{pinnedLabel:e.speakerLabel,weak:f,thin:F})}catch{}D(e,{type:"final",text:a,reason:i,endOfTurn:c,durationMs:Math.round(n.length/p*1e3),..._?{speaker:_}:{}})}else a!==e.lastInterim&&(e.lastInterim=a,D(e,{type:"interim",text:a}))}async function be(e){const t=O(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(P=P.then(()=>J(t,{flush:!0}).catch(()=>{})))}finally{D(t,{type:"end"}),t.listeners.clear(),k.delete(t.id),t.diarizer&&E.release(),k.size===0&&v()&&w?.arm()}return!0}function qe(){for(const e of k.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);k.clear(),w?.disarm(),w=null,s="off",h=null,d=null,M=null,x=null,g=null}function Qe(e,t="test/fake",{warmMs:n=null,dtype:r=null}={}){d=e,h=t,s=e?"ready":"off",A=r,n!==null&&(w=H({warmMs:n,busy:b,unload:()=>C()}),e&&w.arm())}export{pe as AUTO_FETCH_MAX_MB,p as SAMPLE_RATE,le as THIN_SPEAKER_SAMPLES,ae as WEAK_SPEAKER_SAMPLES,qe as _reset,Qe as _setPipeForTest,Te as clampEndSilence,Ye as createSession,be as endSession,O as getSession,Ue as health,Oe as init,v as isReady,ue as looksHallucinated,fe as modelOnDisk,Ce as progress,We as pushAudio,L as runtimeDtype,Y as runtimeName,Be as sessionCount,Xe as setModel,he as speakerPlan,He as state,je as subscribe,Ge as toFloat32,C as unload,Ke as warmPending};
1
+ import{join as Z}from"node:path";import{existsSync as I,readdirSync as ee}from"node:fs";import{randomUUID as te}from"node:crypto";import{ensureLib as X,modelRoot as B}from"./ner-engine.js";import{runtimeDtype as L,runtimeName as Y,DTYPE_SUFFIX as ne}from"./model-runtime.js";import{verifyModelWeights as re}from"./model-integrity.js";import{DEFAULT_STT_MODEL as j,isEnglishOnly as W,sttModelDtype as R,isKnownSttModel as oe,sttModelEngine as z}from"./stt-models.js";import*as T from"./parakeet-engine.js";import*as E from"./diarize-engine.js";import{diarizeApproxMB as ie}from"./diarize-models.js";import{makeWarmTimer as H}from"./warm-timer.js";const p=16e3,ae=p,le=3*p,se=2,ce=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 ue(e,t){if(t>se*p)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?ce.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}let s="off",h=null,d=null,M=null,x=null,g=null,A=null,w=null;function fe(e=h||j,t=R(e)||L()){if(z(e)==="parakeet-tdt")return T.parakeetOnDisk(e,T.parakeetDtype(t));const n=Z(B(),...e.split("/"),"onnx");if(!I(n))return!1;const r=ne[t]??"";try{const o=ee(n);return o.includes(`encoder_model${r}.onnx`)&&o.some(a=>a===`decoder_model_merged${r}.onnx`||a===`decoder_model${r}.onnx`)}catch{return!1}}function He(){return s}function v(){return s==="ready"&&!!d}function Ce(){return g}function Ue(){return{configured:s!=="off",ok:v(),state:s,model:h,dtype:A,runtime:Y(),error:M,warmMs:w?.warmMs??null}}function Ke(){return!!w?.pending()}function b(){return k.size>0||s==="loading"||s==="downloading"}async function C({log:e=()=>{}}={}){if(b())return!1;w?.disarm();const t=d;if(d=null,x=null,A=null,g=null,M=null,s="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((w?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function G(e){return e.then(t=>(t&&!b()&&w?.arm(),t))}async function q(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(z(e)==="parakeet-tdt")return de(e,{log:t,allowDownload:n,dtype:r});const o=d,a=h;let l;try{l=await X()}catch(m){return s="error",M=`engine load failed: ${m.message}`,t(`[stt] transformers.js not available (${m.message}) — dictation falls back to the browser engine`),!1}const i=(r&&r!=="auto"?r:null)||R(e)||L(),c=fe(e,i);if(l.env.allowRemoteModels=c?!1:!!n,!c&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const y=l.env.remoteHost,_=!oe(e);if(!c&&_)try{l.env.remoteHost="https://huggingface.co/"}catch{}s=c?"loading":"downloading",c||(g={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${_?", from Hugging Face":""})…`));try{const m=f=>{if(!f)return;const F=typeof f.progress=="number"?Math.round(f.progress):g?.pct??0;f.status==="progress"||f.status==="download"||f.status==="initiate"?g={model:e,file:f.file||g?.file||null,pct:F}:f.status==="done"&&f.file&&t(`[stt] fetched ${f.file}`)};let S;try{S=await l.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:m})}catch(f){if(c||_||!n)throw f;t(`[stt] mirror fetch failed (${String(f.message).slice(0,80)}) — retrying from Hugging Face…`),l.env.remoteHost="https://huggingface.co/",l.env.allowRemoteModels=!0,S=await l.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:m})}if(!c)try{re(e,{modelsDir:B(),log:t})}catch(f){try{await S.dispose?.()}catch{}throw f}if(d=S,h=e,s="ready",M=null,g=null,A=i,o&&o!==S)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (in-process, offline) — local dictation active`),!0}catch(m){return M=m.message,g=null,o?(d=o,h=a,s="ready"):s="error",t(`[stt] model load failed (${m.message})${o?" — keeping previous model":""}`),!1}finally{try{l.env.remoteHost=y}catch{}}}async function de(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=d,a=h,l=T.parakeetDtype(r&&r!=="auto"?r:me()),u=T.parakeetOnDisk(e,l);if(!u&&!n)return s="error",M="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;s=u?"loading":"downloading",u||(g={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const i=await T.loadRecognizer({modelId:e,dtype:l,allowDownload:n,log:t,onProgress:y=>{g={model:e,file:y.file||null,pct:typeof y.pct=="number"?y.pct:g?.pct??0}}}),c=async y=>({text:await i.transcribe(y)});if(c.__parakeet=!0,c.dispose=()=>i.dispose(),d=c,h=e,s="ready",M=null,g=null,A=l,o&&o!==c)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${l} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(i){return M=i.message,g=null,o?(d=o,h=a,s="ready"):s="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}function me(){return T.PARAKEET_DEFAULT_DTYPE}const pe=30;function he({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:r=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof r=="number"&&r<=pe||e==="download"?{allowDownload:!0}:null}function U(e,{log:t=()=>{},warmMs:n}={}){const r=he({mode:e,onDisk:E.modelOnDisk(),ready:E.isReady(),approxMB:ie(E.activeModel())});r&&E.init({...r,warmMs:n,onLog:t})}function Oe(e={}){if(x)return x;const t=typeof e.onLog=="function"?e.onLog:()=>{};return h=e.model||j,s="loading",w=H({warmMs:e.warmMs,busy:b,log:t,unload:()=>C({log:t})}),x=G(q(h,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype})).then(n=>(n&&U(e.speaker,{log:t,warmMs:e.warmMs}),n)),x}async function Xe(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;const r=z(e)==="parakeet-tdt"?T.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:T.PARAKEET_DEFAULT_DTYPE):t.dtype&&t.dtype!=="auto"?t.dtype:R(e)||L();if(e===h&&v()&&A===r)return U(t.speaker,{log:n,warmMs:t.warmMs}),!0;w??=H({warmMs:t.warmMs,busy:b,log:n,unload:()=>C({log:n})});const o=await G(q(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype}));return o&&U(t.speaker,{log:n,warmMs:t.warmMs}),o}const ge=4,ye=6e4,we=1200,Q=12,K=700,$=.008,_e=30,k=new Map;let P=Promise.resolve();function Be(){return k.size}const Me=300,ke=3e3;function Te(e){const t=Number(e);return Number.isFinite(t)?Math.min(ke,Math.max(Me,Math.round(t))):K}function Ye({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=K,interims:a=!0,remote:l=null}={}){if(k.size>=ge){const i=new Error("too many concurrent dictation sessions");throw i.code="too_many_sessions",i}const u={id:te(),endSilenceMs:Te(o),lang:typeof e=="string"&&e?e.slice(0,12):null,langTried:!1,redact:!!t,diarize:!!n,speakerLabel:typeof r=="string"&&r?r.slice(0,40):null,diarizer:n?new E.Diarizer:null,remote:l||null,interims:a!==!1&&!l,chunks:[],samples:0,listeners:new Set,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return k.set(u.id,u),w?.disarm(),u.diarizer&&E.retain(),V(u),{id:u.id}}function O(e){return k.get(String(e||""))||null}function je(e,t){const n=O(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function D(e,t){for(const n of e.listeners)try{n(t)}catch{}}function V(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>be(e.id).catch(()=>{}),ye),e.idleTimer.unref?.()}function We(e,t){const n=O(e);if(!n||n.closed){const r=new Error("no such session");throw r.code="no_session",r}!(t instanceof Float32Array)||!t.length||(n.chunks.push(t),n.samples+=t.length,V(n),Ee(n))}function Ge(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let r=0;r<n.length;r++)n[r]=e.readFloatLE(r*4);return n}function Ee(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+we-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,P=P.then(()=>J(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function Se(e){const t=new Float32Array(e.samples);let n=0;for(const r of e.chunks)t.set(r,n),n+=r.length;return t}function N(e,t=0,n=e.length){let r=0;const o=Math.max(1,n-t);for(let a=t;a<n;a++)r+=e[a]*e[a];return Math.sqrt(r/o)}function xe(e){const t=Math.round(.02*p);let n=0,r=e.length;for(let o=0;o+t<=e.length;o+=t)if(N(e,o,o+t)>=$){n=o;break}for(let o=e.length-t;o>=0;o-=t)if(N(e,o,o+t)>=$){r=o+t;break}return r>n?e.subarray(n,r):e}async function Ae(e){try{const t=await X(),n=d?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const r=e.length>p*8?e.subarray(0,p*8):e,o=await d.processor(r),a=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),l=await d.model({...o,decoder_input_ids:a});let u=null,i=-1/0;for(const[c,y]of Object.entries(n.lang_to_id)){const _=Number(l.logits.data[y]);_>i&&(i=_,u=c)}return u?u.slice(2,-2):null}catch{return null}}async function J(e,{flush:t=!1}={}){if(e.closed&&!t||!e.remote&&!v()||!e.samples)return;e.lastDecodeAt=Date.now();const n=Se(e),r=Math.round((e.endSilenceMs||K)/1e3*p),o=n.length>r&&N(n,n.length-r)<$;if(N(n)<$){n.length>p*5&&(e.chunks=[n.subarray(n.length-p)],e.samples=p);return}if(!e.interims&&!t&&!o&&n.length<Q*p)return;if(!e.remote&&!e.lang&&!e.langTried&&!W(h)&&!d?.__parakeet&&n.length>=p){e.langTried=!0;const i=await Ae(n);i&&(e.lang=i,D(e,{type:"language",lang:i}))}let a="";try{if(e.remote)a=(await e.remote.transcribe(n,{lang:e.lang})).text;else{const i=W(h)?{}:{language:e.lang||void 0,task:"transcribe"},c=await d(n,i);a=String(c?.text||"").trim()}}catch(i){D(e,{type:"error",code:"decode_failed",message:i.message,fatal:!1});return}if(!a)return;const l=n.length>=Q*p,u=n.length>=_e*p;if(t||o||l||u){const i=t?"flush":o?"silence":u?"overflow":"length",c=i==="flush"||i==="silence";e.chunks=[],e.samples=0,e.lastInterim="";const y=xe(n);if(ue(a,y?y.length:0))return;let _=null;if(e.diarizer)try{const m=e.speakerLabel?null:y,S=m?await E.embed(m):null,f=!!m&&m.length<ae,F=!!m&&m.length<le;_=e.diarizer.assign(S,{pinnedLabel:e.speakerLabel,weak:f,thin:F})}catch{}D(e,{type:"final",text:a,reason:i,endOfTurn:c,durationMs:Math.round(n.length/p*1e3),..._?{speaker:_}:{}})}else a!==e.lastInterim&&(e.lastInterim=a,D(e,{type:"interim",text:a}))}async function be(e){const t=O(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(P=P.then(()=>J(t,{flush:!0}).catch(()=>{})))}finally{D(t,{type:"end"}),t.listeners.clear(),k.delete(t.id),t.diarizer&&E.release(),k.size===0&&v()&&w?.arm()}return!0}function qe(){for(const e of k.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);k.clear(),w?.disarm(),w=null,s="off",h=null,d=null,M=null,x=null,g=null}function Qe(e,t="test/fake",{warmMs:n=null,dtype:r=null}={}){d=e,h=t,s=e?"ready":"off",A=r,n!==null&&(w=H({warmMs:n,busy:b,unload:()=>C()}),e&&w.arm())}export{pe as AUTO_FETCH_MAX_MB,p as SAMPLE_RATE,le as THIN_SPEAKER_SAMPLES,ae as WEAK_SPEAKER_SAMPLES,qe as _reset,Qe as _setPipeForTest,Te as clampEndSilence,Ye as createSession,be as endSession,O as getSession,Ue as health,Oe as init,v as isReady,ue as looksHallucinated,fe as modelOnDisk,Ce as progress,We as pushAudio,L as runtimeDtype,Y as runtimeName,Be as sessionCount,Xe as setModel,he as speakerPlan,He as state,je as subscribe,Ge as toFloat32,C as unload,Ke as warmPending};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.57.2";export{o as VERSION};
1
+ const o="0.57.4";export{o as VERSION};