@chatpanel/gateway 0.119.0 → 0.121.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.119.0",
3
+ "version": "0.121.0",
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": {
@@ -15,17 +15,16 @@
15
15
  "bin",
16
16
  "gateway.config.example.json",
17
17
  "LICENSE",
18
- "README.md",
19
- "native/darwin-arm64"
18
+ "README.md"
20
19
  ],
21
20
  "engines": {
22
21
  "node": ">=22.13"
23
22
  },
24
23
  "dependencies": {
25
24
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
26
- "@chatpanel/bridge": "^0.47.0",
27
- "@chatpanel/events": "^0.392.0",
28
- "@chatpanel/pii": "^0.15.0",
25
+ "@chatpanel/bridge": "^0.48.0",
26
+ "@chatpanel/events": "^0.400.0",
27
+ "@chatpanel/pii": "^0.15.6",
29
28
  "@huggingface/transformers": "^4.2.0",
30
29
  "defuddle": "^0.19.4",
31
30
  "fflate": "^0.8.3",
@@ -1 +1 @@
1
- import{modelFetch as Q}from"./model-sources.js";import{existsSync as z,readFileSync as Z,mkdirSync as V,createWriteStream as ee,createReadStream as te,renameSync as ne,rmSync as U}from"node:fs";import{createHash as re}from"node:crypto";import{join as A}from"node:path";import{modelRoot as oe}from"./ner-engine.js";import{getOrt as ce,ortProviders as ae,rawOrtAvailable as se}from"./ort.js";import{fft as ie}from"./aec-engine.js";import{INDIC_LICENSE as M,licenseAcceptance as fe}from"./stt-models.js";const $e="bodhan-ai/indic-transcribe-core",de=fe(M);function $(){return A(oe(),"bodhan-ai","indic-transcribe-core-int8")}const le="https://huggingface.co/ChatPanel/indic-transcribe-core-int8/resolve/main",D=Object.freeze({"encoder.onnx":"fa49d702bf83d52327105736ded11aea2e6afcfcb1667182e6db36e5cc27f097","encoder.onnx.data":"66c3442b950a3ff5e18fc33db1d15069b7888235776bdc86824d6f99d728f9a5","cross_kv.onnx":"0aed59ffef5e77e2b957d42f742ea2645fed3ac49954b6a91dc8e629d7196c26","cross_kv.onnx.data":"022d88763437e56ac1156b3953c68a01c205b52627094a086d243b822f6e810b","decoder.onnx":"f858a610f1d3498a993d5eb0424ef888d96edc853be3b7aa32846b237d2c4a97","decoder.onnx.data":"c557a469b426ad424b0ed04c7422df44fc12131df2ae300b3f4bc92bdf50d05b","mel_fb_128x257.f32":"586bbdf62da6485f02faecb278f781277fab9537558a57d611bf2fc35e12452b","window_400.f32":"cb9f40f78ef078b89ba969960015aa5e5a833e0c549e9dcdb532d9defbb418d2","vocab.json":"894a3b8761a73dec92577e7ef1664d1357fdee6008a598add2c9006423d3c79d","LICENSE.md":"b39f2a9cb2d5ace3a03f4425cbc6db38ebd9a53ab7a7648d67dc1e0998ad75c2"});function q(){return Object.keys(D).every(a=>z(A($(),a)))}const G=a=>new Promise((o,s)=>{const i=re("sha256");te(a).on("data",b=>i.update(b)).on("error",s).on("end",()=>o(i.digest("hex")))});async function De({licenseAccepted:a=null,onProgress:o=()=>{},log:s=()=>{},fetchImpl:i=Q()}={}){if(q())return $();if(a!==de){const x=new Error(`Indic-Transcribe is downloaded only after its licence (${M.name}) is accepted`);throw x.code="license_required",x}const b=$();V(b,{recursive:!0});const d=Object.keys(D);for(const[x,u]of d.entries()){const y=A(b,u);if(z(y))continue;const g=await i(`${le}/${u}`);if(!g.ok||!g.body)throw new Error(`${u}: HTTP ${g.status}`);const f=Number(g.headers.get("content-length"))||0,v=`${y}.part`;if(await new Promise((w,r)=>{const h=ee(v),n=g.body.getReader();let e=0;const c=()=>n.read().then(({done:t,value:p})=>{if(t){h.end(w);return}e+=p.length,f&&o({file:u,pct:Math.round((x+e/f)/d.length*100)}),h.write(Buffer.from(p)),c()},r);h.on("error",r),c()}),await G(v)!==D[u])throw U(v,{force:!0}),new Error(`${u} does not match its pinned hash — not used`);ne(v,y),s(`[indic] fetched ${u}`)}return b}const P=16e3,C=512,W=160,J=400,L=128,T=C/2+1,be=.97,pe=2**-24,me=1e-5,we=24,he=8,ue=128,K=new Set,X=3;function ge(a,{fb:o,window:s}){const i=a.length,b=new Float32Array(i);b[0]=a[0]||0;for(let r=1;r<i;r++)b[r]=a[r]-be*a[r-1];const d=Math.floor(i/W)+1,x=C/2,u=r=>(r<0&&(r=-r),r>=i&&(r=2*(i-1)-r),b[Math.max(0,Math.min(i-1,r))]),y=(C-J)/2,g=new Float64Array(C),f=new Float64Array(C),v=new Float64Array(T),w=new Float32Array(L*d);for(let r=0;r<d;r++){const h=r*W-x;for(let n=0;n<C;n++){const e=n>=y&&n<y+J?s[n-y]:0;g[n]=e?u(h+n)*e:0,f[n]=0}ie(g,f);for(let n=0;n<T;n++)v[n]=g[n]*g[n]+f[n]*f[n];for(let n=0;n<L;n++){let e=0;const c=n*T;for(let t=0;t<T;t++)e+=o[c+t]*v[t];w[n*d+r]=Math.log(e+pe)}}for(let r=0;r<L;r++){const h=r*d;let n=0;for(let t=0;t<d;t++)n+=w[h+t];n/=d;let e=0;for(let t=0;t<d;t++)e+=(w[h+t]-n)**2;const c=Math.sqrt(e/Math.max(1,d-1))+me;for(let t=0;t<d;t++)w[h+t]=(w[h+t]-n)/c}return{data:w,frames:d}}function _e(a){return String(a||"").replace(/\b[A-Z][A-Z']*(?:[\s,.!?;:-]+[A-Z][A-Z']*){2,}\b/g,o=>o.toLowerCase().replace(/\bi\b/g,"I").replace(/\bi'(m|ll|ve|d)\b/g,(i,b)=>`I'${b}`).replace(/(^|[.!?]\s+)([a-z])/g,(i,b,d)=>b+d.toUpperCase())).replace(/(^|[.!?]\s+)([a-z])/,(o,s,i)=>/[A-Z]{3}/.test(a)?s+i.toUpperCase():o)}const ye=/\b(do|does|did|is|are|was|were|ca|could|would|should|wo|have|has|had|ai|must|need)n t\b/gi,Ie=[[ye,(a,o)=>`${o}n't`],[/\b(can) t\b/gi,(a,o)=>`${o}'t`],[/\b(it|that|what|there|here|let|he|she|who|where|how|everyone|nobody) s\b/gi,(a,o)=>`${o}'s`],[/\b(I) (m)\b/g,()=>"I'm"],[/\b(I|you|we|they) (ll|ve|d)\b/gi,(a,o,s)=>`${o}'${s}`],[/\b(you|we|they) re\b/gi,(a,o)=>`${o}'re`]];function xe(a){let o=String(a||"");for(const[s,i]of Ie)o=o.replace(s,i);return o}function ve(a,o){return a.map(s=>o[s]??"").join("").replace(/▁/g," ").trim()}async function Le({sessionOptions:a=null,log:o=()=>{}}={}){if(!se())throw new Error("Indic-Transcribe needs the npm gateway (the standalone binary cannot run it)");if(!q())throw new Error("Indic-Transcribe is not downloaded");const s=$();for(const[e,c]of Object.entries(D))if(!K.has(e)){if(await G(A(s,e))!==c)throw U(A(s,e),{force:!0}),new Error(`${e} changed on disk — removed`);K.add(e)}const i=await ce(),b={executionProviders:ae(),graphOptimizationLevel:"all",logSeverityLevel:3,...a||{}},[d,x,u]=await Promise.all(["encoder","cross_kv","decoder"].map(e=>i.InferenceSession.create(A(s,`${e}.onnx`),b))),y=e=>{const c=Z(A(s,e));return new Float32Array(c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength))},g={fb:y("mel_fb_128x257.f32"),window:y("window_400.f32")},f=JSON.parse(Z(A(s,"vocab.json"),"utf8")),v=new Set(f.eos),w=i.Tensor;o("[indic] ready — Indic-Transcribe-core (int8, in-process, offline)");async function r(e,c,t){const p=await u.run({ids:new w("int64",BigInt64Array.from([BigInt(c)]),[1,1]),pos:new w("int64",BigInt64Array.from([BigInt(t)]),[1]),self_k:e.k,self_v:e.v,cross_k:e.ck,cross_v:e.cv});return e.k=p.new_self_k,e.v=p.new_self_v,p.logits.data}async function h(e){const{data:c,frames:t}=ge(e,g),p=(await d.run({features:new w("float32",c,[1,L,t])})).states,S=await x.run({states:p}),E=new w("float32",new Float32Array(0),[we,1,he,0,ue]),l={k:E,v:E,ck:S.cross_k,cv:S.cross_v},_=f.prompt_te.slice();let F=null;for(let I=0;I<X;I++)F=await r(l,_[I],I);return{st:l,prompt:_,logits:F}}function n(e,c){const t=(c&&c.length?c:Object.keys(f.lang_ids)).filter(l=>f.lang_ids[l]!=null);let p=-1/0;for(const l of t)p=Math.max(p,e[f.lang_ids[l]]);let S=0;const E={};for(const l of t)E[l]=Math.exp(e[f.lang_ids[l]]-p),S+=E[l];return t.map(l=>[l,E[l]/S]).sort((l,_)=>_[1]-l[1])}return{vocab:f,async identify(e,{langs:c=[]}={}){if(!(e instanceof Float32Array)||e.length<P/4)return{lang:null,confidence:0,scores:{}};const t=n((await h(e)).logits,c);return t.length?{lang:t[0][0],confidence:t[0][1],scores:Object.fromEntries(t)}:{lang:null,confidence:0,scores:{}}},async transcribe(e,{lang:c=null,langs:t=[],last:p=null,maxNew:S=256,choose:E=null}={}){if(!(e instanceof Float32Array)||e.length<P/4)return{text:"",lang:c,confidence:0};const{st:l,prompt:_,logits:F}=await h(e);let I=null,O=c,R=1;if(!O){const m=n(F,t),k=Object.fromEntries(m);O=(E&&m.length?E(k,e.length/P):null)||m[0]?.[0]||p||"en",R=k[O]??0}const Y=f.lang_ids[O]??f.lang_ids.en;_[3]=_[4]=Y;for(let m=X;m<_.length;m++)I=await r(l,_[m],m);const j=[];for(let m=_.length;m<_.length+S;m++){let k=0,H=-1/0;for(let N=0;N<I.length;N++)I[N]>H&&(H=I[N],k=N);if(v.has(k))break;j.push(k),I=await r(l,k,m)}const B=_e(ve(j.filter(m=>!f.timestamp_ids.includes(m)),f.pieces));return{text:O==="en"?xe(B):B,lang:O,confidence:R}},async dispose(){for(const e of[d,x,u])try{await e.release?.()}catch{}}}}export{D as INDIC_FILES,M as INDIC_LICENSE,de as INDIC_LICENSE_ACCEPTANCE,$e as INDIC_MODEL_ID,le as INDIC_SOURCE,P as SAMPLE_RATE,ve as decodeIds,De as ensureIndicFiles,$ as indicDir,q as indicOnDisk,Le as loadRecognizer,ge as melFeatures,xe as restoreApostrophes,_e as restoreCase};
1
+ import{modelFetch as ee}from"./model-sources.js";import{existsSync as U,readFileSync as q,mkdirSync as te,createWriteStream as ne,createReadStream as re,renameSync as oe,rmSync as G}from"node:fs";import{createHash as ce}from"node:crypto";import{join as C}from"node:path";import{modelRoot as se}from"./ner-engine.js";import{getOrt as ae,ortProviders as ie,rawOrtAvailable as fe}from"./ort.js";import{fft as de}from"./aec-engine.js";import{INDIC_LICENSE as z,licenseAcceptance as le}from"./stt-models.js";const Le="bodhan-ai/indic-transcribe-core",be=le(z);function L(){return C(se(),"bodhan-ai","indic-transcribe-core-int8")}const pe="https://huggingface.co/ChatPanel/indic-transcribe-core-int8/resolve/main",P=Object.freeze({"encoder.onnx":"fa49d702bf83d52327105736ded11aea2e6afcfcb1667182e6db36e5cc27f097","encoder.onnx.data":"66c3442b950a3ff5e18fc33db1d15069b7888235776bdc86824d6f99d728f9a5","cross_kv.onnx":"0aed59ffef5e77e2b957d42f742ea2645fed3ac49954b6a91dc8e629d7196c26","cross_kv.onnx.data":"022d88763437e56ac1156b3953c68a01c205b52627094a086d243b822f6e810b","decoder.onnx":"f858a610f1d3498a993d5eb0424ef888d96edc853be3b7aa32846b237d2c4a97","decoder.onnx.data":"c557a469b426ad424b0ed04c7422df44fc12131df2ae300b3f4bc92bdf50d05b","mel_fb_128x257.f32":"586bbdf62da6485f02faecb278f781277fab9537558a57d611bf2fc35e12452b","window_400.f32":"cb9f40f78ef078b89ba969960015aa5e5a833e0c549e9dcdb532d9defbb418d2","vocab.json":"894a3b8761a73dec92577e7ef1664d1357fdee6008a598add2c9006423d3c79d","LICENSE.md":"b39f2a9cb2d5ace3a03f4425cbc6db38ebd9a53ab7a7648d67dc1e0998ad75c2"});function W(){return Object.keys(P).every(r=>U(C(L(),r)))}const X=r=>new Promise((o,i)=>{const s=ce("sha256");re(r).on("data",l=>s.update(l)).on("error",i).on("end",()=>o(s.digest("hex")))});async function Pe({licenseAccepted:r=null,onProgress:o=()=>{},log:i=()=>{},fetchImpl:s=ee()}={}){if(W())return L();if(r!==be){const A=new Error(`Indic-Transcribe is downloaded only after its licence (${z.name}) is accepted`);throw A.code="license_required",A}const l=L();te(l,{recursive:!0});const a=Object.keys(P);for(const[A,g]of a.entries()){const I=C(l,g);if(U(I))continue;const _=await s(`${pe}/${g}`);if(!_.ok||!_.body)throw new Error(`${g}: HTTP ${_.status}`);const f=Number(_.headers.get("content-length"))||0,S=`${I}.part`;if(await new Promise((u,c)=>{const w=ne(S),n=_.body.getReader();let h=0;const e=()=>n.read().then(({done:t,value:b})=>{if(t){w.end(u);return}h+=b.length,f&&o({file:g,pct:Math.round((A+h/f)/a.length*100)}),w.write(Buffer.from(b)),e()},c);w.on("error",c),e()}),await X(S)!==P[g])throw G(S,{force:!0}),new Error(`${g} does not match its pinned hash — not used`);oe(S,I),i(`[indic] fetched ${g}`)}return l}const M=16e3,F=512,J=160,K=400,T=128,j=F/2+1,he=.97,me=2**-24,ue=1e-5,we=24,ge=8,_e=128,Y=new Set,Q=3,R=80;function ye(r,o=R*M){const i=Math.max(1,Math.ceil(r/o)),s=Math.ceil(r/i),l=[];for(let a=0;a<r;a+=s)l.push([a,Math.min(r,a+s)]);return l}function xe(r,{fb:o,window:i}){const s=r.length,l=new Float32Array(s);l[0]=r[0]||0;for(let c=1;c<s;c++)l[c]=r[c]-he*r[c-1];const a=Math.floor(s/J)+1,A=F/2,g=c=>(c<0&&(c=-c),c>=s&&(c=2*(s-1)-c),l[Math.max(0,Math.min(s-1,c))]),I=(F-K)/2,_=new Float64Array(F),f=new Float64Array(F),S=new Float64Array(j),u=new Float32Array(T*a);for(let c=0;c<a;c++){const w=c*J-A;for(let n=0;n<F;n++){const h=n>=I&&n<I+K?i[n-I]:0;_[n]=h?g(w+n)*h:0,f[n]=0}de(_,f);for(let n=0;n<j;n++)S[n]=_[n]*_[n]+f[n]*f[n];for(let n=0;n<T;n++){let h=0;const e=n*j;for(let t=0;t<j;t++)h+=o[e+t]*S[t];u[n*a+c]=Math.log(h+me)}}for(let c=0;c<T;c++){const w=c*a;let n=0;for(let t=0;t<a;t++)n+=u[w+t];n/=a;let h=0;for(let t=0;t<a;t++)h+=(u[w+t]-n)**2;const e=Math.sqrt(h/Math.max(1,a-1))+ue;for(let t=0;t<a;t++)u[w+t]=(u[w+t]-n)/e}return{data:u,frames:a}}function Ie(r){return String(r||"").replace(/\b[A-Z][A-Z']*(?:[\s,.!?;:-]+[A-Z][A-Z']*){2,}\b/g,o=>o.toLowerCase().replace(/\bi\b/g,"I").replace(/\bi'(m|ll|ve|d)\b/g,(s,l)=>`I'${l}`).replace(/(^|[.!?]\s+)([a-z])/g,(s,l,a)=>l+a.toUpperCase())).replace(/(^|[.!?]\s+)([a-z])/,(o,i,s)=>/[A-Z]{3}/.test(r)?i+s.toUpperCase():o)}const ve=/\b(do|does|did|is|are|was|were|ca|could|would|should|wo|have|has|had|ai|must|need)n t\b/gi,Ee=[[ve,(r,o)=>`${o}n't`],[/\b(can) t\b/gi,(r,o)=>`${o}'t`],[/\b(it|that|what|there|here|let|he|she|who|where|how|everyone|nobody) s\b/gi,(r,o)=>`${o}'s`],[/\b(I) (m)\b/g,()=>"I'm"],[/\b(I|you|we|they) (ll|ve|d)\b/gi,(r,o,i)=>`${o}'${i}`],[/\b(you|we|they) re\b/gi,(r,o)=>`${o}'re`]];function Ae(r){let o=String(r||"");for(const[i,s]of Ee)o=o.replace(i,s);return o}function Se(r,o){return r.map(i=>o[i]??"").join("").replace(/▁/g," ").trim()}async function Te({sessionOptions:r=null,log:o=()=>{}}={}){if(!fe())throw new Error("Indic-Transcribe needs the npm gateway (the standalone binary cannot run it)");if(!W())throw new Error("Indic-Transcribe is not downloaded");const i=L();for(const[e,t]of Object.entries(P))if(!Y.has(e)){if(await X(C(i,e))!==t)throw G(C(i,e),{force:!0}),new Error(`${e} changed on disk — removed`);Y.add(e)}const s=await ae(),l={executionProviders:ie(),graphOptimizationLevel:"all",logSeverityLevel:3,...r||{}},[a,A,g]=await Promise.all(["encoder","cross_kv","decoder"].map(e=>s.InferenceSession.create(C(i,`${e}.onnx`),l))),I=e=>{const t=q(C(i,e));return new Float32Array(t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength))},_={fb:I("mel_fb_128x257.f32"),window:I("window_400.f32")},f=JSON.parse(q(C(i,"vocab.json"),"utf8")),S=new Set(f.eos),u=s.Tensor;o("[indic] ready — Indic-Transcribe-core (int8, in-process, offline)");async function c(e,t,b){const m=await g.run({ids:new u("int64",BigInt64Array.from([BigInt(t)]),[1,1]),pos:new u("int64",BigInt64Array.from([BigInt(b)]),[1]),self_k:e.k,self_v:e.v,cross_k:e.ck,cross_v:e.cv});return e.k=m.new_self_k,e.v=m.new_self_v,m.logits.data}async function w(e){const{data:t,frames:b}=xe(e.length>R*M?e.subarray(0,R*M):e,_),m=(await a.run({features:new u("float32",t,[1,T,b])})).states,O=await A.run({states:m}),v=new u("float32",new Float32Array(0),[we,1,ge,0,_e]),p={k:v,v,ck:O.cross_k,cv:O.cross_v},y=f.prompt_te.slice();let $=null;for(let E=0;E<Q;E++)$=await c(p,y[E],E);return{st:p,prompt:y,logits:$}}function n(e,t){const b=(t&&t.length?t:Object.keys(f.lang_ids)).filter(p=>f.lang_ids[p]!=null);let m=-1/0;for(const p of b)m=Math.max(m,e[f.lang_ids[p]]);let O=0;const v={};for(const p of b)v[p]=Math.exp(e[f.lang_ids[p]]-m),O+=v[p];return b.map(p=>[p,v[p]/O]).sort((p,y)=>y[1]-p[1])}return{vocab:f,async identify(e,{langs:t=[]}={}){if(!(e instanceof Float32Array)||e.length<M/4)return{lang:null,confidence:0,scores:{}};const b=n((await w(e)).logits,t);return b.length?{lang:b[0][0],confidence:b[0][1],scores:Object.fromEntries(b)}:{lang:null,confidence:0,scores:{}}},transcribe:h,async dispose(){for(const e of[a,A,g])try{await e.release?.()}catch{}}};async function h(e,{lang:t=null,langs:b=[],last:m=null,maxNew:O=256,choose:v=null}={}){if(!(e instanceof Float32Array)||e.length<M/4)return{text:"",lang:t,confidence:0};if(e.length>R*M){const d=[];for(const[x,D]of ye(e.length)){const k=await h(e.subarray(x,D),{lang:t,langs:b,last:m,maxNew:O,choose:v});k.text&&d.push(k),m=k.lang||m}return{text:d.map(x=>x.text).join(" "),lang:d[0]?.lang??t,confidence:d[0]?.confidence??0}}const{st:p,prompt:y,logits:$}=await w(e);let E=null,N=t,B=1;if(!N){const d=n($,b),x=Object.fromEntries(d);N=(v&&d.length?v(x,e.length/M):null)||d[0]?.[0]||m||"en",B=x[N]??0}const V=f.lang_ids[N]??f.lang_ids.en;y[3]=y[4]=V;for(let d=Q;d<y.length;d++)E=await c(p,y[d],d);const H=[];for(let d=y.length;d<y.length+O;d++){let x=0,D=-1/0;for(let k=0;k<E.length;k++)E[k]>D&&(D=E[k],x=k);if(S.has(x))break;H.push(x),E=await c(p,x,d)}const Z=Ie(Se(H.filter(d=>!f.timestamp_ids.includes(d)),f.pieces));return{text:N==="en"?Ae(Z):Z,lang:N,confidence:B}}}export{P as INDIC_FILES,z as INDIC_LICENSE,be as INDIC_LICENSE_ACCEPTANCE,Le as INDIC_MODEL_ID,pe as INDIC_SOURCE,R as MAX_SECONDS,M as SAMPLE_RATE,Se as decodeIds,Pe as ensureIndicFiles,L as indicDir,W as indicOnDisk,Te as loadRecognizer,xe as melFeatures,Ae as restoreApostrophes,Ie as restoreCase,ye as windowPieces};
package/src/ner-engine.js CHANGED
@@ -1 +1 @@
1
- import q from"node:os";import{join as S}from"node:path";import{existsSync as K,mkdirSync as ft,readdirSync as V,readFileSync as pt}from"node:fs";import{DEFAULT_MODEL as X,isMirroredModel as dt}from"./models.js";import{isLoopbackHost as ht,isPrivateHost as mt,isMetadataHost as gt}from"@chatpanel/pii";import{recaseForDetection as yt}from"@chatpanel/pii/pii-detect.js";import{recasedSpanOk as wt}from"@chatpanel/pii/recased-spans.js";import{verifyModelWeights as _t}from"./model-integrity.js";import{runtimeName as Mt}from"./model-runtime.js";import{nativeOrtFailure as xt}from"./ort.js";import{makeWarmTimer as Z}from"./warm-timer.js";import{makeModelFileCache as bt}from"./model-file-cache.js";import{modelFetch as Lt}from"./model-sources.js";import{onLane as Tt}from"./inference-lane.js";const C="https://huggingface.co/";function At(t=process.env){const e=t.CHATPANEL_MODEL_BASE_URL?"CHATPANEL_MODEL_BASE_URL":"registries.models",r=t.CHATPANEL_MODEL_BASE_URL||t.CHATPANEL_REGISTRY_MODELS;if(!r)return C;const n=l=>(console.warn(`[models] ignoring ${e} (${r}): ${l} — using ${C}`),C);let o;try{o=new URL(r)}catch{return n("not a valid URL")}if(o.protocol!=="http:"&&o.protocol!=="https:")return n(`scheme ${o.protocol} not allowed`);if(gt(o.hostname))return n("points at cloud metadata");const s=ht(o.hostname)||mt(o.hostname);return o.protocol==="http:"&&!s?n("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${o.origin} (${e}), not ${C}`),r.replace(/\/*$/,"/"))}const I=At();let h="off",y=null,w=null,b=null,T=null,E=null,L=null,m=null,M=null,N=0,H=null;const g=new Map;let tt=Promise.resolve();function oe({host:t=null,allowRemote:e=!1}={},r){const n=tt.then(async()=>{const o=await z(),s=o.env.remoteHost,l=o.env.allowRemoteModels;try{o.env.allowRemoteModels=e,t&&(o.env.remoteHost=t)}catch{}try{return await r(o)}finally{try{o.env.remoteHost=s,o.env.allowRemoteModels=l}catch{}}});return tt=n.catch(()=>{}),n}function P(){return process.env.CHATPANEL_MODELS_DIR||S(q.homedir(),".chatpanel","models")}function R(t=y||X){const e=S(P(),...t.split("/"));return K(S(e,"onnx","model_quantized.onnx"))||K(S(e,"onnx","model.onnx"))}function re(){const t=P(),e=[];try{for(const r of V(t,{withFileTypes:!0}))if(r.isDirectory())for(const n of V(S(t,r.name),{withFileTypes:!0})){if(!n.isDirectory())continue;const o=`${r.name}/${n.name}`;R(o)&&St(S(t,r.name,n.name))&&e.push(o)}}catch{}return e}function St(t){try{return(JSON.parse(pt(S(t,"config.json"),"utf8")).architectures||[]).some(r=>/ForTokenClassification$/.test(String(r)))}catch{return!1}}function se(){return h}function O(){return h==="ready"&&!!w}function ie(){return{configured:h!=="off",ok:O(),state:h,model:y,error:b,runtime:Mt(),dtype:w?"q8":null,stats:Ft(),companions:Et(),warmMs:M?.warmMs??null}}async function Ot(t,{signal:e,strict:r=!1}={}){if(!O())return[];if(e?.aborted)return[];const n=String(t||""),o=await et(n,e);if(!o)return[];const s=[];for(const f of o||[]){if(nt(f,r))continue;let a=String(f.word??"");const u=f.entity_group??f.entity??"ENTITY";if(a.startsWith("##")&&s.length&&s[s.length-1].type===u){s[s.length-1].value+=a.slice(2);continue}a=a.replace(/##/g,"").trim(),a&&s.push({value:a,type:u})}const l=new Set,c=[];for(const f of s){const a=Wt(n,Dt(n,f.value.trim()));if(a.length<=1)continue;const u=`${f.type}:${a.toLowerCase()}`;l.has(u)||(l.add(u),c.push({value:a,type:f.type}))}return c}async function et(t,e){N++;try{return await vt(t,e)}finally{N--,$()||M?.arm()}}async function vt(t,e){const r=performance.now(),n=[],o=[{text:t,key:"orig"}];if(F){const s=yt(t);s.changed&&o.push({text:s.text,key:"recased"})}for(const{model:s,pipe:l}of st())for(const c of o){let f=0;for(const a of Nt(c.text,l.tokenizer)){if(e?.aborted)return null;const u=c.text.indexOf(a,f),d=await Tt(()=>l(a,{aggregation_strategy:"simple"}));for(const i of d||[])n.push({...i,_win:u<0?f:u,_winText:a,_model:s,_pass:c.key,_passText:c.text});u>=0&&(f=Math.max(f,u+1))}}return Rt(performance.now()-r,t.length,n.length),n}let F=!0;function ae(t){F=t!==!1}const nt=(t,e)=>!e&&t._pass==="recased"&&!wt(String(t.word??"").replace(/##/g,""),t.entity_group??t.entity);async function le(t,{signal:e,strict:r=!1}={}){if(!O())return[];const n=String(t||""),o=await et(n,e);if(!o)return[];const s=[],l=new Set;let c=-1,f=-1,a=null,u=null;for(const i of o){if(nt(i,r))continue;const p=String(i.word??"").replace(/##/g,"").trim();if(!p)continue;(i._win!==f||i._model!==a||i._pass!==u)&&(f=i._win,a=i._model,u=i._pass,c=i._win);const v=i._passText||n;let x=v.indexOf(p,c);if(x<0&&(x=v.indexOf(p,i._win)),x<0)continue;let A=x+p.length;c=A;const Y=Q=>!!Q&&/[\p{L}\p{N}'’-]/u.test(Q);for(;x>0&&Y(n[x-1]);)x--;for(;A<n.length&&Y(n[A]);)A++;const B=String(i.entity_group??i.entity??"ENTITY"),J=`${x}:${A}:${B}`;if(l.has(J))continue;l.add(J);const G=Number(i.score);s.push({value:n.slice(x,A),type:B,start:x,end:A,score:Number.isFinite(G)?Math.max(0,Math.min(1,G)):1,model:i._model})}s.sort((i,p)=>i.start-p.start||i.end-p.end);const d=[];for(const i of s){const p=d[d.length-1];if(p&&p.type===i.type&&p.end===i.start){p.end=i.end,p.value=n.slice(p.start,p.end),p.score=Math.min(p.score,i.score);continue}d.push({...i})}return g.size||F?Ct(d):d}const ot=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function kt(t){const e=String(t).toLowerCase();return/secret|password|key/.test(e)?"secret":/ssn|social/.test(e)?"ssn":/card/.test(e)?"card":/iban/.test(e)?"iban":/account/.test(e)?"account":/^id|num|username|passport|licen|url|date|imei|ip$|mac$/.test(e)?"id":/email/.test(e)?"email":/phone|tel/.test(e)?"phone":/address|street|zip|post|building/.test(e)?"address":/per|name|person/.test(e)?"person":/org|company/.test(e)?"org":"loc"}function D(t){const e=ot.indexOf(kt(t.type));return e<0?ot.length:e}let k=[];function $t(t){k=Array.isArray(t)?t.slice():[],m&&(m={...m,union:k.slice()})}function W(t){if(t.model===y)return-1;const e=k.indexOf(t.model);return e<0?k.length:e}function Ct(t){const e=[...t].sort((n,o)=>n.start-o.start||o.end-n.end),r=[];for(const n of e){const o=r[r.length-1];if(o&&n.start<o.end){const s=c=>c.end-c.start;(D(n)<D(o)||D(n)===D(o)&&(s(n)>s(o)||s(n)===s(o)&&(W(n)<W(o)||W(n)===W(o)&&n.score>o.score)))&&(r[r.length-1]=n);continue}r.push(n)}return r}function ce(){const t=w?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const r of Object.values(t)){const n=String(r).replace(/^[BIES]-/,"");n&&n!=="O"&&e.add(n)}return[...e]}function ue(){const t=Number(w?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function Et(){return[...g].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function rt(t,{log:e=()=>{},allowDownload:r=!0}={}){if(!t||t===y)return!1;if(g.get(t)?.pipe)return!0;g.set(t,{pipe:null,state:R(t)?"loading":"downloading",error:null});try{const{pipe:o}=await at(t,{log:e,allowDownload:r});return g.set(t,{pipe:o,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(o){return g.set(t,{pipe:null,state:"error",error:o.message}),e(`[ner] companion ${t} failed to load (${o.message}) — the union runs without it`),!1}}async function fe(t){const e=g.get(t);if(!e)return!1;g.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function st(){const t=w?[{model:y,pipe:w}]:[];for(const[e,r]of g)r.pipe&&t.push({model:e,pipe:r.pipe});return t}const Ht=160,it=256;function Nt(t,e){if(!t||typeof e!="function")return[t];const r=Number(e.model_max_length),o=Math.min(it,Number.isFinite(r)&&r>0?r:it)-8,s=a=>{try{return e(a).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=o)return[t];const l=[];let c=0,f=Math.max(64,Math.floor(o*3));for(;c<t.length;){let a=Math.min(t.length,c+f);if(a<t.length){const p=t.lastIndexOf(" ",a);p>c+f/2&&(a=p)}let u=t.slice(c,a);for(;s(u)>o&&u.length>32;){f=Math.max(32,Math.floor(u.length/2)),a=c+f;const p=t.lastIndexOf(" ",a);p>c+f/2&&(a=p),u=t.slice(c,a)}if(l.push(u),a>=t.length)break;const d=Math.max(c+1,a-Ht),i=t.indexOf(" ",d);c=i>0&&i<a?i+1:a}return l}const Pt=200,_=[];function Rt(t,e,r){_.push({ms:t,chars:e,spans:r}),_.length>Pt&&_.shift()}function Ft(){if(!_.length)return{calls:0};const t=_.map(o=>o.ms).sort((o,s)=>o-s),e=o=>t[Math.min(t.length-1,Math.floor(o*t.length))],r=_.reduce((o,s)=>o+s.chars,0),n=_.reduce((o,s)=>o+s.ms,0);return{calls:_.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(_[_.length-1].ms),charsPerSec:n>0?Math.round(r/(n/1e3)):null}}function Dt(t,e){if(!e||t.includes(e))return e;const r=t.toLowerCase().indexOf(e.toLowerCase());return r<0?e:t.slice(r,r+e.length)}function Wt(t,e){if(!e)return e;const r=t.indexOf(e);if(r<0)return e;const n=l=>!!l&&/[\p{L}\p{N}'’-]/u.test(l);let o=r,s=r+e.length;for(;o>0&&n(t[o-1]);)o--;for(;s<t.length&&n(t[s]);)s++;return t.slice(o,s)}async function pe(t,e={}){let r="",n=!1;try{const s=JSON.parse(e.body||"{}");r=s.text||"",n=s.strict===!0}catch{}const o=await Ot(r,{signal:e.signal,strict:n});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function de(){return L}async function z(){if(E)return E;const t=P();try{ft(t,{recursive:!0})}catch{}const e=globalThis.__CHATPANEL_WASM_PATHS__||null;if(e)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}let r;try{r=await import("@huggingface/transformers")}catch(i){throw e?i:new Error(xt(i))}const{env:n,pipeline:o,Tensor:s,AutoModel:l,AutoProcessor:c,AutoTokenizer:f,AutoModelForSequenceClassification:a,LogLevel:u}=r;if(n.cacheDir=t,e&&u)try{n.logLevel=u.ERROR}catch{}n.localModelPath=t,e||(n.useCustomCache=!0,n.customCache=bt(t,{remoteHost:()=>n.remoteHost}));try{n.remoteHost=I}catch{}if(I===C&&n.fetch&&!n.fetch.__chatpanel)try{const i=Lt(n.fetch);i.__chatpanel=!0,n.fetch=i}catch{}try{n.backends.onnx.wasm.numThreads=1}catch{}if(e)try{n.backends.onnx.wasm.proxy=!1,n.backends.onnx.wasm.wasmPaths=e}catch{}return E={env:n,pipeline:(i,p,v={})=>o(i,p,v.progress_callback&&n.allowRemoteModels===!1?{...v,progress_callback:void 0}:v),Tensor:s,AutoModel:l,AutoProcessor:c,AutoTokenizer:f,AutoModelForSequenceClassification:a,AutoModelForAudioFrameClassification:r.AutoModelForAudioFrameClassification},E}function Ut({cores:t=q.availableParallelism?.()??q.cpus().length,wasm:e=!!globalThis.__CHATPANEL_WASM_PATHS__,env:r=process.env}={}){const n=Number(r.CHATPANEL_NER_THREADS);return{intraOpNumThreads:e?1:Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(4,Math.floor(t/4))),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}async function at(t,{log:e=()=>{},allowDownload:r=!0,onProgress:n=()=>{}}={}){const o=await z(),s=R(t);if(o.env.allowRemoteModels=s?!1:!!r,!s&&!r)throw new Error("model not on disk and downloads disabled");const l=o.env.remoteHost,c=!dt(t);if(!s&&c)try{o.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${c?", from Hugging Face":""})…`);try{const a={dtype:"q8",progress_callback:d=>{d&&(d.status==="progress"||d.status==="download"||d.status==="initiate"?n(d):d.status==="done"&&d.file&&e(`[ner] fetched ${d.file}`))},session_options:Ut()};let u;try{u=await o.pipeline("token-classification",t,a)}catch(d){if(s||c||!r)throw d;e(`[ner] mirror fetch failed (${String(d.message).slice(0,80)}) — retrying from Hugging Face…`),o.env.remoteHost="https://huggingface.co/",o.env.allowRemoteModels=!0,u=await o.pipeline("token-classification",t,a)}if(!s)try{_t(t,{modelsDir:P(),log:e})}catch(d){try{await u.dispose?.()}catch{}throw d}return{pipe:u,haveLocal:s}}finally{try{o.env.remoteHost=l}catch{}}}async function lt(t,{log:e=()=>{},allowDownload:r=!0}={}){const n=w,o=y;try{await z()}catch(l){return h="error",b=`engine load failed: ${l.message}`,e(`[ner] transformers.js not available (${l.message}) — deterministic-only`),!1}const s=R(t);if(!s&&!r)return h="error",b="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;h=s?"loading":"downloading",s||(L={model:t,file:null,pct:0});try{const{pipe:l}=await at(t,{log:e,allowDownload:r,onProgress:c=>{L={model:t,file:c.file||L?.file||null,pct:typeof c.progress=="number"?Math.round(c.progress):L?.pct??0}}});if(w=l,y=t,h="ready",b=null,L=null,m&&(m={...m,model:t}),n&&n!==l)try{await n.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),$()||M?.arm(),!0}catch(l){return b=l.message,L=null,n?(w=n,y=o,h="ready"):h="error",e(`[ner] model load failed (${l.message})${n?" — keeping previous model":" — deterministic-only"}`),!1}}function jt(t={}){if(T)return T;const e=typeof t.onLog=="function"?t.onLog:()=>{};m=t,y=t.model||X,h="loading";const r=t.allowDownload!==!1;return M=Z({warmMs:t.warmMs,busy:$,log:e,unload:()=>ct({log:e})}),T=lt(y,{log:e,allowDownload:r}).then(async n=>{const o=Array.isArray(t.union)?t.union:[];$t(o);for(const s of o)await rt(s,{log:e,allowDownload:r});return O()&&!$()&&M?.arm(),n}),T}function $(){if(N>0||h==="loading"||h==="downloading")return!0;for(const t of g.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function ct({log:t=()=>{}}={}){if($())return!1;M?.disarm();const e=st().map(r=>r.pipe);w=null,T=null,L=null,b=null,g.clear(),h=e.length?"idle":"off";for(const r of e)try{await r.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((M?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function qt(){try{h==="idle"&&(H||m)?await(H?H():jt(m)):T&&await T,O()&&await ut()}catch{}return O()}let U=null;function ut(){const t=k.filter(e=>e&&e!==y&&!g.has(e));return t.length?(U||=(async()=>{const e=typeof m?.onLog=="function"?m.onLog:()=>{};for(const r of t)g.has(r)||(j?await j(r):await rt(r,{log:e,allowDownload:m?.allowDownload!==!1}))})().catch(()=>{}).finally(()=>{U=null}),U):Promise.resolve()}let j=null;function he(t){j=t}async function me(t,e={}){const r=typeof e.onLog=="function"?e.onLog:()=>{},n=e.allowDownload!==!1;if(!t)return!1;if(t===y&&O())return!0;if(t===y&&h==="idle")return qt();const o=g.get(t);if(o?.pipe){const l=w;if(w=o.pipe,y=t,h="ready",b=null,g.delete(t),l)try{await l.dispose?.()}catch{}return r(`[ner] ${t} promoted from the union to primary`),m&&(m={...m,model:t}),!0}const s=await lt(t,{log:r,allowDownload:n});return s&&(m&&(m={...m,model:t}),await ut()),s}function ge(){h="off",y=null,w=null,b=null,T=null,E=null,L=null,_.length=0,g.clear(),F=!0,k=[],M?.disarm(),M=null,m=null,N=0,H=null,j=null,U=null}function ye(t,e){g.set(t,{pipe:e,state:"ready",error:null})}function we(t,{model:e="test/model",warmMs:r=null,reload:n=null}={}){w=t,y=e,h="ready",b=null,_.length=0,n&&(H=n),r!==null&&(M=Z({warmMs:r,busy:$,unload:()=>ct()}),t&&M.arm())}export{ge as _reset,ye as _setCompanionForTest,he as _setCompanionLoaderForTest,we as _setForTest,rt as addCompanion,Et as companions,Ot as detect,le as detectSpans,qt as ensure,z as ensureLib,pe as fetchAdapter,ie as health,jt as init,O as isReady,ce as labels,ue as maxTokens,R as modelOnDisk,P as modelRoot,re as modelsOnDisk,de as progress,fe as removeCompanion,At as resolveModelHost,Ut as sessionOptionsFor,ae as setCaseRecovery,me as setModel,$t as setUnionOrder,se as state,Ft as stats,Ct as unionSpans,ct as unload,Nt as windowsFor,oe as withModelSource};
1
+ import z from"node:os";import{join as S}from"node:path";import{existsSync as K,mkdirSync as ft,readdirSync as V,readFileSync as pt}from"node:fs";import{DEFAULT_MODEL as X,isMirroredModel as dt}from"./models.js";import{isLoopbackHost as ht,isPrivateHost as mt,isMetadataHost as gt}from"@chatpanel/pii";import{recaseForDetection as yt}from"@chatpanel/pii/pii-detect.js";import{recasedSpanOk as wt}from"@chatpanel/pii/recased-spans.js";import{verifyModelWeights as _t}from"./model-integrity.js";import{runtimeName as Mt}from"./model-runtime.js";import{nativeOrtFailure as xt}from"./ort.js";import{makeWarmTimer as Z}from"./warm-timer.js";import{makeModelFileCache as bt}from"./model-file-cache.js";import{modelFetch as Lt}from"./model-sources.js";import{onLane as Tt}from"./inference-lane.js";const C="https://huggingface.co/";function At(t=process.env){const e=t.CHATPANEL_MODEL_BASE_URL?"CHATPANEL_MODEL_BASE_URL":"registries.models",r=t.CHATPANEL_MODEL_BASE_URL||t.CHATPANEL_REGISTRY_MODELS;if(!r)return C;const n=l=>(console.warn(`[models] ignoring ${e} (${r}): ${l} — using ${C}`),C);let o;try{o=new URL(r)}catch{return n("not a valid URL")}if(o.protocol!=="http:"&&o.protocol!=="https:")return n(`scheme ${o.protocol} not allowed`);if(gt(o.hostname))return n("points at cloud metadata");const s=ht(o.hostname)||mt(o.hostname);return o.protocol==="http:"&&!s?n("plaintext http:// to a public host (use https or a LAN/loopback mirror)"):(console.warn(`[models] ⚠ model weights will be downloaded from ${o.origin} (${e}), not ${C}`),r.replace(/\/*$/,"/"))}const I=At();let h="off",y=null,w=null,b=null,A=null,E=null,L=null,m=null,x=null,N=0,H=null;const g=new Map;let tt=Promise.resolve();function oe({host:t=null,allowRemote:e=!1}={},r){const n=tt.then(async()=>{const o=await Y(),s=o.env.remoteHost,l=o.env.allowRemoteModels;try{o.env.allowRemoteModels=e,t&&(o.env.remoteHost=t)}catch{}try{return await r(o)}finally{try{o.env.remoteHost=s,o.env.allowRemoteModels=l}catch{}}});return tt=n.catch(()=>{}),n}function P(){return process.env.CHATPANEL_MODELS_DIR||S(z.homedir(),".chatpanel","models")}function R(t=y||X){const e=S(P(),...t.split("/"));return K(S(e,"onnx","model_quantized.onnx"))||K(S(e,"onnx","model.onnx"))}function re(){const t=P(),e=[];try{for(const r of V(t,{withFileTypes:!0}))if(r.isDirectory())for(const n of V(S(t,r.name),{withFileTypes:!0})){if(!n.isDirectory())continue;const o=`${r.name}/${n.name}`;R(o)&&St(S(t,r.name,n.name))&&e.push(o)}}catch{}return e}function St(t){try{return(JSON.parse(pt(S(t,"config.json"),"utf8")).architectures||[]).some(r=>/ForTokenClassification$/.test(String(r)))}catch{return!1}}function se(){return h}function O(){return h==="ready"&&!!w}function ie(){return{configured:h!=="off",ok:O(),state:h,model:y,error:b,runtime:Mt(),dtype:w?"q8":null,stats:Ft(),companions:Et(),warmMs:x?.warmMs??null}}async function Ot(t,{signal:e,strict:r=!1}={}){if(!O())return[];if(e?.aborted)return[];const n=String(t||""),o=await et(n,e);if(!o)return[];const s=[];for(const u of o||[]){let i=String(u.word??"");const f=u.entity_group??u.entity??"ENTITY";if(i.startsWith("##")&&s.length&&s[s.length-1].type===f){s[s.length-1].value+=i.slice(2);continue}i=i.replace(/##/g,"").trim(),i&&s.push({value:i,type:f,pass:u._pass})}const l=new Set,c=[];for(const u of s){const i=Wt(n,Dt(n,u.value.trim()));if(i.length<=1||nt(i,u.type,u.pass,r))continue;const f=`${u.type}:${i.toLowerCase()}`;l.has(f)||(l.add(f),c.push({value:i,type:u.type}))}return c}async function et(t,e){N++;try{return await vt(t,e)}finally{N--,$()||x?.arm()}}async function vt(t,e){const r=performance.now(),n=[],o=[{text:t,key:"orig"}];if(F){const s=yt(t);s.changed&&o.push({text:s.text,key:"recased"})}for(const{model:s,pipe:l}of st())for(const c of o){let u=0;for(const i of Nt(c.text,l.tokenizer)){if(e?.aborted)return null;const f=c.text.indexOf(i,u),d=await Tt(()=>l(i,{aggregation_strategy:"simple"}));for(const a of d||[])n.push({...a,_win:f<0?u:f,_winText:i,_model:s,_pass:c.key,_passText:c.text});f>=0&&(u=Math.max(u,f+1))}}return Rt(performance.now()-r,t.length,n.length),n}let F=!0;function ae(t){F=t!==!1}const nt=(t,e,r,n)=>!n&&r==="recased"&&!wt(t,e);async function le(t,{signal:e,strict:r=!1}={}){if(!O())return[];const n=String(t||""),o=await et(n,e);if(!o)return[];const s=[],l=new Set;let c=-1,u=-1,i=null,f=null;for(const a of o){const p=String(a.word??"").replace(/##/g,"").trim();if(!p)continue;(a._win!==u||a._model!==i||a._pass!==f)&&(u=a._win,i=a._model,f=a._pass,c=a._win);const v=a._passText||n;let M=v.indexOf(p,c);if(M<0&&(M=v.indexOf(p,a._win)),M<0)continue;let T=M+p.length;c=T;const B=Q=>!!Q&&/[\p{L}\p{N}'’-]/u.test(Q);for(;M>0&&B(n[M-1]);)M--;for(;T<n.length&&B(n[T]);)T++;const q=String(a.entity_group??a.entity??"ENTITY");if(nt(n.slice(M,T),q,a._pass,r))continue;const J=`${M}:${T}:${q}`;if(l.has(J))continue;l.add(J);const G=Number(a.score);s.push({value:n.slice(M,T),type:q,start:M,end:T,score:Number.isFinite(G)?Math.max(0,Math.min(1,G)):1,model:a._model})}s.sort((a,p)=>a.start-p.start||a.end-p.end);const d=[];for(const a of s){const p=d[d.length-1];if(p&&p.type===a.type&&p.end===a.start){p.end=a.end,p.value=n.slice(p.start,p.end),p.score=Math.min(p.score,a.score);continue}d.push({...a})}return g.size||F?Ct(d):d}const ot=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function kt(t){const e=String(t).toLowerCase();return/secret|password|key/.test(e)?"secret":/ssn|social/.test(e)?"ssn":/card/.test(e)?"card":/iban/.test(e)?"iban":/account/.test(e)?"account":/^id|num|username|passport|licen|url|date|imei|ip$|mac$/.test(e)?"id":/email/.test(e)?"email":/phone|tel/.test(e)?"phone":/address|street|zip|post|building/.test(e)?"address":/per|name|person/.test(e)?"person":/org|company/.test(e)?"org":"loc"}function D(t){const e=ot.indexOf(kt(t.type));return e<0?ot.length:e}let k=[];function $t(t){k=Array.isArray(t)?t.slice():[],m&&(m={...m,union:k.slice()})}function W(t){if(t.model===y)return-1;const e=k.indexOf(t.model);return e<0?k.length:e}function Ct(t){const e=[...t].sort((n,o)=>n.start-o.start||o.end-n.end),r=[];for(const n of e){const o=r[r.length-1];if(o&&n.start<o.end){const s=c=>c.end-c.start;(D(n)<D(o)||D(n)===D(o)&&(s(n)>s(o)||s(n)===s(o)&&(W(n)<W(o)||W(n)===W(o)&&n.score>o.score)))&&(r[r.length-1]=n);continue}r.push(n)}return r}function ce(){const t=w?.model?.config?.id2label;if(!t)return[];const e=new Set;for(const r of Object.values(t)){const n=String(r).replace(/^[BIES]-/,"");n&&n!=="O"&&e.add(n)}return[...e]}function ue(){const t=Number(w?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function Et(){return[...g].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function rt(t,{log:e=()=>{},allowDownload:r=!0}={}){if(!t||t===y)return!1;if(g.get(t)?.pipe)return!0;g.set(t,{pipe:null,state:R(t)?"loading":"downloading",error:null});try{const{pipe:o}=await at(t,{log:e,allowDownload:r});return g.set(t,{pipe:o,state:"ready",error:null}),e(`[ner] companion ready — ${t} joins the union`),!0}catch(o){return g.set(t,{pipe:null,state:"error",error:o.message}),e(`[ner] companion ${t} failed to load (${o.message}) — the union runs without it`),!1}}async function fe(t){const e=g.get(t);if(!e)return!1;g.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function st(){const t=w?[{model:y,pipe:w}]:[];for(const[e,r]of g)r.pipe&&t.push({model:e,pipe:r.pipe});return t}const Ht=160,it=256;function Nt(t,e){if(!t||typeof e!="function")return[t];const r=Number(e.model_max_length),o=Math.min(it,Number.isFinite(r)&&r>0?r:it)-8,s=i=>{try{return e(i).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=o)return[t];const l=[];let c=0,u=Math.max(64,Math.floor(o*3));for(;c<t.length;){let i=Math.min(t.length,c+u);if(i<t.length){const p=t.lastIndexOf(" ",i);p>c+u/2&&(i=p)}let f=t.slice(c,i);for(;s(f)>o&&f.length>32;){u=Math.max(32,Math.floor(f.length/2)),i=c+u;const p=t.lastIndexOf(" ",i);p>c+u/2&&(i=p),f=t.slice(c,i)}if(l.push(f),i>=t.length)break;const d=Math.max(c+1,i-Ht),a=t.indexOf(" ",d);c=a>0&&a<i?a+1:i}return l}const Pt=200,_=[];function Rt(t,e,r){_.push({ms:t,chars:e,spans:r}),_.length>Pt&&_.shift()}function Ft(){if(!_.length)return{calls:0};const t=_.map(o=>o.ms).sort((o,s)=>o-s),e=o=>t[Math.min(t.length-1,Math.floor(o*t.length))],r=_.reduce((o,s)=>o+s.chars,0),n=_.reduce((o,s)=>o+s.ms,0);return{calls:_.length,p50Ms:Math.round(e(.5)),p95Ms:Math.round(e(.95)),maxMs:Math.round(t[t.length-1]),lastMs:Math.round(_[_.length-1].ms),charsPerSec:n>0?Math.round(r/(n/1e3)):null}}function Dt(t,e){if(!e||t.includes(e))return e;const r=t.toLowerCase().indexOf(e.toLowerCase());return r<0?e:t.slice(r,r+e.length)}function Wt(t,e){if(!e)return e;const r=t.indexOf(e);if(r<0)return e;const n=l=>!!l&&/[\p{L}\p{N}'’-]/u.test(l);let o=r,s=r+e.length;for(;o>0&&n(t[o-1]);)o--;for(;s<t.length&&n(t[s]);)s++;return t.slice(o,s)}async function pe(t,e={}){let r="",n=!1;try{const s=JSON.parse(e.body||"{}");r=s.text||"",n=s.strict===!0}catch{}const o=await Ot(r,{signal:e.signal,strict:n});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function de(){return L}async function Y(){if(E)return E;const t=P();try{ft(t,{recursive:!0})}catch{}const e=globalThis.__CHATPANEL_WASM_PATHS__||null;if(e)try{Object.defineProperty(process,"release",{value:{...process.release,name:"bun"},configurable:!0})}catch{}let r;try{r=await import("@huggingface/transformers")}catch(a){throw e?a:new Error(xt(a))}const{env:n,pipeline:o,Tensor:s,AutoModel:l,AutoProcessor:c,AutoTokenizer:u,AutoModelForSequenceClassification:i,LogLevel:f}=r;if(n.cacheDir=t,e&&f)try{n.logLevel=f.ERROR}catch{}n.localModelPath=t,e||(n.useCustomCache=!0,n.customCache=bt(t,{remoteHost:()=>n.remoteHost}));try{n.remoteHost=I}catch{}if(I===C&&n.fetch&&!n.fetch.__chatpanel)try{const a=Lt(n.fetch);a.__chatpanel=!0,n.fetch=a}catch{}try{n.backends.onnx.wasm.numThreads=1}catch{}if(e)try{n.backends.onnx.wasm.proxy=!1,n.backends.onnx.wasm.wasmPaths=e}catch{}return E={env:n,pipeline:(a,p,v={})=>o(a,p,v.progress_callback&&n.allowRemoteModels===!1?{...v,progress_callback:void 0}:v),Tensor:s,AutoModel:l,AutoProcessor:c,AutoTokenizer:u,AutoModelForSequenceClassification:i,AutoModelForAudioFrameClassification:r.AutoModelForAudioFrameClassification},E}function Ut({cores:t=z.availableParallelism?.()??z.cpus().length,wasm:e=!!globalThis.__CHATPANEL_WASM_PATHS__,env:r=process.env}={}){const n=Number(r.CHATPANEL_NER_THREADS);return{intraOpNumThreads:e?1:Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(4,Math.floor(t/4))),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}async function at(t,{log:e=()=>{},allowDownload:r=!0,onProgress:n=()=>{}}={}){const o=await Y(),s=R(t);if(o.env.allowRemoteModels=s?!1:!!r,!s&&!r)throw new Error("model not on disk and downloads disabled");const l=o.env.remoteHost,c=!dt(t);if(!s&&c)try{o.env.remoteHost="https://huggingface.co/"}catch{}s||e(`[ner] downloading model ${t} (one-time${c?", from Hugging Face":""})…`);try{const i={dtype:"q8",progress_callback:d=>{d&&(d.status==="progress"||d.status==="download"||d.status==="initiate"?n(d):d.status==="done"&&d.file&&e(`[ner] fetched ${d.file}`))},session_options:Ut()};let f;try{f=await o.pipeline("token-classification",t,i)}catch(d){if(s||c||!r)throw d;e(`[ner] mirror fetch failed (${String(d.message).slice(0,80)}) — retrying from Hugging Face…`),o.env.remoteHost="https://huggingface.co/",o.env.allowRemoteModels=!0,f=await o.pipeline("token-classification",t,i)}if(!s)try{_t(t,{modelsDir:P(),log:e})}catch(d){try{await f.dispose?.()}catch{}throw d}return{pipe:f,haveLocal:s}}finally{try{o.env.remoteHost=l}catch{}}}async function lt(t,{log:e=()=>{},allowDownload:r=!0}={}){const n=w,o=y;try{await Y()}catch(l){return h="error",b=`engine load failed: ${l.message}`,e(`[ner] transformers.js not available (${l.message}) — deterministic-only`),!1}const s=R(t);if(!s&&!r)return h="error",b="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;h=s?"loading":"downloading",s||(L={model:t,file:null,pct:0});try{const{pipe:l}=await at(t,{log:e,allowDownload:r,onProgress:c=>{L={model:t,file:c.file||L?.file||null,pct:typeof c.progress=="number"?Math.round(c.progress):L?.pct??0}}});if(w=l,y=t,h="ready",b=null,L=null,m&&(m={...m,model:t}),n&&n!==l)try{await n.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),$()||x?.arm(),!0}catch(l){return b=l.message,L=null,n?(w=n,y=o,h="ready"):h="error",e(`[ner] model load failed (${l.message})${n?" — keeping previous model":" — deterministic-only"}`),!1}}function jt(t={}){if(A)return A;const e=typeof t.onLog=="function"?t.onLog:()=>{};m=t,y=t.model||X,h="loading";const r=t.allowDownload!==!1;return x=Z({warmMs:t.warmMs,busy:$,log:e,unload:()=>ct({log:e})}),A=lt(y,{log:e,allowDownload:r}).then(async n=>{const o=Array.isArray(t.union)?t.union:[];$t(o);for(const s of o)await rt(s,{log:e,allowDownload:r});return O()&&!$()&&x?.arm(),n}),A}function $(){if(N>0||h==="loading"||h==="downloading")return!0;for(const t of g.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function ct({log:t=()=>{}}={}){if($())return!1;x?.disarm();const e=st().map(r=>r.pipe);w=null,A=null,L=null,b=null,g.clear(),h=e.length?"idle":"off";for(const r of e)try{await r.dispose?.()}catch{}return e.length&&t(`[ner] idle for ${Math.round((x?.warmMs||0)/6e4)} min — ${e.length===1?"model":`${e.length} models`} unloaded (reloads on the next turn)`),!0}async function qt(){try{h==="idle"&&(H||m)?await(H?H():jt(m)):A&&await A,O()&&await ut()}catch{}return O()}let U=null;function ut(){const t=k.filter(e=>e&&e!==y&&!g.has(e));return t.length?(U||=(async()=>{const e=typeof m?.onLog=="function"?m.onLog:()=>{};for(const r of t)g.has(r)||(j?await j(r):await rt(r,{log:e,allowDownload:m?.allowDownload!==!1}))})().catch(()=>{}).finally(()=>{U=null}),U):Promise.resolve()}let j=null;function he(t){j=t}async function me(t,e={}){const r=typeof e.onLog=="function"?e.onLog:()=>{},n=e.allowDownload!==!1;if(!t)return!1;if(t===y&&O())return!0;if(t===y&&h==="idle")return qt();const o=g.get(t);if(o?.pipe){const l=w;if(w=o.pipe,y=t,h="ready",b=null,g.delete(t),l)try{await l.dispose?.()}catch{}return r(`[ner] ${t} promoted from the union to primary`),m&&(m={...m,model:t}),!0}const s=await lt(t,{log:r,allowDownload:n});return s&&(m&&(m={...m,model:t}),await ut()),s}function ge(){h="off",y=null,w=null,b=null,A=null,E=null,L=null,_.length=0,g.clear(),F=!0,k=[],x?.disarm(),x=null,m=null,N=0,H=null,j=null,U=null}function ye(t,e){g.set(t,{pipe:e,state:"ready",error:null})}function we(t,{model:e="test/model",warmMs:r=null,reload:n=null}={}){w=t,y=e,h="ready",b=null,_.length=0,n&&(H=n),r!==null&&(x=Z({warmMs:r,busy:$,unload:()=>ct()}),t&&x.arm())}export{ge as _reset,ye as _setCompanionForTest,he as _setCompanionLoaderForTest,we as _setForTest,rt as addCompanion,Et as companions,Ot as detect,le as detectSpans,qt as ensure,Y as ensureLib,pe as fetchAdapter,ie as health,jt as init,O as isReady,ce as labels,ue as maxTokens,R as modelOnDisk,P as modelRoot,re as modelsOnDisk,de as progress,fe as removeCompanion,At as resolveModelHost,Ut as sessionOptionsFor,ae as setCaseRecovery,me as setModel,$t as setUnionOrder,se as state,Ft as stats,Ct as unionSpans,ct as unload,Nt as windowsFor,oe as withModelSource};
package/src/redact.js CHANGED
@@ -1 +1 @@
1
- import{createHash as W}from"node:crypto";import{createVault as Y,redactText as Z,detectEntities as tt,gatedDictionary as et,sanitizeUnicode as nt,strictnessOf as z}from"@chatpanel/pii";import{ENTITIES_SCHEMA as P,entitiesFormat as ot}from"./extraction.js";import{describeSchema as st,coerce as rt}from"./structured.js";import*as q from"./ner-engine.js";const b=8e3,it=2e6,u=new Map;let k=0,_="";const F=t=>`${W("sha256").update(t).digest("base64")}:${t.length}`;function G(t,e,o){t!==_&&(u.clear(),k=0,_=t);const s=F(e);if(!u.has(s))for(u.set(s,{ents:o,len:e.length}),k+=e.length;k>it&&u.size;){const[n]=u.keys();k-=u.get(n).len,u.delete(n)}}function B(t,e){return t===_?u.get(F(e))?.ents:void 0}function gt(){u.clear(),k=0,_="",f.length=0,x=0}function K(t,e=b){const o=[];for(const s of String(t||"").split(/\n[ \t]*\n/)){let n=s.trim();for(;n.length>e;){let i=n.lastIndexOf(" ",e);i<e/2&&(i=e),o.push(n.slice(0,i).trim()),n=n.slice(i).trim()}n.length>=8&&o.push(n)}return o}function ct(t){if(t<=1)return t===1?[0]:[];const e=[t-1,0];for(let o=t-2;o>0;o--)e.push(o);return e}function L(t,{useEngine:e}){const o=t.detection,s=e?{backend:"endpoint",url:"inproc:ner",transport:"in-process",timeoutMs:3e4,maxChars:b,types:o?.types,strictness:z(t)}:{...o,timeoutMs:Math.max(Number(o.timeoutMs)||0,3e4),strictness:z(t)},n=JSON.stringify([s.backend,s.url||"",s.model||"",s.strictness||"",s.types||null]);return{detection:s,sig:n}}const lt=()=>({block:st(P),format:t=>ot(t),parse:t=>rt(t,P)?.value??null});async function U(t,{detection:e,fetchImpl:o,signal:s=void 0,onEgress:n=null}){let i=!1,g=null;try{g=await tt(t,{detection:e},{signal:s,fetchImpl:o,onError:()=>{i=!0},onEgress:n,structured:lt()})}catch{g=null}return i?null:g}const ut=64e3,f=[];let x=0,D=0,p=null;function X(t,{detection:e,fetchImpl:o,sig:s}){for(const n of t)B(s,n)||f.some(i=>i.text===n)||(f.push({text:n,detection:e,fetchImpl:o,sig:s}),x+=n.length);for(;x>ut&&f.length;)x-=f.shift().text.length}function ft(){return p||(f.length?(p=(async()=>{try{for(;f.length;){if(D>0)return;const t=f.shift();if(x-=t.text.length,B(t.sig,t.text))continue;const e=await U(t.text,t);e&&G(t.sig,t.text,e)}}finally{p=null}})(),p):Promise.resolve())}function j(){if(!f.length||p)return;setTimeout(()=>{ft().catch(()=>{})},50).unref?.()}function mt(t,e,{nerEngine:o=q}={}){if(!t||typeof t!="string"||e?.tier!=="full")return!1;const s=e.detection;if(s&&s.backend&&s.backend!=="off"||!o.isReady())return!1;const{detection:n,sig:i}=L(e,{useEngine:!0});return X(K(t,n.maxChars||b),{detection:n,fetchImpl:o.fetchAdapter,sig:i}),j(),!0}async function yt(t,e,{signal:o,isPro:s=!0,onEgress:n=null,fetchImpl:i=null,budgetChars:g=b,sanitizeOnly:J=!1,nerEngine:w=q}={}){const S=Y();let C=0;for(const r of t){const c=r.get();if(typeof c!="string"||!c)continue;const{clean:a,removed:y}=nt(c);y&&(r.set(a),C+=y)}const A=t.map(r=>r.get()).filter(r=>typeof r=="string"&&r);if(A.length===0)return{vault:S,count:0,sanitized:C};if(J)return{vault:S,count:0,sanitized:C};const E=e.tier==="full"?"full":"basic",V=et(e,s),M=e.detection,v=!!(M&&M.backend&&M.backend!=="off");E==="full"&&!v&&typeof w.ensure=="function"&&await w.ensure();const m=!v&&w.isReady();let H=[],O=0;if(E==="full"&&(v||m)){const{detection:r,sig:c}=L(e,{useEngine:m}),a=m?w.fetchAdapter:i||void 0,y=new Set,R=[],I=[];let $=g;D++;try{for(const h of ct(A.length))for(const l of K(A[h],r.maxChars||b)){if(o?.aborted)break;if(y.has(l))continue;y.add(l);let d=B(c,l);if(!d){if(l.length>$){O+=l.length,I.push(l);continue}$-=l.length,d=await U(l,{detection:r,fetchImpl:a,signal:o,onEgress:m?null:n}),d?G(c,l,d):d=[]}R.push(...d)}}finally{D--}m&&I.length&&X(I,{detection:r,fetchImpl:a,sig:c}),j();const T=new Map;for(const h of R){if(!h||!h.value)continue;const l=`${h.type}:${String(h.value).toLowerCase()}`;T.has(l)||T.set(l,h)}H=[...T.values()]}const Q={tier:E,entities:H,dictionary:V};let N=0;for(const r of t){const c=r.get();if(typeof c!="string"||!c)continue;const a=Z(c,S,Q);a!==c&&N++,r.set(a)}return{vault:S,count:N,sanitized:C,unscanned:O}}function bt(t,e){return{get:t,set:e}}export{gt as clearBlockCache,K as detectBlocks,ft as flushPendingDetection,yt as redactSegments,mt as rememberAnswer,ct as scanOrder,bt as segment};
1
+ import{createHash as Y}from"node:crypto";import{createVault as Z,redactText as tt,detectEntities as et,gatedDictionary as nt,sanitizeUnicode as st,strictnessOf as $}from"@chatpanel/pii";import*as ot from"@chatpanel/pii";const rt=ot.consistentPlaces||(t=>t);import{ENTITIES_SCHEMA as z,entitiesFormat as it}from"./extraction.js";import{describeSchema as ct,coerce as lt}from"./structured.js";import*as q from"./ner-engine.js";const b=8e3,ut=2e6,u=new Map;let k=0,_="";const F=t=>`${Y("sha256").update(t).digest("base64")}:${t.length}`;function G(t,e,s){t!==_&&(u.clear(),k=0,_=t);const o=F(e);if(!u.has(o))for(u.set(o,{ents:s,len:e.length}),k+=e.length;k>ut&&u.size;){const[n]=u.keys();k-=u.get(n).len,u.delete(n)}}function B(t,e){return t===_?u.get(F(e))?.ents:void 0}function bt(){u.clear(),k=0,_="",f.length=0,x=0}function K(t,e=b){const s=[];for(const o of String(t||"").split(/\n[ \t]*\n/)){let n=o.trim();for(;n.length>e;){let i=n.lastIndexOf(" ",e);i<e/2&&(i=e),s.push(n.slice(0,i).trim()),n=n.slice(i).trim()}n.length>=8&&s.push(n)}return s}function ft(t){if(t<=1)return t===1?[0]:[];const e=[t-1,0];for(let s=t-2;s>0;s--)e.push(s);return e}function L(t,{useEngine:e}){const s=t.detection,o=e?{backend:"endpoint",url:"inproc:ner",transport:"in-process",timeoutMs:3e4,maxChars:b,types:s?.types,strictness:$(t)}:{...s,timeoutMs:Math.max(Number(s.timeoutMs)||0,3e4),strictness:$(t)},n=JSON.stringify([o.backend,o.url||"",o.model||"",o.strictness||"",o.types||null]);return{detection:o,sig:n}}const at=()=>({block:ct(z),format:t=>it(t),parse:t=>lt(t,z)?.value??null});async function U(t,{detection:e,fetchImpl:s,signal:o=void 0,onEgress:n=null}){let i=!1,g=null;try{g=await et(t,{detection:e},{signal:o,fetchImpl:s,onError:()=>{i=!0},onEgress:n,structured:at()})}catch{g=null}return i?null:g}const ht=64e3,f=[];let x=0,D=0,p=null;function X(t,{detection:e,fetchImpl:s,sig:o}){for(const n of t)B(o,n)||f.some(i=>i.text===n)||(f.push({text:n,detection:e,fetchImpl:s,sig:o}),x+=n.length);for(;x>ht&&f.length;)x-=f.shift().text.length}function dt(){return p||(f.length?(p=(async()=>{try{for(;f.length;){if(D>0)return;const t=f.shift();if(x-=t.text.length,B(t.sig,t.text))continue;const e=await U(t.text,t);e&&G(t.sig,t.text,e)}}finally{p=null}})(),p):Promise.resolve())}function j(){if(!f.length||p)return;setTimeout(()=>{dt().catch(()=>{})},50).unref?.()}function kt(t,e,{nerEngine:s=q}={}){if(!t||typeof t!="string"||e?.tier!=="full")return!1;const o=e.detection;if(o&&o.backend&&o.backend!=="off"||!s.isReady())return!1;const{detection:n,sig:i}=L(e,{useEngine:!0});return X(K(t,n.maxChars||b),{detection:n,fetchImpl:s.fetchAdapter,sig:i}),j(),!0}async function xt(t,e,{signal:s,isPro:o=!0,onEgress:n=null,fetchImpl:i=null,budgetChars:g=b,sanitizeOnly:J=!1,nerEngine:w=q}={}){const S=Z();let C=0;for(const r of t){const c=r.get();if(typeof c!="string"||!c)continue;const{clean:a,removed:y}=st(c);y&&(r.set(a),C+=y)}const A=t.map(r=>r.get()).filter(r=>typeof r=="string"&&r);if(A.length===0)return{vault:S,count:0,sanitized:C};if(J)return{vault:S,count:0,sanitized:C};const E=e.tier==="full"?"full":"basic",V=nt(e,o),M=e.detection,v=!!(M&&M.backend&&M.backend!=="off");E==="full"&&!v&&typeof w.ensure=="function"&&await w.ensure();const m=!v&&w.isReady();let H=[],N=0;if(E==="full"&&(v||m)){const{detection:r,sig:c}=L(e,{useEngine:m}),a=m?w.fetchAdapter:i||void 0,y=new Set,P=[],I=[];let R=g;D++;try{for(const h of ft(A.length))for(const l of K(A[h],r.maxChars||b)){if(s?.aborted)break;if(y.has(l))continue;y.add(l);let d=B(c,l);if(!d){if(l.length>R){N+=l.length,I.push(l);continue}R-=l.length,d=await U(l,{detection:r,fetchImpl:a,signal:s,onEgress:m?null:n}),d?G(c,l,d):d=[]}P.push(...d)}}finally{D--}m&&I.length&&X(I,{detection:r,fetchImpl:a,sig:c}),j();const W=rt(P,r.types),T=new Map;for(const h of W){if(!h||!h.value)continue;const l=`${h.type}:${String(h.value).toLowerCase()}`;T.has(l)||T.set(l,h)}H=[...T.values()]}const Q={tier:E,entities:H,dictionary:V};let O=0;for(const r of t){const c=r.get();if(typeof c!="string"||!c)continue;const a=tt(c,S,Q);a!==c&&O++,r.set(a)}return{vault:S,count:O,sanitized:C,unscanned:N}}function wt(t,e){return{get:t,set:e}}export{bt as clearBlockCache,K as detectBlocks,dt as flushPendingDetection,xt as redactSegments,kt as rememberAnswer,ft as scanOrder,wt as segment};
package/src/server.js CHANGED
@@ -64,4 +64,4 @@ data: ${JSON.stringify(c)}
64
64
  connection: close\r
65
65
  content-length: 0\r
66
66
  \r
67
- `)}catch{}}),ue.once("listening",()=>{P()}),ue.linkHost=y,ue.runtimeDefaults=()=>P().ensureDefaults(),ue}function Lt(t,d){let u=d&&typeof d=="object"?d:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const p={};if(Array.isArray(u.grants)&&(p.grants=u.grants.map(y=>String(y).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const y=u.workspace;p.workspace={repo:String(y.repo).slice(0,400),projectId:String(y.projectId||"").slice(0,120),jobId:String(y.jobId||"").slice(0,120),...y.base?{base:String(y.base).slice(0,120)}:{}}}if(u.connectionId&&(p.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(p.workingDir=u.workingDir.trim().slice(0,1024)),Xa.includes(u.permissionMode)&&u.permissionMode!=="default"&&(p.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const y=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(T=>String(T).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),$=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(T=>String(T).slice(0,1024)).filter(Boolean).slice(0,32),B=u.sandbox.outside===!0,E=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(T=>String(T).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(y.length||$.length||B||E.length)&&(p.sandbox={...y.length?{hosts:y}:{},...$.length?{write:$}:{},...B?{outside:!0}:{},...E.length?{signIn:E}:{}})}const w=Kr(u.thread);return w&&(p.thread=w),u.ephemeral===!0&&(p.ephemeral=!0),u.worker===!0&&(p.worker=!0,p.ephemeral=!0),Object.keys(p).length?p:null}let Ve=null,ut=null;async function Sl(t=Wt()){Hr();let d=null;try{d=await _r()}catch(T){throw T instanceof Or&&(console.error(`[chatpanel-gateway] org policy: ${T.message}`),process.exit(78)),T}const u=d?.policy||null;u&&(Zt(t,u),console.log(`[chatpanel-gateway] ${d.label} — ${d.signed?"signed":"unsigned"} policy from ${d.source}`));const p=Tr({enabled:Xt(t)});console.log(`[chatpanel-gateway] certificates: ${p.on?`this computer's list is trusted too (${p.added} added to the runtime's own)`:`the runtime's own list only — ${p.why}`}`),kr(globalThis,{allow:u?.egress?(T,{local:x})=>Pr(u,T,{local:x}):null}),_e();const w=As(t),y=jr(t),$=tr(t);let B=!1;w.on("error",T=>{if(T&&T.code==="EADDRINUSE"){const x=ct(t.host)?"127.0.0.1":t.host;fetch(`http://${x}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(R=>R.ok?R.json():null).catch(()=>null).then(R=>{const j=!!(R?.version&&typeof R.tier=="string"),V=Qr({name:"gateway",self:de,holder:j?{ours:j,version:R.version}:null,managedBy:Yr(process.env),port:t.port});if(V.action==="standby"||B&&!R){if(!B)for(const P of V.lines)console.error(P);B=!0,setTimeout(()=>w.listen(t.port,t.host),Xr);return}if(j){const P=R.managedBy?` (run by ${R.managedBy})`:"";for(const[U,z]of V.lines.entries())console.error(U===0?z.replace(` on ${t.port}`,` at http://${x}:${t.port}${P}`):z)}else{const P=mn(t.port);console.error(`Port ${t.port} is held by ${P||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${le()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${T?.message||T}`),process.exit(1)}),w.listen(t.port,t.host,()=>{B&&console.log(" standby : the other gateway is gone — this copy has the port now"),B=!1,console.log(`ChatPanel Privacy Gateway v${de} on http://${t.host}:${t.port}`),w.linkHost?.start().catch(T=>console.log(` link : not started (${T?.message||T})`)),w.runtimeDefaults?.().then(T=>{for(const x of T||[])console.log(` ${x.label.toLowerCase().padEnd(9).slice(0,9)}: ${x.ok?x.already?"running":x.adopted?"already running — adopted":"started":`not started (${x.skipped})`}`)}).catch(T=>console.log(` runtime : defaults not started (${T?.message||T})`)),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token");for(const T of qa(t))console.log(` ⚠ sandbox : ${T}`);console.log(` confined : ${wn(wt({stateDir:He.dirname(le())}))}`),ut={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},un(t,{childEnv:()=>({...Za(t,process.env,qe()),...Ya(t)})}).then(T=>{Ve=T}).catch(T=>{ut={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${T?.message||T})`},console.log(` bridge : not supervised (${T?.message||T})`)}),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),ct(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),io()&&kt(J,ft()).then(T=>{T?.ok&&(console.log(` warm : seeded ${T.ingested} records from ${T.file}`),T.whole&&Ue())}).catch(()=>{});const E=()=>{y?.stop(),$.stop(),Ve?.stop(),is(w)};return process.on("SIGINT",E),process.on("SIGTERM",E),w}export{vs as RECORDS_MAX_BYTES,_l as VERSION,As as createGateway,_s as joinUpstream,Bt as parseAgentModel,Sl as start};
67
+ `)}catch{}}),ue.once("listening",()=>{P()}),ue.linkHost=y,ue.runtimeDefaults=()=>P().ensureDefaults(),ue}function Lt(t,d){let u=d&&typeof d=="object"?d:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const p={};if(Array.isArray(u.grants)&&(p.grants=u.grants.map(y=>String(y).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const y=u.workspace;p.workspace={repo:String(y.repo).slice(0,400),projectId:String(y.projectId||"").slice(0,120),jobId:String(y.jobId||"").slice(0,120),...y.base?{base:String(y.base).slice(0,120)}:{}}}if(u.connectionId&&(p.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(p.workingDir=u.workingDir.trim().slice(0,1024)),Xa.includes(u.permissionMode)&&u.permissionMode!=="default"&&(p.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const y=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(T=>String(T).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),$=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(T=>String(T).slice(0,1024)).filter(Boolean).slice(0,32),B=u.sandbox.outside===!0,E=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(T=>String(T).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(y.length||$.length||B||E.length)&&(p.sandbox={...y.length?{hosts:y}:{},...$.length?{write:$}:{},...B?{outside:!0}:{},...E.length?{signIn:E}:{}})}const w=Kr(u.thread);return w&&(p.thread=w),u.ephemeral===!0&&(p.ephemeral=!0),u.worker===!0&&(p.worker=!0,p.ephemeral=!0),u.lean===!0&&(p.lean=!0,p.ephemeral=!0),Object.keys(p).length?p:null}let Ve=null,ut=null;async function Sl(t=Wt()){Hr();let d=null;try{d=await _r()}catch(T){throw T instanceof Or&&(console.error(`[chatpanel-gateway] org policy: ${T.message}`),process.exit(78)),T}const u=d?.policy||null;u&&(Zt(t,u),console.log(`[chatpanel-gateway] ${d.label} — ${d.signed?"signed":"unsigned"} policy from ${d.source}`));const p=Tr({enabled:Xt(t)});console.log(`[chatpanel-gateway] certificates: ${p.on?`this computer's list is trusted too (${p.added} added to the runtime's own)`:`the runtime's own list only — ${p.why}`}`),kr(globalThis,{allow:u?.egress?(T,{local:x})=>Pr(u,T,{local:x}):null}),_e();const w=As(t),y=jr(t),$=tr(t);let B=!1;w.on("error",T=>{if(T&&T.code==="EADDRINUSE"){const x=ct(t.host)?"127.0.0.1":t.host;fetch(`http://${x}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(R=>R.ok?R.json():null).catch(()=>null).then(R=>{const j=!!(R?.version&&typeof R.tier=="string"),V=Qr({name:"gateway",self:de,holder:j?{ours:j,version:R.version}:null,managedBy:Yr(process.env),port:t.port});if(V.action==="standby"||B&&!R){if(!B)for(const P of V.lines)console.error(P);B=!0,setTimeout(()=>w.listen(t.port,t.host),Xr);return}if(j){const P=R.managedBy?` (run by ${R.managedBy})`:"";for(const[U,z]of V.lines.entries())console.error(U===0?z.replace(` on ${t.port}`,` at http://${x}:${t.port}${P}`):z)}else{const P=mn(t.port);console.error(`Port ${t.port} is held by ${P||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${le()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${T?.message||T}`),process.exit(1)}),w.listen(t.port,t.host,()=>{B&&console.log(" standby : the other gateway is gone — this copy has the port now"),B=!1,console.log(`ChatPanel Privacy Gateway v${de} on http://${t.host}:${t.port}`),w.linkHost?.start().catch(T=>console.log(` link : not started (${T?.message||T})`)),w.runtimeDefaults?.().then(T=>{for(const x of T||[])console.log(` ${x.label.toLowerCase().padEnd(9).slice(0,9)}: ${x.ok?x.already?"running":x.adopted?"already running — adopted":"started":`not started (${x.skipped})`}`)}).catch(T=>console.log(` runtime : defaults not started (${T?.message||T})`)),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token");for(const T of qa(t))console.log(` ⚠ sandbox : ${T}`);console.log(` confined : ${wn(wt({stateDir:He.dirname(le())}))}`),ut={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},un(t,{childEnv:()=>({...Za(t,process.env,qe()),...Ya(t)})}).then(T=>{Ve=T}).catch(T=>{ut={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${T?.message||T})`},console.log(` bridge : not supervised (${T?.message||T})`)}),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),ct(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),io()&&kt(J,ft()).then(T=>{T?.ok&&(console.log(` warm : seeded ${T.ingested} records from ${T.file}`),T.whole&&Ue())}).catch(()=>{});const E=()=>{y?.stop(),$.stop(),Ve?.stop(),is(w)};return process.on("SIGINT",E),process.on("SIGTERM",E),w}export{vs as RECORDS_MAX_BYTES,_l as VERSION,As as createGateway,_s as joinUpstream,Bt as parseAgentModel,Sl as start};
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 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};
1
+ import{join as Ve}from"node:path";import{deflateSync as Qe}from"node:zlib";import ve from"node:os";import{existsSync as Je,readdirSync as Ze}from"node:fs";import{randomUUID as et}from"node:crypto";import{ensureLib as Ne,modelRoot as Pe}from"./ner-engine.js";import{runtimeDtype as se,runtimeName as Oe,DTYPE_SUFFIX as tt}from"./model-runtime.js";import{verifyModelWeights as nt}from"./model-integrity.js";import{DEFAULT_STT_MODEL as Re,isEnglishOnly as me,sttModelDtype as he,isKnownSttModel as ot,sttModelEngine as G}from"./stt-models.js";import*as I from"./parakeet-engine.js";import*as _e from"./coreml-stt-engine.js";import*as te from"./indic-engine.js";import*as j from"./diarize-engine.js";import*as Y from"./segment-engine.js";import{turnsFromSpans as rt,mainLocal as lt,timeByLocal as at,audioOfLocal as st}from"@chatpanel/events/speaker-turns.js";import{diarizeApproxMB as it}from"./diarize-models.js";import*as ne from"./translate-engine.js";import*as Z from"./indictrans-engine.js";import{rawOrtAvailable as ct}from"./ort.js";import*as $ from"./vad-engine.js";import*as ee from"./echo-pair.js";import{mostlyEcho as ut}from"./aec-engine.js";import{pickSegmentLanguage as ft,detectTextLanguage as dt,needsTranslation as gt,localTranslatable as pt,normalizeLanguages as mt,normalizeLanguage as ht,decodeLanguages as _t,lineLanguage as wt,autoCandidates as yt,AUTO_LEARN_CONFIDENCE as Mt,AUTO_LEARN_SECONDS as Et,ANY_LANGUAGE_CONFIDENCE as St,AUTO_LANGUAGES as Tt}from"@chatpanel/events/speech-language.js";import*as Lt from"@chatpanel/events/speech-language.js";import{makeWarmTimer as we}from"./warm-timer.js";const p=16e3,Fe=p,$e=3*p,xt=2,At=new Set(["thank you","thanks","thank you for watching","thanks for watching","you","uh","um","hmm","hm","mm","amen","bye","okay","ok","yeah","oh","the","that","so","and","i","a","me","we","yes","no","thank you very much","subtitles by the amara.org community","you you"]);function kt(e,t){if(t>xt*p)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?At.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}const bt=12,ye=3;function Dt(e){const t=String(e||"").split(/\s+/).filter(Boolean);if(t.length<ye)return{text:String(e||"").trim(),removed:0,total:t.length};const n=l=>l.toLowerCase().replace(/[^\p{L}\p{N}']/gu,""),o=[];let r=0;for(let l=0;l<t.length;){let f=0,c=0;for(let i=1;i<=bt&&l+i*ye<=t.length;i++){let s=1;for(;l+(s+1)*i<=t.length&&t.slice(l+s*i,l+(s+1)*i).every((u,d)=>n(u)===n(t[l+d]));)s++;s>=ye&&(s-1)*i>f&&(f=(s-1)*i,c=i)}f?(o.push(...t.slice(l,l+c)),r+=f,l+=c+f):(o.push(t[l]),l++)}return{text:o.join(" "),removed:r,total:t.length}}const vt=.6,Ce=2.4;function He(e){const t=Buffer.from(String(e||""),"utf8");return t.length<40?1:t.length/Qe(t).length}function Nt(e){return String(e||"").replace(/([^\d\s]{1,8}?)\1{4,}/gu,"$1")}function Pt({cores:e=ve.availableParallelism?.()??ve.cpus().length,env:t=process.env}={}){const n=Number(t.CHATPANEL_STT_THREADS);return Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(4,Math.floor(e/2)))}function oe(e){return{intraOpNumThreads:Pt(e),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}const Ot=.12,ze=.8,Rt=.15,Ft=.5,$t=1.2,Ue=(e,t)=>e>=Ft||e>=Rt&&!(t<$t),Ct=.999,Ht=2.5;function ie(e={},t=1/0){return Ue(e.en??0,t)?"en":Object.entries(e).sort((n,o)=>o[1]-n[1])[0]?.[0]||null}function zt(e,t=[]){const n=[];return e.forEach((o,r)=>{const l=t[r]??o.lang,f=n[n.length-1];f&&f.lang===l?f.to=o.to:n.push({from:o.from,to:o.to,lang:l})}),n}function Ut(e,{base:t=null,rate:n=p}={}){const o=e||[],r=i=>{const[s,u]=Object.entries(i.scores||{}).sort((d,b)=>b[1]-d[1])[0]||[];return s&&s!=="en"&&u>=Ct?s:null},l=new Array(o.length).fill(null);for(let i=0;i<o.length;){const s=r(o[i]);let u=i+1;if(s)for(;u<o.length&&r(o[u])===s;)u++;if(s&&(o[u-1].to-o[i].from)/n>=Ht)for(let d=i;d<u;d++)l[d]=s;i=u}const f=[];let c=t;return o.forEach((i,s)=>{l[s]?c=l[s]:c!=="en"&&Ue(i.scores?.en??0,(i.to-i.from)/n)&&(c="en");const u=f[f.length-1];u&&u.lang===c?u.to=i.to:f.push({from:i.from,to:i.to,lang:c})}),f}async function Gt(e,t,n){const{spelledEnglish:o,isSpelledEnglish:r,SPELLED_ENGLISH_MIN:l,SPELLED_SHAPE_MIN:f}=Lt;if(typeof o!="function")return e;const c=[];let i=!1;for(const s of e){const u=o(s.text);if(!s.lang||s.lang==="en"||u.english<l&&!r(s.text)){c.push(s);continue}const d=u.words>=f&&u.shaped===u.words,b=[];for(let a=0;a+1<t.length;a++)t[a]>=s.from&&t[a+1]<=s.to&&b.push([t[a],t[a+1]]);if(b.length<2||d){const a=r(s.text)?await n(s.from,s.to,"en"):"";a?(c.push({...s,text:a,lang:"en"}),i=!0):c.push(s);continue}const h=[];for(const[a,S]of b){const A=await n(a,S,s.lang),z=o(A),ge=z.words>0&&z.words-z.shaped<=(z.english>=1&&z.words>=3?1:0);h.push({from:a,to:S,text:A,near:ge,lang:r(A)?"en":s.lang})}for(let a=!0;a;)a=!1,h.forEach((S,A)=>{S.lang!=="en"&&S.near&&(h[A-1]?.lang==="en"||h[A+1]?.lang==="en")&&(S.lang="en",a=!0)});if(!h.some(a=>a.lang==="en")){c.push(s);continue}const M=[];for(const a of h){const S=M[M.length-1];S&&S.lang===a.lang?(S.to=a.to,S.n++):M.push({from:a.from,to:a.to,lang:a.lang,n:1,text:a.text})}for(const a of M){const S=a.n===1&&a.lang===s.lang?a.text:await n(a.from,a.to,a.lang);S&&c.push({from:a.from,to:a.to,lang:a.lang,text:S})}i=!0}return i?c.reduce((s,u)=>{const d=s[s.length-1];return d&&d.lang===u.lang&&d.to===u.from?s[s.length-1]={...d,to:u.to,text:`${d.text} ${u.text}`}:s.push(u),s},[]):e}function jt(e,t,{frame:n=Math.round(.03*p),minPause:o=Ot*p,minPiece:r=ze*p}={}){const l=[];let f=0,c=-1;for(let i=0;i+n<=e;i+=n){const s=t(i,i+n)===!1;if(s&&c<0&&(c=i),(!s||i+2*n>e)&&c>=0){const u=s?i+n:i,d=Math.round((c+u)/2);u-c>=o&&d-f>=r&&e-d>=r&&(l.push(d),f=d),c=-1}}return l}const Bt=.12;function It(e,t=Math.round(.03*p)){const n=Math.floor(e.length/t);if(n<3)return 0;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=J(e,r*t,(r+1)*t);return o.sort(),Math.max(1e-4,o[Math.floor(n*.9)]*Bt)}let _="off",x=null,m=null,v=null,q=null,L=null,K=null,P=null;function Kt(e=x||Re,t=he(e)||se()){if(G(e)==="parakeet-tdt")return I.parakeetOnDisk(e,I.parakeetDtype(t));if(G(e)==="coreml-tdt")return _e.coremlOnDisk(e);if(G(e)==="indic-canary")return te.indicOnDisk();const n=Ve(Pe(),...e.split("/"),"onnx");if(!Je(n))return!1;const o=tt[t]??"";try{const r=Ze(n);return r.includes(`encoder_model${o}.onnx`)&&r.some(l=>l===`decoder_model_merged${o}.onnx`||l===`decoder_model${o}.onnx`)}catch{return!1}}function Dn(){return _}function ce(){return _==="ready"&&!!m}function vn(){return L}function Nn(){return{configured:_!=="off",ok:ce(),state:_,model:x,dtype:K,runtime:Oe(),error:v,warmMs:P?.warmMs??null,vad:$.state()}}function Pn(){return!!P?.pending()}function re(){return H.size>0||_==="loading"||_==="downloading"}async function Me({log:e=()=>{}}={}){if(re())return!1;P?.disarm();const t=m;if(m=null,q=null,K=null,L=null,v=null,_="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((P?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function Ge(e){return e.then(t=>(t&&!re()&&P?.arm(),t))}async function je(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null,licenseAccepted:r=null}={}){if(G(e)==="parakeet-tdt")return Wt(e,{log:t,allowDownload:n,dtype:o});if(G(e)==="coreml-tdt")return Yt(e,{log:t,allowDownload:n});if(G(e)==="indic-canary")return qt(e,{log:t,allowDownload:n,licenseAccepted:r});const l=m,f=x;let c;try{c=await Ne()}catch(h){return _="error",v=`engine load failed: ${h.message}`,t(`[stt] transformers.js not available (${h.message}) — dictation falls back to the browser engine`),!1}const s=(o&&o!=="auto"?o:null)||he(e)||se(),u=Kt(e,s);if(c.env.allowRemoteModels=u?!1:!!n,!u&&!n)return _="error",v="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const d=c.env.remoteHost,b=!ot(e);if(!u&&b)try{c.env.remoteHost="https://huggingface.co/"}catch{}_=u?"loading":"downloading",u||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${b?", from Hugging Face":""})…`));try{const h=a=>{if(!a)return;const S=typeof a.progress=="number"?Math.round(a.progress):L?.pct??0;a.status==="progress"||a.status==="download"||a.status==="initiate"?L={model:e,file:a.file||L?.file||null,pct:S}:a.status==="done"&&a.file&&t(`[stt] fetched ${a.file}`)};let M;try{M=await c.pipeline("automatic-speech-recognition",e,{dtype:s,progress_callback:h,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:oe()}})}catch(a){if(u||b||!n)throw a;t(`[stt] mirror fetch failed (${String(a.message).slice(0,80)}) — retrying from Hugging Face…`),c.env.remoteHost="https://huggingface.co/",c.env.allowRemoteModels=!0,M=await c.pipeline("automatic-speech-recognition",e,{dtype:s,progress_callback:h,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:oe()}})}if(!u)try{nt(e,{modelsDir:Pe(),log:t})}catch(a){try{await M.dispose?.()}catch{}throw a}if(m=M,x=e,_="ready",v=null,L=null,K=s,l&&l!==M)try{await l.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${s} (in-process, offline) — local dictation active`),!0}catch(h){return v=h.message,L=null,l?(m=l,x=f,_="ready"):_="error",t(`[stt] model load failed (${h.message})${l?" — keeping previous model":""}`),!1}finally{try{c.env.remoteHost=d}catch{}}}async function Wt(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null}={}){const r=m,l=x,f=I.parakeetDtype(o&&o!=="auto"?o:Xt()),c=I.parakeetOnDisk(e,f);if(!c&&!n)return _="error",v="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;_=c?"loading":"downloading",c||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const i=await I.loadRecognizer({modelId:e,dtype:f,allowDownload:n,log:t,sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:oe(),onProgress:u=>{L={model:e,file:u.file||null,pct:typeof u.pct=="number"?u.pct:L?.pct??0}}}),s=async u=>({text:await i.transcribe(u)});if(s.__transducer=!0,s.dispose=()=>i.dispose(),m=s,x=e,_="ready",v=null,L=null,K=f,r&&r!==s)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${f} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(i){return v=i.message,L=null,r?(m=r,x=l,_="ready"):_="error",t(`[stt] model load failed (${i.message})${r?" — keeping previous model":""}`),!1}}function Xt(){return I.PARAKEET_DEFAULT_DTYPE}const Be="fp16";async function Yt(e,{log:t=()=>{},allowDownload:n=!0}={}){const o=m,r=x,l=_e.coremlOnDisk(e);if(!l&&!n)return _="error",v="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;_=l?"loading":"downloading",l||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let f=null;const c=await _e.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:i=>{L={model:e,file:i.file||null,pct:typeof i.pct=="number"?i.pct:L?.pct??0}},onExit:i=>{m===f&&(m=null,q=null,_="error",v=i,P?.disarm(),t(`[stt] ${i} — reloads on the next dictation`))}});if(f=async i=>({text:await c.transcribe(i)}),f.__transducer=!0,f.dispose=()=>c.dispose(),m=f,x=e,_="ready",v=null,L=null,K=Be,o&&o!==f)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} (Core ML on the Neural Engine, helper ${c.version}, windows ${c.windows.join("/")} s, offline) — local dictation active`),!0}catch(f){return v=f.message,L=null,o?(m=o,x=r,_="ready"):_="error",t(`[stt] model load failed (${f.message})${o?" — keeping previous model":""}`),!1}}async function qt(e,{log:t=()=>{},allowDownload:n=!0,licenseAccepted:o=null}={}){const r=m,l=x,f=te.indicOnDisk();if(!f&&!n)return _="error",v="model not on disk and downloads disabled",!1;_=f?"loading":"downloading",f||(L={model:e,file:null,pct:0},t(`[stt] downloading ${e} (one-time, ~1.5 GB, from Hugging Face)…`));try{f||await te.ensureIndicFiles({licenseAccepted:o,log:t,onProgress:s=>{L={model:e,file:s.file,pct:s.pct}}});const c=await te.loadRecognizer({sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:oe(),log:t}),i=async(s,u={})=>c.transcribe(s,u);if(i.identify=(s,u)=>c.identify(s,u),i.__transducer=!0,i.__indic=!0,i.dispose=()=>c.dispose(),m=i,x=e,_="ready",v=null,L=null,K="int8",r&&r!==i)try{await r.dispose?.()}catch{}return t(`[stt] ready — ${e} (Indic-Transcribe, int8, in-process, offline) — ${te.INDIC_LICENSE.attribution}`),!0}catch(c){return v=c.message,L=null,r?(m=r,x=l,_="ready"):_="error",t(`[stt] model load failed (${c.message})${r?" — keeping previous model":""}`),!1}}const Vt=30;function Ie({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:o=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof o=="number"&&o<=Vt||e==="download"?{allowDownload:!0}:null}function Ee(e,{log:t=()=>{},warmMs:n,allowDownload:o=!0}={}){const r=Ie({mode:e,onDisk:j.modelOnDisk(),ready:j.isReady(),approxMB:it(j.activeModel())});if(r&&j.init({allowDownload:r.allowDownload&&o!==!1,warmMs:n,onLog:t}),e==="off"||Se)return;const l=Ie({mode:e,onDisk:Y.modelOnDisk(),ready:Y.isReady(),approxMB:Y.SEGMENT_MODEL_APPROX_MB});l&&Y.init({allowDownload:l.allowDownload&&o!==!1,warmMs:n,onLog:t})}let Se=!1,Te=null;function Le(e={},{log:t=()=>{}}={}){e.vad!==!1&&(Te={vad:e.vad,allowDownload:e.allowDownload,warmMs:e.warmMs},($.state()==="off"||$.state()==="error")&&$.init({allowDownload:e.allowDownload!==!1,warmMs:e.warmMs,onLog:t}))}function On(e={}){if(q&&_!=="error")return q;const t=typeof e.onLog=="function"?e.onLog:()=>{};return x=e.model||Re,Se=e.segment===!1,_="loading",P=we({warmMs:e.warmMs,busy:re,log:t,unload:()=>Me({log:t})}),q=Ge(je(x,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype,licenseAccepted:e.licenseAccepted||null})).then(n=>(n&&(Ee(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),Le(e,{log:t})),n)),q}async function Rn(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(Se=t.segment===!1);const o=G(e)==="parakeet-tdt"?I.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:I.PARAKEET_DEFAULT_DTYPE):G(e)==="coreml-tdt"?Be:G(e)==="indic-canary"?"int8":t.dtype&&t.dtype!=="auto"?t.dtype:he(e)||se();if(e===x&&ce()&&K===o)return Ee(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;P??=we({warmMs:t.warmMs,busy:re,log:n,unload:()=>Me({log:n})});const r=await Ge(je(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype,licenseAccepted:t.licenseAccepted||null}));return r&&(Ee(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),Le(t,{log:n})),r}const Qt=8,Jt=12e4,Zt=6e4,en=1200,ue=12,xe=700,Ae=.008,tn=.002,nn=4;function on(e){return e>0?Math.min(Ae,Math.max(tn,e*nn)):Ae}function rn(e){const t=Math.round(.1*p),n=Math.floor(e.length/t);if(n<5)return null;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=J(e,r*t,(r+1)*t);return o.sort(),o[Math.floor(n*.1)]}const Ke=30,ln=15e3,H=new Map,V=new Map;let Q=Promise.resolve();function Fn(){return H.size}const an=300,sn=3e3;function cn(e){const t=Number(e);return Number.isFinite(t)?Math.min(sn,Math.max(an,Math.round(t))):xe}function $n({lang:e,langs:t=null,translateTo:n=null,translateLoad:o=null,echo:r=null,redact:l=!1,diarize:f=!1,speakerLabel:c=null,endSilenceMs:i=xe,interims:s=!0,remote:u=null,poll:d=!1,format:b="f32"}={}){if(H.size>=Qt){const S=new Error("too many concurrent dictation sessions");throw S.code="too_many_sessions",S}const h=Array.isArray(t)?mt(t):null,M=typeof e=="string"&&e?e.slice(0,12):null,a={id:et(),format:b==="pcm16"?"pcm16":"f32",endSilenceMs:cn(i),lang:h?h.length===1?h[0]:h.length?null:M:M,langs:h,lastLang:null,lastDecoded:null,learned:new Set,translateTo:ht(n)||null,translateLoad:o||{},translations:Promise.resolve(),echo:r&&typeof r=="object"?ee.join(r.group,r.role):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!l,diarize:!!f,speakerLabel:typeof c=="string"&&c?c.slice(0,40):null,diarizer:f?new j.Diarizer:null,remote:u||null,interims:s!==!1&&!u,chunks:[],samples:0,listeners:new Set,poll:d?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return H.set(a.id,a),P?.disarm(),a.diarizer&&(j.retain(),Y.retain()),a.translateTo&&(ne.retain(),Z.retain()),$.retain(),Te&&($.state()==="off"||$.state()==="error")&&Le(Te),We(a),{id:a.id}}function fe(e){return H.get(String(e||""))||null}function Cn(e,t){const n=fe(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function W(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function Hn(e){const t=String(e||""),n=H.get(t);if(n)return n.poll?n.poll.splice(0):null;const o=V.get(t);return o?(clearTimeout(o.timer),V.delete(t),o.session.poll.splice(0)):null}function zn(e){return V.get(String(e||""))?.session||null}function We(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>gn(e.id).catch(()=>{}),Zt),e.idleTimer.unref?.()}function Un(e,t){const n=fe(e);if(!n||n.closed){const o=new Error("no such session");throw o.code="no_session",o}if(!(!(t instanceof Float32Array)||!t.length)){if(We(n),n.echo?.role==="mic"){ee.pushMic(n.echo,t),Xe(n);return}n.echo?.role==="reference"&&ee.pushReference(n.echo,t),n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,Xe(n)}}function Gn(e){const t=fe(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),Q=Q.then(()=>ke(t).catch(()=>{})),Q)}function jn(e,t="f32"){if(t==="pcm16"){const r=new Float32Array(Math.floor(e.length/2));for(let l=0;l<r.length;l++)r[l]=e.readInt16LE(l*2)/32768;return r}const n=e.length-e.length%4,o=new Float32Array(n/4);for(let r=0;r<o.length;r++)o[r]=e.readFloatLE(r*4);return o}function Xe(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+en-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,Q=Q.then(()=>ke(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function de(e,t,n){const o=e.samples-t,r=[];n&&r.push(n),o>0&&r.push(Ye(e).subarray(t)),e.chunks=r,e.samples=r.reduce((l,f)=>l+f.length,0),e.lastInterim=""}function Ye(e){const t=new Float32Array(e.samples);let n=0;for(const o of e.chunks)t.set(o,n),n+=o.length;return t}function un(e,t,n){const o=p/100,r=Math.max(0,e.length-t),l=Math.floor((e.length-r)/o),f=Math.max(1,Math.round(n/o));if(l<=f)return 0;const c=new Float32Array(l);for(let d=0;d<l;d++){let b=0;const h=r+d*o;for(let M=0;M<o;M++)b+=e[h+M]*e[h+M];c[d]=b/o}let i=-1,s=1/0,u=0;for(let d=0;d<f;d++)u+=c[d];for(let d=0;d+f<=l;d++)d>0&&(u+=c[d+f-1]-c[d-1]),u<s&&(s=u,i=d);return i<0?0:r+Math.round((i+f/2)*o)}function J(e,t=0,n=e.length){let o=0;const r=Math.max(1,n-t);for(let l=t;l<n;l++)o+=e[l]*e[l];return Math.sqrt(o/r)}function fn(e,t=Ae){const n=Math.round(.02*p);let o=0,r=e.length;for(let l=0;l+n<=e.length;l+=n)if(J(e,l,l+n)>=t){o=l;break}for(let l=e.length-n;l>=0;l-=n)if(J(e,l,l+n)>=t){r=l+n;break}return r>o?e.subarray(o,r):e}async function qe(e){try{const t=await Ne(),n=m?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const o=e.length>p*8?e.subarray(0,p*8):e,r=await m.processor(o),l=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),f=await m.model({...r,decoder_input_ids:l}),c={};for(const[i,s]of Object.entries(n.lang_to_id))c[i.slice(2,-2)]=Number(f.logits.data[s]);return c}catch{return null}}async function dn(e){const t=await qe(e);if(!t)return null;let n=null,o=-1/0;for(const[r,l]of Object.entries(t))l>o&&(o=l,n=r);return n}async function ke(e,{flush:t=!1}={}){if(e.closed&&!t)return;if(e.echo?.role==="mic"){const g=await ee.drain(e.echo,{force:t});g.length&&(e.chunks.push(g),e.samples+=g.length,e.pushed+=g.length)}if(!e.remote&&!ce()||!e.samples)return;e.lastDecodeAt=Date.now();let n=Ye(e);const o=n.length,r=Math.max(0,(e.pushed||0)-e.samples),l=Math.round((e.endSilenceMs||xe)/1e3*p),f=rn(n);f!==null&&(e.noiseFloor==null||f<e.noiseFloor)&&(e.noiseFloor=f);const c=on(e.noiseFloor);let i=null,s=null;$.isReady()&&(e.vad||=$.createStream(),await e.vad.advance(n,r)&&(i=e.vad.speechIn(r,r+n.length,$.ONSET),n.length>l&&(s=e.vad.speechIn(r+n.length-l,r+n.length,$.OFFSET))));const u=n.length>l&&(s!==null?!s:J(n,n.length-l)<c);if(i===!1||i===null&&J(n)<c){n.length>p*5&&(e.chunks=[n.subarray(n.length-p)],e.samples=p);return}if(!e.interims&&!t&&!u&&n.length<ue*p)return;let d=null;if(!t&&!u&&o>=ue*p&&o<Ke*p){const g=un(n,3*p,Math.round(.2*p));g>0&&g<n.length&&(d=n.subarray(g),n=n.subarray(0,g))}const b=!e.remote&&!me(x)&&!m?.__transducer;if(b&&!e.langs&&!e.lang&&!e.langTried&&n.length>=p){e.langTried=!0;const g=await dn(n);g&&(e.lang=g,W(e,{type:"language",lang:g}))}const h=t||u||o>=ue*p;let M=e.lang;if(b&&e.langs&&!e.lang){const g=e.langs.length>0,O=g?_t(e.langs):yt([...e.learned]);if(O.length===1)M=O[0];else if(M=O.includes(e.lastDecoded)?e.lastDecoded:null,(h||!M)&&n.length>=p/2){const R=await qe(n);if(R){const T=ft({scores:R,allowed:O,seconds:n.length/p,last:e.lastDecoded});M=!g&&!T.inherited&&T.confidence<St?e.lastDecoded||"en":T.lang,!g&&h&&!T.inherited&&T.confidence>=Mt&&n.length>=Et*p&&e.learned.add(T.lang)}}h&&M&&(e.lastDecoded=M)}let a="",S=null,A=null,z=null;try{if(e.remote){const g=await e.remote.transcribe(n,{lang:e.lang,langs:e.langs});a=g.text,z=g.lang||null}else{const g=m.__indic?e.langs?.length?{langs:[...new Set([...e.langs,"en"])],last:e.lastLang,choose:ie}:e.lang?{lang:e.lang}:{langs:[...Tt],last:e.lastLang,choose:ie}:me(x)?{}:{language:M||void 0,task:"transcribe"},O=m.__indic&&m.identify&&h&&g.langs&&n.length>=2*ze*p?jt(n.length,(E=>(y,k)=>J(n,y,k)>=E)(It(n))):[],R=[0,...O,n.length];let T=null;if(O.length){const E=await m.identify(n,{langs:g.langs}),y=[];for(let k=0;k+1<R.length;k++){const N=await m.identify(n.subarray(R[k],R[k+1]),{langs:g.langs});y.push({from:R[k],to:R[k+1],scores:N?.scores||{}})}if(T=Ut(y,{base:E?.scores?ie(E.scores,n.length/p):null}),T.length>1){const k=[];for(let N=0;N<T.length;N++){const w=T[N],D=w.lang&&w.lang!=="en"&&(T[N-1]?.lang==="en"||T[N+1]?.lang==="en");k.push(D?ie((await m.identify(n.subarray(w.from,w.to),{langs:g.langs}))?.scores||{},(w.to-w.from)/p):w.lang)}T=zt(T,k)}T.length<2&&(T=null)}if(T){A=[];for(const E of T){const y=await m(n.subarray(E.from,E.to),E.lang?{lang:E.lang}:{...g}),k=String(y?.text||"").trim(),N=y?.lang||E.lang||null;k&&A.push({text:k,lang:N,from:E.from,to:E.to}),N&&(g.last=N)}}else{const E=await m(n,g);a=String(E?.text||"").trim(),m.__indic&&(S=E?.lang||null),m.__indic&&a&&(A=[{text:a,lang:S,from:0,to:n.length}])}if(A&&h&&g.langs&&(A=await Gt(A,R,async(E,y,k)=>String((await m(n.subarray(E,y),{lang:k}))?.text||"").trim())),A){a=A.map(y=>y.text).join(" ");const E=new Map;for(const y of A)y.lang&&E.set(y.lang,(E.get(y.lang)||0)+(y.to-y.from));S=[...E].sort((y,k)=>k[1]-y[1])[0]?.[0]||null,(A.length<2||E.size<2)&&(A=null)}}}catch(g){W(e,{type:"error",code:"decode_failed",message:g.message,fatal:!1}),h&&de(e,o,d);return}if(!a){h&&de(e,o,d);return}{const g=Dt(a);if(g.removed&&g.removed/g.total>=vt&&g.total>=12?a="":a=g.text,a&&He(a)>Ce){const O=Nt(a);a=O.replace(/[\s\p{P}]/gu,"").length<12||He(O)>Ce?"":O}if(!a){h&&de(e,o,d);return}}const ge=o>=ue*p,be=o>=Ke*p;if(t||u||ge||be){const g=t?"flush":u?"silence":be?"overflow":"length",O=g==="flush"||g==="silence";de(e,o,d);const R=fn(n,c);if(kt(a,R?R.length:0)||e.echo?.role==="mic"&&ut(ee.verdict(e.echo,r,r+n.length)))return;let T=null,E=null;if(e.diarizer)try{const w=e.speakerLabel?null:await Y.spans(n),D=w?rt(w):[];if(D.length){const F=new Map;for(const{local:C}of at(D)){const U=st(n,D,C),le=U.length?await j.embed(U):null,ae=U.length<Fe,X=U.length<$e;F.set(C,e.diarizer.assign(le,{pinnedLabel:null,weak:ae,thin:X}))}const B=Math.round(r/p*1e3);E=D.map(C=>({startMs:B+Math.round(C.start*1e3),durationMs:Math.round((C.end-C.start)*1e3),speaker:F.get(C.local)})).filter(C=>C.speaker),T=F.get(lt(D))||null}}catch{}if(e.diarizer&&!T)try{const w=R,D=w?await j.embed(w):null,F=!!w&&w.length<Fe,B=!!w&&w.length<$e;T=e.diarizer.assign(D,{pinnedLabel:e.speakerLabel,weak:F,thin:B})}catch{}let y=null;(e.langs||e.translateTo)&&(S?y=S:z?y=z:me(x)&&!e.remote?y="en":b?y=wt(a,M||e.lang)||null:y=e.lang||dt(a,{allowed:e.langs||[],last:e.lastLang}).lang,y&&y!==e.lastLang&&(e.lastLang=y,W(e,{type:"language",lang:y})));const k=Math.round(r/p*1e3),N=A&&(e.langs||e.translateTo)?A.map((w,D)=>({text:w.text,lang:w.lang,startMs:k+Math.round(w.from/p*1e3),durationMs:Math.round((w.to-w.from)/p*1e3),last:D===A.length-1})):[{text:a,lang:y,startMs:k,durationMs:Math.round(n.length/p*1e3),last:!0}];for(const w of N){N.length>1&&w.lang&&w.lang!==e.lastLang&&(e.lastLang=w.lang,W(e,{type:"language",lang:w.lang}));const{text:D,lang:F,startMs:B}=w,C=(D.match(new RegExp("\\p{Script=Latin}","gu"))||[]).length/Math.max(1,(D.match(new RegExp("\\p{L}","gu"))||[]).length),U=Z.indictransLanguage(F)&&C<.5&&Z.state()!=="error"&&ct(),le=!!e.translateTo&&gt(F,e.translateTo)&&(U||pt(D,F)&&ne.state()!=="error"),ae=N.length>1&&E?E.filter(X=>X.startMs<B+w.durationMs&&X.startMs+X.durationMs>B):E;if(W(e,{type:"final",text:D,reason:g,endOfTurn:w.last?O:!1,durationMs:w.durationMs,startMs:B,...F?{lang:F}:{},...le?{translating:!0}:{},...T?{speaker:T}:{},...ae?.length?{turns:ae}:{}}),le){const X=e.translateTo,pe=U?Z:ne;pe.state()==="off"&&pe.init({...e.translateLoad,...U?{sessionOptions:oe()}:{}}),e.translations=e.translations.then(async()=>{await pe.ready();const De=U?await Z.translate(D,F):await ne.translate(D);W(e,{type:"translation",startMs:B,lang:F,to:X,text:De||null,...De?{}:{failed:!0}})}).catch(()=>{})}}}else a!==e.lastInterim&&(e.lastInterim=a,W(e,{type:"interim",text:a}))}async function gn(e){const t=fe(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(Q=Q.then(()=>ke(t,{flush:!0}).catch(()=>{}))),await Promise.race([t.translations,new Promise(n=>setTimeout(n,ln).unref?.())])}finally{if(W(t,{type:"end"}),t.listeners.clear(),H.delete(t.id),t.poll){const n=setTimeout(()=>V.delete(t.id),Jt);n.unref?.(),V.set(t.id,{session:t,timer:n})}t.diarizer&&(j.release(),Y.release()),t.translateTo&&(ne.release(),Z.release()),$.release(),ee.leave(t.echo),H.size===0&&ce()&&P?.arm()}return!0}function Bn(){for(const e of H.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);H.clear();for(const e of V.values())clearTimeout(e.timer);V.clear(),P?.disarm(),P=null,_="off",x=null,m=null,v=null,q=null,L=null}function In(e,t="test/fake",{warmMs:n=null,dtype:o=null}={}){m=e,x=t,_=e?"ready":"off",K=o,n!==null&&(P=we({warmMs:n,busy:re,unload:()=>Me()}),e&&P.arm())}export{Vt as AUTO_FETCH_MAX_MB,Ce as COMPRESSION_LIMIT,Ct as FROM_ENGLISH,Ht as FROM_ENGLISH_RUN_S,vt as LOOP_DROP,Bt as PAUSE_SHARE,ze as PIECE_MIN_S,Ot as PIECE_PAUSE_S,p as SAMPLE_RATE,Ft as SURE_ENGLISH,$e as THIN_SPEAKER_SAMPLES,Rt as TO_ENGLISH,$t as WEAK_ENGLISH_MIN_S,Fe as WEAK_SPEAKER_SAMPLES,Bn as _reset,In as _setPipeForTest,cn as clampEndSilence,Dt as collapseLoops,Nt as collapseRuns,He as compressionRatio,$n as createSession,Gn as decodeNow,Hn as drainEvents,gn as endSession,zn as endedSession,fe as getSession,Nn as health,On as init,ce as isReady,Ut as languageGroups,kt as looksHallucinated,Kt as modelOnDisk,rn as noiseFloorOf,jt as pauseCuts,It as pauseLevel,vn as progress,Un as pushAudio,un as quietestCut,zt as relabelGroups,Gt as respellEnglish,se as runtimeDtype,Oe as runtimeName,ie as segmentLanguage,Fn as sessionCount,Rn as setModel,on as silenceGate,Ie as speakerPlan,Dn as state,oe as sttSessionOptions,Pt as sttThreads,Cn as subscribe,jn as toFloat32,Me as unload,Pn as warmPending};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.119.0";export{o as VERSION};
1
+ const o="0.121.0";export{o as VERSION};