@chatpanel/gateway 0.105.1 → 0.116.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 +2 -2
- package/src/aec-engine.js +1 -0
- package/src/echo-pair.js +1 -0
- package/src/egress.js +1 -1
- package/src/indic-engine.js +1 -0
- package/src/indictrans-engine.js +1 -0
- package/src/parakeet-engine.js +2 -2
- package/src/server.js +30 -30
- package/src/stt-engine.js +1 -1
- package/src/stt-models.js +1 -1
- package/src/stt-remote.js +1 -1
- package/src/translate-engine.js +1 -0
- package/src/vad-engine.js +1 -0
- package/src/version.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.116.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": {
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
26
26
|
"@chatpanel/bridge": "^0.47.0",
|
|
27
|
-
"@chatpanel/events": "^0.
|
|
27
|
+
"@chatpanel/events": "^0.388.0",
|
|
28
28
|
"@chatpanel/pii": "^0.15.0",
|
|
29
29
|
"@huggingface/transformers": "^4.2.0",
|
|
30
30
|
"defuddle": "^0.19.4",
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as R,mkdirSync as X,createWriteStream as G,renameSync as J,rmSync as W,readFileSync as Q}from"node:fs";import{createHash as V}from"node:crypto";import{join as k}from"node:path";import{modelRoot as Y}from"./ner-engine.js";import{getOrt as Z,ortProviders as tt,rawOrtAvailable as H}from"./ort.js";const et=16e3,p=512,m=128,M=p/2+1,ot="https://raw.githubusercontent.com/fastrepl/anarlog/b14809dcd80fe80c5158c8a9f5a19fa173878b12/crates/aec/data/models",E=Object.freeze({"model_128_1.onnx":"a060e46a6bebed03d6360262d814851dc6c2806cec7c1b6a388e617cae7c082c","model_128_2.onnx":"6b6e312f701a3fad2aac2981ca1ed978d25dffa0bc8da9f33235a2e91f56705a"}),q=7.3;function v(){return k(Y(),"fastrepl","dtln-aec-128")}const B=new Map;function rt(t){if(B.has(t))return B.get(t);const r=new Float64Array(t/2),y=new Float64Array(t/2);for(let i=0;i<t/2;i++)r[i]=Math.cos(-2*Math.PI*i/t),y[i]=Math.sin(-2*Math.PI*i/t);const n={c:r,s:y};return B.set(t,n),n}function D(t,r,y=!1){const n=t.length;for(let o=1,f=0;o<n;o++){let s=n>>1;for(;f&s;s>>=1)f^=s;f^=s,o<f&&([t[o],t[f]]=[t[f],t[o]],[r[o],r[f]]=[r[f],r[o]])}const{c:i,s:c}=rt(n);for(let o=2;o<=n;o<<=1){const f=n/o;for(let s=0;s<n;s+=o)for(let a=0;a<o/2;a++){const w=i[a*f],l=y?-c[a*f]:c[a*f],h=s+a,u=h+o/2,g=t[u]*w-r[u]*l,d=t[u]*l+r[u]*w;t[u]=t[h]-g,r[u]=r[h]-d,t[h]+=g,r[h]+=d}}if(y)for(let o=0;o<n;o++)t[o]/=n,r[o]/=n}function dt(t,r,{maxMs:y=1e3,minCorr:n=.3}={}){const i=et/100,c=Math.floor(Math.min(t.length,r.length)/i);if(c<200)return{delay:0,corr:0};const o=l=>{const h=new Float64Array(c);for(let d=0;d<c;d++){let x=0;for(let b=0;b<i;b++)x+=l[d*i+b]**2;h[d]=Math.log10(x/i+1e-9)}let u=0;for(const d of h)u+=d;u/=c;let g=0;for(const d of h)g+=(d-u)**2;g=Math.sqrt(g/c)+1e-9;for(let d=0;d<c;d++)h[d]=(h[d]-u)/g;return h},f=o(t),s=o(r);let a=0,w=-1;for(let l=0;l<=Math.min(y/10,c-100);l++){let h=0;for(let u=l;u<c;u++)h+=f[u]*s[u-l];h/=c-l,h>w&&(w=h,a=l)}return w>n?{delay:a*i,corr:w}:{delay:0,corr:w}}function ht(t,r,y,{frame:n=1600,speakersOn:i=1e-5}={}){let c=0,o=0,f=0,s=0;for(let a=0;a+n<=t.length;a+=n){s++;let w=0;for(let l=a;l<a+n;l++)w+=y[l]*y[l];if(!(w/n<=i)){f++;for(let l=a;l<a+n;l++)c+=t[l]*t[l],o+=r[l]*r[l]}}return{share:s?f/s:0,db:f?10*Math.log10((c+1e-12)/(o+1e-12)):0}}function yt({share:t,db:r}){return t>.5&&r>10}let A="off",P=null,S=null,O=null,C=null,j=null;function pt(){return A}function z(){return A==="ready"&&(!!O||!!j)}function wt(){return{configured:A!=="off",ok:z(),state:A,error:P,available:H(),approxMB:q}}function nt(){return Object.keys(E).every(t=>R(k(v(),t)))}const K=t=>V("sha256").update(Q(t)).digest("hex");async function at(t,{fetchImpl:r=fetch,log:y}){const n=v();X(n,{recursive:!0});const i=k(n,t),c=`${i}.part`,o=await r(`${ot}/${t}`);if(!o.ok||!o.body)throw new Error(`HTTP ${o.status} for ${t}`);if(await new Promise((f,s)=>{const a=G(c),w=o.body.getReader(),l=()=>w.read().then(({done:h,value:u})=>{if(h){a.end(f);return}a.write(Buffer.from(u)),l()},s);a.on("error",s),l()}),K(c)!==E[t])throw W(c,{force:!0}),new Error(`${t} does not match its pinned hash — not used`);J(c,i),y(`[aec] fetched ${t}`)}async function st({allowDownload:t=!0,log:r=()=>{},fetchImpl:y}={}){if(!H())return A="error",P="echo cancellation needs the npm gateway (the standalone binary cannot run it)",!1;try{if(!nt()){if(!t)throw new Error("model not on disk and downloads disabled");A="downloading",r(`[aec] downloading DTLN-aec (one-time, ~${q} MB)…`);for(const o of Object.keys(E))R(k(v(),o))||await at(o,{fetchImpl:y,log:r})}for(const[o,f]of Object.entries(E))if(K(k(v(),o))!==f)throw W(k(v(),o),{force:!0}),new Error(`${o} changed on disk — removed`);A="loading",C=await Z();const n={executionProviders:tt(),intraOpNumThreads:1,interOpNumThreads:1},[i,c]=await Promise.all(Object.keys(E).map(o=>C.InferenceSession.create(k(v(),o),n)));return O={s1:i,s2:c},A="ready",P=null,r("[aec] ready — the microphone is cleaned against what the speakers play (DTLN-aec)"),!0}catch(n){return A="error",P=n.message,r(`[aec] unavailable (${n.message}) — the text-level echo guard alone`),!1}}function mt(t={}){return S&&A!=="error"||(A="loading",S=st({allowDownload:t.allowDownload!==!1,log:typeof t.onLog=="function"?t.onLog:()=>{},fetchImpl:t.fetchImpl})),S}function T(t,r){const y=r==="state"?4:3;for(const n of Object.values(t))if(n.dims.length===y)return n;return Object.values(t)[r==="state"?1:0]}function bt(){const t=[1,2,128,2];let r=null,y=null;const n=new Float32Array(p),i=new Float32Array(p),c=new Float32Array(p);let o=new Float32Array(0),f=new Float32Array(0);const s=new Float64Array(p),a=new Float64Array(p),w=new Float32Array(M),l=new Float32Array(M);async function h(u,g){n.copyWithin(0,m),n.set(u,p-m),i.copyWithin(0,m),i.set(g,p-m);for(let e=0;e<p;e++)s[e]=n[e],a[e]=0;D(s,a);const d=Float64Array.from(s.subarray(0,M)),x=Float64Array.from(a.subarray(0,M));for(let e=0;e<M;e++)w[e]=Math.hypot(d[e],x[e]);for(let e=0;e<p;e++)s[e]=i[e],a[e]=0;D(s,a);for(let e=0;e<M;e++)l[e]=Math.hypot(s[e],a[e]);const b=C.Tensor;r||=new b("float32",new Float32Array(256*2),t),y||=new b("float32",new Float32Array(256*2),t);const _=O.s1.inputNames,F=await O.s1.run({[_[0]]:new b("float32",Float32Array.from(w),[1,1,M]),[_[1]]:r,[_[2]]:new b("float32",Float32Array.from(l),[1,1,M])}),I=T(F,"main").data;r=T(F,"state");for(let e=0;e<M;e++)s[e]=d[e]*I[e],a[e]=x[e]*I[e];for(let e=1;e<p/2;e++)s[p-e]=s[e],a[p-e]=-a[e];D(s,a,!0);const L=new Float32Array(p);for(let e=0;e<p;e++)L[e]=s[e];const $=O.s2.inputNames,N=await O.s2.run({[$[0]]:new b("float32",L,[1,1,p]),[$[1]]:y,[$[2]]:new b("float32",Float32Array.from(i),[1,1,p])}),U=T(N,"main").data;y=T(N,"state"),c.copyWithin(0,m),c.fill(0,p-m);for(let e=0;e<p;e++)c[e]+=U[e];return c.slice(0,m)}return{async process(u,g){if(j)return j(u,g);if(!z())return u;const d=new Float32Array(o.length+u.length);d.set(o),d.set(u,o.length);const x=new Float32Array(f.length+g.length);x.set(f),x.set(g.subarray(0,u.length),f.length);const b=Math.floor(d.length/m),_=new Float32Array(b*m);for(let F=0;F<b;F++)_.set(await h(d.subarray(F*m,(F+1)*m),x.subarray(F*m,(F+1)*m)),F*m);return o=d.slice(b*m),f=x.slice(b*m),_}}}function gt(){A="off",P=null,S=null,O=null,j=null}function At(t){j=t||null,A=t?"ready":"off"}export{q as AEC_APPROX_MB,E as AEC_FILES,ot as AEC_SOURCE,p as BLOCK,m as HOP,et as SAMPLE_RATE,gt as _reset,At as _setForTest,v as aecDir,bt as createCanceller,ht as echoDrop,dt as estimateDelay,D as fft,wt as health,mt as init,z as isReady,nt as modelOnDisk,yt as mostlyEcho,pt as state};
|
package/src/echo-pair.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import*as w from"./aec-engine.js";const f=w.SAMPLE_RATE,M=20*f,A=12*f,c=f/10,F=5*f,x=8*f,_=4*f,d=Math.round(.3*f),v=1500,I=6*f,y=new Map;function D(e,t){const r=String(e||"").slice(0,120);if(!r||t!=="mic"&&t!=="reference")return null;const a=y.get(r)||{reference:null,mic:null};y.set(r,a);const l={group:r,role:t,wall0:1/0,received:0,buf:new Float32Array(0),bufStart:0,raw:[],rawSamples:0,rawStart:0,waitingSince:0,history:new Float32Array(0),historyStart:0,lag:0,lagCorr:0,measuredAt:0,started:!1,frames:new Map,canceller:null};return a[t]=l,l}function T(e){if(!e)return;const t=y.get(e.group);t&&(t[e.role]===e&&(t[e.role]=null),!t.reference&&!t.mic&&y.delete(e.group))}const p=(e,t)=>{const r=new Float32Array(e.length+t.length);return r.set(e),r.set(t,e.length),r};function b(e,t,r){e.received+=t,e.wall0=Math.min(e.wall0,r-e.received/f*1e3)}function W(e,t,r=Date.now()){if(b(e,t.length,r),e.buf=p(e.buf,t),e.buf.length>M){const a=e.buf.length-M;e.buf=e.buf.slice(a),e.bufStart+=a}}function N(e,t,r=Date.now()){b(e,t.length,r),e.raw.push(t),e.rawSamples+=t.length,e.waitingSince||(e.waitingSince=r)}function C(e,t,r){return Math.round((e.wall0-t.wall0)/1e3*f+r)-e.lag}function E(e,t,r,a){const l=new Float32Array(a),n=C(e,t,r);for(let o=0;o<a;o++){const s=n+o-t.bufStart;s>=0&&s<t.buf.length&&(l[o]=t.buf[s])}return l}function R(e,t,r=e.history,a=e.historyStart){if(r.length<_)return!1;const l=Math.min(x,r.length),n=a+r.length-l,o=r.subarray(r.length-l),s=e.lag;e.lag=0;const u=E(e,t,n+d,l);e.lag=s;let g=0;for(const S of u)g+=S*S;if(g/u.length<1e-6)return!1;const{delay:i,corr:h}=w.estimateDelay(o,u,{maxMs:1e3+d/f*1e3});if(h>.3){const S=i-d;Math.abs(S-e.lag)>f/50&&(e.canceller=null),e.lag=S,e.lagCorr=h}return h>.3}async function U(e,{force:t=!1,now:r=Date.now()}={}){if(!e?.rawSamples)return new Float32Array(0);const a=y.get(e.group)?.reference||null;let l=e.rawSamples;if(a&&w.isReady()&&!t){const h=Math.floor((a.wall0+(a.bufStart+a.buf.length)/f*1e3-e.wall0)/1e3*f)+e.lag-e.rawStart;h<l&&r-e.waitingSince<v&&(l=Math.max(0,Math.floor(h/w.HOP)*w.HOP))}let n=new Float32Array(0);for(const h of e.raw)n=p(n,h);if(a&&w.isReady()&&!e.lagCorr&&!e.started&&!t&&n.length<I){if(!R(e,a,n,e.rawStart))return new Float32Array(0);l=e.rawSamples}if(e.started=!0,!l)return new Float32Array(0);const o=n.subarray(l);n=n.slice(0,l),e.raw=o.length?[o.slice()]:[],e.rawSamples=o.length,e.waitingSince=o.length?r:0;const s=e.rawStart;if(e.rawStart+=l,e.history=p(e.history,n),e.history.length>A){const h=e.history.length-A;e.history=e.history.slice(h),e.historyStart+=h}if(!a||!w.isReady())return n;const u=e.historyStart+e.history.length;(!e.lagCorr||u-e.measuredAt>=F)&&(R(e,a)||e.lagCorr)&&(e.measuredAt=u);const g=E(e,a,s,n.length);e.canceller||=w.createCanceller();let i;try{i=await e.canceller.process(n,g)}catch{return n}return i.length<n.length&&t&&(i=p(i,n.subarray(i.length))),P(e,s,n,i,g),i}function P(e,t,r,a,l){for(let n=0;n+c<=a.length;n+=c){let o=0,s=0,u=0;for(let g=n;g<n+c;g++)o+=r[g]*r[g],s+=a[g]*a[g],u+=l[g]*l[g];e.frames.set(Math.floor((t+n)/c),[o/c,s/c,u/c])}if(e.frames.size>3e3)for(const n of e.frames.keys()){if(e.frames.size<=3e3)break;e.frames.delete(n)}}function j(e,t,r){let a=0,l=0,n=0,o=0;for(let s=Math.floor(t/c);s*c<r;s++){const u=e?.frames.get(s);u&&(o++,!(u[2]<=1e-5)&&(n++,a+=u[0],l+=u[1]))}return{share:o?n/o:0,db:n?10*Math.log10((a+1e-12)/(l+1e-12)):0,lagMs:Math.round((e?.lag||0)/f*1e3)}}function q(){y.clear()}export{q as _reset,U as drain,D as join,T as leave,N as pushMic,W as pushReference,j as verdict};
|
package/src/egress.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{confinedLine as $}from"./confine.js";import{searchEngines as E}from"./retrieval/search-apis.js";import{linkPaths as S}from"@chatpanel/events/link-routes.js";import{isBlockedHost as g}from"@chatpanel/pii";const L=()=>new Date().toISOString();function y(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),n=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[n]||"",scheme:n}}catch{return null}}const m=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:g(t,{allowLoopback:!1,allowPrivate:!1})&&!g(t,{allowLoopback:!0,allowPrivate:!0})};function A({clock:e=L}={}){const t=new Map;return{record(n){const r=y(n);if(!r||!r.host)return;const u=`${r.scheme}://${r.host}:${r.port}`,s=e(),c=t.get(u);if(c){c.count+=1,c.lastAt=s;return}t.set(u,{host:r.host,port:r.port,scheme:r.scheme,local:m(r.host),count:1,firstAt:s,lastAt:s})},snapshot(){return[...t.values()].sort((n,r)=>n.local===r.local?r.count-n.count:n.local?1:-1)},reset(){t.clear()}}}let b=null;function N(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const n=A();let r=t;n.setGate=l=>{r=l},n.blocked=[];const u=l=>{let i=null;try{i=y(l),n.record(l)}catch{}if(!r||!i?.host)return null;let h=!0;try{h=r(`${i.scheme}://${i.host}:${i.port}`,{local:m(i.host)})}catch{h=!0}if(h)return null;const o=`${i.host}:${i.port}`;n.blocked.includes(o)||n.blocked.push(o);const a=new Error(`egress to ${i.host} is blocked by your organisation’s policy`);return a.code="EGRESS_POLICY",a},s=e.fetch;typeof s=="function"&&(e.fetch=function(i,h){const o=u(i);return o?Promise.reject(o):s.call(this,i,h)});const c=e.WebSocket;return typeof c=="function"&&(e.WebSocket=new Proxy(c,{construct(l,i,h){const o=u(i[0]);if(o)throw o;return Reflect.construct(l,i,h)}})),e.__chatpanelEgress=n,e===globalThis&&(b=n),n}function P(){return b||(globalThis.__chatpanelEgress??null)}function f(e){try{return new URL(e).host}catch{return String(e||"")}}function x(e={},t=process.env,n=process.platform,r=process.arch){const u=[],s=(a,p,{when:d="always",off:w=null,local:v=!1,data:k=""}={})=>{a&&u.push({host:a,purpose:p,when:d,off:w,local:v,data:k})};s("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),s("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),s("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),t.CHATPANEL_ORT_DIR||s("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"}),n==="darwin"&&r==="arm64"&&s("registry.npmjs.org","the Apple on-device helper, for an install that came without it (the standalone binary)",{when:"Install on the Apple on-device row, `--install` or `--fetch-apple-helper` — never when the helper is already here",off:"do not run them; the npm package and the desktop app carry the helper and never fetch it",data:"nothing — this gateway version's package and its checksum"});const c=e.link?.enabled===!1?null:S(e.link||{}).relay;if(c){const a=new URL(c).host;s(a,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone or a partner server is paired (Settings › Link your phone, `chatpanel-gateway link pair`), and while pairing",off:"link.enabled = false, or remove every paired device",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}s("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const l=e.search?.searxng?.url||"";if(l){let a=l;try{a=new URL(l).host}catch{}s(a,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(a)})}if(e.search?.provider!=="searxng"){s("www.startpage.com","web search: the built-in results-page search, one of three engines",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),s("html.duckduckgo.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"}),s("www.bing.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"});for(const a of E(e).filter(p=>p.kind==="api"&&p.enabled!==!1))s(a.api.host,`web search: ${a.api.name} (search API${a.api.needsKey?", with the key you gave it":", no key"})`,{when:"the same as www.startpage.com — one engine per search, a keyed API asked first",off:`search.apis: [{ id: "${a.api.id}", enabled: false }]`,data:"the same query"})}if(e.read?.remote?.url){let a=e.read.remote.url;try{a=new URL(e.read.remote.url).host}catch{}s(a,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(a)})}const i={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[a,p]of Object.entries(i)){const d=e.capabilities?.[a];if(!d?.url||d.provider==="embedded")continue;let w=d.url;try{w=new URL(d.url).host}catch{}s(w,`${p.what}${d.service?` (the ${d.service} container, started under Settings › Runtime)`:` (${d.adapter} at the address you configured)`}`,{when:`a client calls /v1/${a}`,off:d.service?`stop the ${d.service} service under Settings › Runtime`:`capabilities.${a} = null`,data:`${p.data}${d.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(w)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(s("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),s("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[a,p]of Object.entries(e.upstreams||{}))p?.baseUrl&&s(f(p.baseUrl),`model upstream "${a}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a}`,off:`upstreams.${a}.baseUrl`,local:m(f(p.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const a of e.destinations||[])a?.baseUrl&&s(f(a.baseUrl),`destination "${a.id||a.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a.id||"it"}`,off:"destinations[]",local:m(f(a.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});s("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&s(f(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:m(f(e.ner.url).split(":")[0]),data:"the text being redacted"});const h=e.tts||{};if(h.provider==="openai"||h.provider==="elevenlabs"){const a=h.remote?.baseUrl?f(h.remote.baseUrl):h.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";s(a,`remote read-aloud voice (${h.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:h.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}n==="darwin"&&e.runtime?.heatwatch!==!1&&s("127.0.0.1:7878","live memory: will this local model fit in what is free now? (Heatwatch, when installed)",{when:"before the Runtime starts a local model, and GET /v1/runtime/plan",off:"runtime.heatwatch = false",local:!0,data:"a number — the memory the model needs; never chat content"});const o=e.bridge?.url||"http://127.0.0.1:4319";return s(f(o),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),u}function O(e,{ledger:t=P(),version:n="",startedAt:r=null,env:u=process.env,managed:s=null,certificates:c=null,linkPartners:l=null,confined:i=null}={}){const h=x(e,u);for(const o of l||[])!o.host||o.route!=="link"&&o.route!=="relay"||h.some(a=>a.host===o.host)||h.push({host:o.host,purpose:`ChatPanel Link: the relay partner "${o.partner?.name||o.name}" reaches this gateway through`,when:"while that partner device is paired",off:`remove it: chatpanel-gateway link revoke ${o.id}`,data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"});return{ok:!0,version:n,since:r?new Date(r).toISOString():null,...c?{certificates:c}:{},...i?{confined:i}:{},...s?{managed:s,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests and sockets. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:h,...l?{link:{partners:l.map(o=>({id:o.id,partner:o.partner?.name||o.name,scopes:o.scopes||[],route:o.route||null,host:o.host||null,...o.folder?{folder:o.folder}:{},pairedAt:o.pairedAt||null,lastSeen:o.lastSeen||null,online:!!o.online}))}}:{}}}function _(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const n of e.observed||[])t.push(` ${n.local?"[local] ":""}${n.scheme}://${n.host}:${n.port} ×${n.count} last ${n.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const n of e.declared||[])t.push(` ${n.local?"[local] ":""}${n.host}`),t.push(` ${n.purpose}`),t.push(` when: ${n.when}${n.off?` · off: ${n.off}`:""}`),n.data&&t.push(` sends: ${n.data}`);if(e.certificates){const n=e.certificates;t.push(""),t.push("CERTIFICATES — whose word is taken that a server is who it says"),t.push(n.on?` the runtime's own list, and this computer's (${n.added} added) — what a company proxy that re-signs HTTPS needs; checks stay on`:` the runtime's own list only${n.why?` — ${n.why}`:""}`),t.push(" off: tls.systemCa: false in the config, or CHATPANEL_SYSTEM_CA=off, then restart")}if(e.confined&&(t.push(""),t.push("CONFINEMENT — what this process itself can reach on this computer"),t.push(` ${$(e.confined)}`),e.confined.on&&t.push(" checked at start: home folder listed "+(e.confined.homeListed?"YES":"no")+" · home folder written "+(e.confined.homeWritten?"YES":"no")+" · sandbox runtime written "+(e.confined.fenceWritten?"YES":"no")+" · own folder written "+(e.confined.stateWritten?"yes":"NO"))),e.link){t.push(""),t.push("LINK PARTNERS — servers the owner paired to reach this gateway over ChatPanel Link"),e.link.partners?.length||t.push(" (none — no partner can reach this gateway until you pair one)");for(const n of e.link.partners||[]){const r=n.lastSeen?new Date(n.lastSeen).toISOString():"never";t.push(` partner:${n.partner} scopes: ${n.scopes.join(", ")||"none"} agents: ${n.scopes.includes("agents")?"yes":"no"}`),t.push(` route: ${n.route||"?"}${n.host?` via ${n.host}`:""} · last seen ${r}${n.online?" (online)":""}`),n.scopes.includes("agents")&&t.push(` agents run as yours do (your Coding Agents settings and sandbox), in ${n.folder||"its folder"}; it never answers their approval prompts`),t.push(` revoke: chatpanel-gateway link revoke ${n.id}`)}}return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,n])=>n).map(([n,r])=>r===!0?n:`${n}=${r}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
|
|
1
|
+
import{confinedLine as $}from"./confine.js";import{searchEngines as E}from"./retrieval/search-apis.js";import{linkPaths as S}from"@chatpanel/events/link-routes.js";import{isBlockedHost as g}from"@chatpanel/pii";const L=()=>new Date().toISOString();function y(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),n=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[n]||"",scheme:n}}catch{return null}}const m=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:g(t,{allowLoopback:!1,allowPrivate:!1})&&!g(t,{allowLoopback:!0,allowPrivate:!0})};function A({clock:e=L}={}){const t=new Map;return{record(n){const r=y(n);if(!r||!r.host)return;const u=`${r.scheme}://${r.host}:${r.port}`,s=e(),c=t.get(u);if(c){c.count+=1,c.lastAt=s;return}t.set(u,{host:r.host,port:r.port,scheme:r.scheme,local:m(r.host),count:1,firstAt:s,lastAt:s})},snapshot(){return[...t.values()].sort((n,r)=>n.local===r.local?r.count-n.count:n.local?1:-1)},reset(){t.clear()}}}let b=null;function N(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const n=A();let r=t;n.setGate=l=>{r=l},n.blocked=[];const u=l=>{let i=null;try{i=y(l),n.record(l)}catch{}if(!r||!i?.host)return null;let h=!0;try{h=r(`${i.scheme}://${i.host}:${i.port}`,{local:m(i.host)})}catch{h=!0}if(h)return null;const o=`${i.host}:${i.port}`;n.blocked.includes(o)||n.blocked.push(o);const a=new Error(`egress to ${i.host} is blocked by your organisation’s policy`);return a.code="EGRESS_POLICY",a},s=e.fetch;typeof s=="function"&&(e.fetch=function(i,h){const o=u(i);return o?Promise.reject(o):s.call(this,i,h)});const c=e.WebSocket;return typeof c=="function"&&(e.WebSocket=new Proxy(c,{construct(l,i,h){const o=u(i[0]);if(o)throw o;return Reflect.construct(l,i,h)}})),e.__chatpanelEgress=n,e===globalThis&&(b=n),n}function P(){return b||(globalThis.__chatpanelEgress??null)}function f(e){try{return new URL(e).host}catch{return String(e||"")}}function x(e={},t=process.env,n=process.platform,r=process.arch){const u=[],s=(a,p,{when:d="always",off:w=null,local:v=!1,data:k=""}={})=>{a&&u.push({host:a,purpose:p,when:d,off:w,local:v,data:k})};s("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),s("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),s("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),s("raw.githubusercontent.com","the meeting echo canceller's weights (DTLN-aec, ~7 MB, pinned commit and hashes)",{when:"the first meeting captured with both the microphone and what is playing",off:"stt.aec = false, or the same switches as dl.chatpanel.net",data:"the file path being downloaded"}),t.CHATPANEL_ORT_DIR||s("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"}),n==="darwin"&&r==="arm64"&&s("registry.npmjs.org","the Apple on-device helper, for an install that came without it (the standalone binary)",{when:"Install on the Apple on-device row, `--install` or `--fetch-apple-helper` — never when the helper is already here",off:"do not run them; the npm package and the desktop app carry the helper and never fetch it",data:"nothing — this gateway version's package and its checksum"});const c=e.link?.enabled===!1?null:S(e.link||{}).relay;if(c){const a=new URL(c).host;s(a,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone or a partner server is paired (Settings › Link your phone, `chatpanel-gateway link pair`), and while pairing",off:"link.enabled = false, or remove every paired device",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}s("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const l=e.search?.searxng?.url||"";if(l){let a=l;try{a=new URL(l).host}catch{}s(a,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(a)})}if(e.search?.provider!=="searxng"){s("www.startpage.com","web search: the built-in results-page search, one of three engines",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),s("html.duckduckgo.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"}),s("www.bing.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"});for(const a of E(e).filter(p=>p.kind==="api"&&p.enabled!==!1))s(a.api.host,`web search: ${a.api.name} (search API${a.api.needsKey?", with the key you gave it":", no key"})`,{when:"the same as www.startpage.com — one engine per search, a keyed API asked first",off:`search.apis: [{ id: "${a.api.id}", enabled: false }]`,data:"the same query"})}if(e.read?.remote?.url){let a=e.read.remote.url;try{a=new URL(e.read.remote.url).host}catch{}s(a,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(a)})}const i={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions (ElevenLabs: /speech-to-text)",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[a,p]of Object.entries(i)){const d=e.capabilities?.[a];if(!d?.url||d.provider==="embedded")continue;let w=d.url;try{w=new URL(d.url).host}catch{}s(w,`${p.what}${d.service?` (the ${d.service} container, started under Settings › Runtime)`:` (${d.adapter} at the address you configured)`}`,{when:`a client calls /v1/${a}`,off:d.service?`stop the ${d.service} service under Settings › Runtime`:`capabilities.${a} = null`,data:`${p.data}${d.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(w)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(s("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),s("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[a,p]of Object.entries(e.upstreams||{}))p?.baseUrl&&s(f(p.baseUrl),`model upstream "${a}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a}`,off:`upstreams.${a}.baseUrl`,local:m(f(p.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const a of e.destinations||[])a?.baseUrl&&s(f(a.baseUrl),`destination "${a.id||a.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a.id||"it"}`,off:"destinations[]",local:m(f(a.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});s("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&s(f(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:m(f(e.ner.url).split(":")[0]),data:"the text being redacted"});const h=e.tts||{};if(h.provider==="openai"||h.provider==="elevenlabs"){const a=h.remote?.baseUrl?f(h.remote.baseUrl):h.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";s(a,`remote read-aloud voice (${h.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:h.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}n==="darwin"&&e.runtime?.heatwatch!==!1&&s("127.0.0.1:7878","live memory: will this local model fit in what is free now? (Heatwatch, when installed)",{when:"before the Runtime starts a local model, and GET /v1/runtime/plan",off:"runtime.heatwatch = false",local:!0,data:"a number — the memory the model needs; never chat content"});const o=e.bridge?.url||"http://127.0.0.1:4319";return s(f(o),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),u}function O(e,{ledger:t=P(),version:n="",startedAt:r=null,env:u=process.env,managed:s=null,certificates:c=null,linkPartners:l=null,confined:i=null}={}){const h=x(e,u);for(const o of l||[])!o.host||o.route!=="link"&&o.route!=="relay"||h.some(a=>a.host===o.host)||h.push({host:o.host,purpose:`ChatPanel Link: the relay partner "${o.partner?.name||o.name}" reaches this gateway through`,when:"while that partner device is paired",off:`remove it: chatpanel-gateway link revoke ${o.id}`,data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"});return{ok:!0,version:n,since:r?new Date(r).toISOString():null,...c?{certificates:c}:{},...i?{confined:i}:{},...s?{managed:s,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests and sockets. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:h,...l?{link:{partners:l.map(o=>({id:o.id,partner:o.partner?.name||o.name,scopes:o.scopes||[],route:o.route||null,host:o.host||null,...o.folder?{folder:o.folder}:{},pairedAt:o.pairedAt||null,lastSeen:o.lastSeen||null,online:!!o.online}))}}:{}}}function _(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const n of e.observed||[])t.push(` ${n.local?"[local] ":""}${n.scheme}://${n.host}:${n.port} ×${n.count} last ${n.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const n of e.declared||[])t.push(` ${n.local?"[local] ":""}${n.host}`),t.push(` ${n.purpose}`),t.push(` when: ${n.when}${n.off?` · off: ${n.off}`:""}`),n.data&&t.push(` sends: ${n.data}`);if(e.certificates){const n=e.certificates;t.push(""),t.push("CERTIFICATES — whose word is taken that a server is who it says"),t.push(n.on?` the runtime's own list, and this computer's (${n.added} added) — what a company proxy that re-signs HTTPS needs; checks stay on`:` the runtime's own list only${n.why?` — ${n.why}`:""}`),t.push(" off: tls.systemCa: false in the config, or CHATPANEL_SYSTEM_CA=off, then restart")}if(e.confined&&(t.push(""),t.push("CONFINEMENT — what this process itself can reach on this computer"),t.push(` ${$(e.confined)}`),e.confined.on&&t.push(" checked at start: home folder listed "+(e.confined.homeListed?"YES":"no")+" · home folder written "+(e.confined.homeWritten?"YES":"no")+" · sandbox runtime written "+(e.confined.fenceWritten?"YES":"no")+" · own folder written "+(e.confined.stateWritten?"yes":"NO"))),e.link){t.push(""),t.push("LINK PARTNERS — servers the owner paired to reach this gateway over ChatPanel Link"),e.link.partners?.length||t.push(" (none — no partner can reach this gateway until you pair one)");for(const n of e.link.partners||[]){const r=n.lastSeen?new Date(n.lastSeen).toISOString():"never";t.push(` partner:${n.partner} scopes: ${n.scopes.join(", ")||"none"} agents: ${n.scopes.includes("agents")?"yes":"no"}`),t.push(` route: ${n.route||"?"}${n.host?` via ${n.host}`:""} · last seen ${r}${n.online?" (online)":""}`),n.scopes.includes("agents")&&t.push(` agents run as yours do (your Coding Agents settings and sandbox), in ${n.folder||"its folder"}; it never answers their approval prompts`),t.push(` revoke: chatpanel-gateway link revoke ${n.id}`)}}return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,n])=>n).map(([n,r])=>r===!0?n:`${n}=${r}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
|
|
2
2
|
`)}export{A as createEgressLedger,x as declaredEgress,O as egressAudit,P as egressLedger,_ as formatAudit,N as installEgressLedger};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as H,readFileSync as z,mkdirSync as Q,createWriteStream as V,createReadStream as ee,renameSync as te,rmSync as Z}from"node:fs";import{createHash as ne}from"node:crypto";import{join as A}from"node:path";import{modelRoot as oe}from"./ner-engine.js";import{getOrt as re,ortProviders as ce,rawOrtAvailable as ae}from"./ort.js";import{fft as se}from"./aec-engine.js";import{INDIC_LICENSE as M,licenseAcceptance as ie}from"./stt-models.js";const Ne="bodhan-ai/indic-transcribe-core",fe=ie(M);function F(){return A(oe(),"bodhan-ai","indic-transcribe-core-int8")}const de="https://dl.chatpanel.net/models/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 U(){return Object.keys(D).every(a=>H(A(F(),a)))}const q=a=>new Promise((r,s)=>{const i=ne("sha256");ee(a).on("data",b=>i.update(b)).on("error",s).on("end",()=>r(i.digest("hex")))});async function $e({licenseAccepted:a=null,onProgress:r=()=>{},log:s=()=>{},fetchImpl:i=fetch}={}){if(U())return F();if(a!==fe){const x=new Error(`Indic-Transcribe is downloaded only after its licence (${M.name}) is accepted`);throw x.code="license_required",x}const b=F();Q(b,{recursive:!0});const d=Object.keys(D);for(const[x,g]of d.entries()){const y=A(b,g);if(H(y))continue;const h=await i(`${de}/${g}`);if(!h.ok||!h.body)throw new Error(`${g}: HTTP ${h.status}${h.status===404?" — not on dl.chatpanel.net yet":""}`);const f=Number(h.headers.get("content-length"))||0,v=`${y}.part`;if(await new Promise((m,o)=>{const u=V(v),n=h.body.getReader();let e=0;const c=()=>n.read().then(({done:t,value:p})=>{if(t){u.end(m);return}e+=p.length,f&&r({file:g,pct:Math.round((x+e/f)/d.length*100)}),u.write(Buffer.from(p)),c()},o);u.on("error",o),c()}),await q(v)!==D[g])throw Z(v,{force:!0}),new Error(`${g} does not match its pinned hash — not used`);te(v,y),s(`[indic] fetched ${g}`)}return b}const G=16e3,C=512,W=160,J=400,L=128,T=C/2+1,le=.97,be=2**-24,pe=1e-5,we=24,he=8,me=128,K=new Set,X=3;function ue(a,{fb:r,window:s}){const i=a.length,b=new Float32Array(i);b[0]=a[0]||0;for(let o=1;o<i;o++)b[o]=a[o]-le*a[o-1];const d=Math.floor(i/W)+1,x=C/2,g=o=>(o<0&&(o=-o),o>=i&&(o=2*(i-1)-o),b[Math.max(0,Math.min(i-1,o))]),y=(C-J)/2,h=new Float64Array(C),f=new Float64Array(C),v=new Float64Array(T),m=new Float32Array(L*d);for(let o=0;o<d;o++){const u=o*W-x;for(let n=0;n<C;n++){const e=n>=y&&n<y+J?s[n-y]:0;h[n]=e?g(u+n)*e:0,f[n]=0}se(h,f);for(let n=0;n<T;n++)v[n]=h[n]*h[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+=r[c+t]*v[t];m[n*d+o]=Math.log(e+be)}}for(let o=0;o<L;o++){const u=o*d;let n=0;for(let t=0;t<d;t++)n+=m[u+t];n/=d;let e=0;for(let t=0;t<d;t++)e+=(m[u+t]-n)**2;const c=Math.sqrt(e/Math.max(1,d-1))+pe;for(let t=0;t<d;t++)m[u+t]=(m[u+t]-n)/c}return{data:m,frames:d}}function ge(a){return String(a||"").replace(/\b[A-Z][A-Z']*(?:[\s,.!?;:-]+[A-Z][A-Z']*){2,}\b/g,r=>r.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])/,(r,s,i)=>/[A-Z]{3}/.test(a)?s+i.toUpperCase():r)}const _e=/\b(do|does|did|is|are|was|were|ca|could|would|should|wo|have|has|had|ai|must|need)n t\b/gi,ye=[[_e,(a,r)=>`${r}n't`],[/\b(can) t\b/gi,(a,r)=>`${r}'t`],[/\b(it|that|what|there|here|let|he|she|who|where|how|everyone|nobody) s\b/gi,(a,r)=>`${r}'s`],[/\b(I) (m)\b/g,()=>"I'm"],[/\b(I|you|we|they) (ll|ve|d)\b/gi,(a,r,s)=>`${r}'${s}`],[/\b(you|we|they) re\b/gi,(a,r)=>`${r}'re`]];function Ie(a){let r=String(a||"");for(const[s,i]of ye)r=r.replace(s,i);return r}function xe(a,r){return a.map(s=>r[s]??"").join("").replace(/▁/g," ").trim()}async function Fe({sessionOptions:a=null,log:r=()=>{}}={}){if(!ae())throw new Error("Indic-Transcribe needs the npm gateway (the standalone binary cannot run it)");if(!U())throw new Error("Indic-Transcribe is not downloaded");const s=F();for(const[e,c]of Object.entries(D))if(!K.has(e)){if(await q(A(s,e))!==c)throw Z(A(s,e),{force:!0}),new Error(`${e} changed on disk — removed`);K.add(e)}const i=await re(),b={executionProviders:ce(),graphOptimizationLevel:"all",logSeverityLevel:3,...a||{}},[d,x,g]=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))},h={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),m=i.Tensor;r("[indic] ready — Indic-Transcribe-core (int8, in-process, offline)");async function o(e,c,t){const p=await g.run({ids:new m("int64",BigInt64Array.from([BigInt(c)]),[1,1]),pos:new m("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 u(e){const{data:c,frames:t}=ue(e,h),p=(await d.run({features:new m("float32",c,[1,L,t])})).states,S=await x.run({states:p}),E=new m("float32",new Float32Array(0),[we,1,he,0,me]),l={k:E,v:E,ck:S.cross_k,cv:S.cross_v},_=f.prompt_te.slice();let $=null;for(let I=0;I<X;I++)$=await o(l,_[I],I);return{st:l,prompt:_,logits:$}}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<G/4)return{lang:null,confidence:0,scores:{}};const t=n((await u(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<G/4)return{text:"",lang:c,confidence:0};const{st:l,prompt:_,logits:$}=await u(e);let I=null,O=c,P=1;if(!O){const w=n($,t),k=Object.fromEntries(w);O=(E&&w.length?E(k):null)||w[0]?.[0]||p||"en",P=k[O]??0}const Y=f.lang_ids[O]??f.lang_ids.en;_[3]=_[4]=Y;for(let w=X;w<_.length;w++)I=await o(l,_[w],w);const R=[];for(let w=_.length;w<_.length+S;w++){let k=0,B=-1/0;for(let N=0;N<I.length;N++)I[N]>B&&(B=I[N],k=N);if(v.has(k))break;R.push(k),I=await o(l,k,w)}const j=ge(xe(R.filter(w=>!f.timestamp_ids.includes(w)),f.pieces));return{text:O==="en"?Ie(j):j,lang:O,confidence:P}},async dispose(){for(const e of[d,x,g])try{await e.release?.()}catch{}}}}export{D as INDIC_FILES,M as INDIC_LICENSE,fe as INDIC_LICENSE_ACCEPTANCE,Ne as INDIC_MODEL_ID,de as INDIC_SOURCE,G as SAMPLE_RATE,xe as decodeIds,$e as ensureIndicFiles,F as indicDir,U as indicOnDisk,Fe as loadRecognizer,ue as melFeatures,Ie as restoreApostrophes,ge as restoreCase};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as z,readFileSync as K,mkdirSync as W,createWriteStream as J,createReadStream as V,renameSync as X,rmSync as U}from"node:fs";import{createHash as Y}from"node:crypto";import{join as m}from"node:path";import{modelRoot as q}from"./ner-engine.js";import{getOrt as Q,ortProviders as ee,rawOrtAvailable as ne}from"./ort.js";import{makeWarmTimer as re}from"./warm-timer.js";const te="ai4bharat/indictrans2-indic-en-dist-200M";function B(){return m(q(),"ai4bharat","indictrans2-indic-en-int8")}const G=Object.freeze({as:"asm_Beng",bn:"ben_Beng",brx:"brx_Deva",doi:"doi_Deva",gu:"guj_Gujr",hi:"hin_Deva",kn:"kan_Knda",kok:"gom_Deva",ks:"kas_Deva",mai:"mai_Deva",ml:"mal_Mlym",mni:"mni_Beng",mr:"mar_Deva",ne:"npi_Deva",or:"ory_Orya",pa:"pan_Guru",sa:"san_Deva",sat:"sat_Olck",sd:"snd_Deva",ta:"tam_Taml",te:"tel_Telu",ur:"urd_Arab"}),L={Beng:2432,Deva:2304,Gujr:2688,Knda:3200,Mlym:3328,Orya:2816,Guru:2560,Taml:2944,Telu:3072};function oe(e){return!!G[String(e||"").toLowerCase()]}const ae=[[/\r/g,""],[/\(\s*/g,"("],[/\s*\)/g,")"],[/\s:\s?/g,":"],[/\s;\s?/g,";"],[/[`´‘‚’]/g,"'"],[/[„“”«»]/g,'"'],[/[–—]/g,"-"],[/\.\.\./g,"..."],[/ %/g,"%"],[/ [?!;]/g,e=>e.trim()]];function ce(e){for(const[r,n]of ae)e=e.replace(r,n);return e.replace(/[ ]{2,}/g," ").replace(/\) ([.!:?;,])/g,")$1").replace(/(\d) %/g,"$1%").replace(/"([,.]+)/g,'$1"').replace(/(\d) (\d)/g,"$1.$2").trim()}const se=[2534,2790,3302,2406,1632,44016,2918,2662,7248,1776,3174];function ie(e){return e.replace(/./gu,r=>{const n=r.codePointAt(0);for(const o of se)if(n>=o&&n<=o+9)return String(n-o);return r})}const le=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}/g,de=/\b(?<![\w/.])(?:(?:https?|ftp):\/\/)?(?:(?:[\w-]+\.)+(?!\.))(?:[\w/\-?#&=%.]+)+(?!\.\w+)\b/g,ue=/(~?\d+\.?\d*\s?%?\s?-?\s?~?\d+\.?\d*\s?%|~?\d+%|\d+[-/.,:']\d+[-/.,:'+]\d+(?:\.\d+)?|\d+[-/.:'+]\d+(?:\.\d+)?)/g,fe=/[A-Za-z0-9]*[#|@]\w+/g;function pe(e){const r=new Map;let n=1;for(const[o,a]of[[le,()=>!0],[de,t=>t.replace(/\./g,"").length>=4],[ue,t=>t.replace(/[ .:]/g,"").length>=4],[fe,()=>!0]])for(const t of new Set(e.match(o)||[])){if(!a(t))continue;const c=`<ID${n++}>`;r.set(c,t),e=e.split(t).join(c)}return{text:e,map:r}}function ge(e,r){if(e=e.replace(/[\uFEFF\uFFFE\u2060\u00AD]/g,"").replace(/[\u200B\u00A0]/g," ").replace(/[\u200C\u200D]/g,"").replace(/„|“|”/g,'"').replace(/–/g,"-").replace(/—/g," - ").replace(/[´‘‚’]/g,"'").replace(/''/g,'"').replace(/´´/g,'"').replace(/…/g,"..."),r==="Deva")e=e.replace(/\u0972/g,"ए").replace(/\u0929/g,"ऩ").replace(/\u0931/g,"ऱ").replace(/\u0934/g,"ऴ").replace(/[\u0958-\u095f]/g,n=>String.fromCharCode([2325,2326,2327,2332,2337,2338,2347,2351][n.charCodeAt(0)-2392])+"़").replace(/\|/g,"।").replace(/([\u0900-\u097f]):/g,"$1ः");else if(L[r]){const n=L[r];e=e.replace(new RegExp(String.fromCharCode(n+100),"g"),"।").replace(new RegExp(String.fromCharCode(n+101),"g"),"॥"),r==="Telu"&&(e=e.replace(/\u0c46\u0c56/g,"ై"))}return e}const me="!\"#$%&'()*+,\\-./:;<=>?@[\\\\\\]^_`{|}~\\u0964\\u0965\\uAAF1\\uAAF0\\uABEB\\uABEC\\uABED\\uABEE\\uABEF\\u1C7E\\u1C7F",be=new RegExp(`([${me}])`,"g");function we(e){let r=e.replace(/\t/g," ").replace(be," $1 ").replace(/[ ]+/g," ").replace(/^ +| +$/g,"");return r=r.replace(/([0-9]+ [,.:/] )+[0-9]+/g,n=>n.replace(/ /g,"")),r.split(" ")}function xe(e,r){const n=L[r];if(!n||n===2304)return e;let o="";for(const a of e){const t=a.codePointAt(0)-n;o+=t>=0&&t<=111&&a!=="।"&&a!=="॥"?String.fromCodePoint(2304+t):a}return o}function he(e,r){const n=G[r];if(!n)throw new Error(`IndicTrans2 has no ${r}`);const o=n.split("_")[1];let a=ie(ce(String(e||"")));const t=pe(a);a=t.text;const c=!["Arab","Aran","Olck","Mtei","Latn"].includes(o);let s=we(ge(a.trim(),o)).join(" ");return c&&(s=xe(s,o).replace(/ ् /g,"्")),{text:`${n} eng_Latn ${s.trim()}`,map:t.map}}function _e(e,r){const n=String(e).normalize("NFKC").replace(/\s+/g," ").trim();if(!n)return[];const o=[];for(const a of n.split(" ")){let t=Array.from(`▁${a}`);for(;;){let c=-1,s=-1/0;for(let i=0;i+1<t.length;i++){const u=r.scores.get(t[i]+t[i+1]);u!==void 0&&u>s&&(s=u,c=i)}if(c<0)break;t=[...t.slice(0,c),t[c]+t[c+1],...t.slice(c+2)]}o.push(...t)}return o}function ve(e,r=new Map){let n=e.join("").replace(/▁/g," ").trim();return n=n.replace(/[<[]\s*id\s*(\d+)\s*[>\]]/gi,(o,a)=>r.get(`<ID${a}>`)??o),n=n.replace(/\s+([.,!?;:%)\]}])/g,"$1").replace(/([([{])\s+/g,"$1").replace(/\s+'(s|re|ve|ll|d|m|t)\b/g,"'$1").replace(/\s+n't\b/g,"n't").replace(/\s{2,}/g," ").trim(),n=n.replace(/\bi\b/g,"I").replace(/\bi'(m|ll|ve|d)\b/g,(o,a)=>`I'${a}`),n.charAt(0).toUpperCase()+n.slice(1)}const ye="https://dl.chatpanel.net/models/ChatPanel/indictrans2-indic-en-int8/resolve/main",P=Object.freeze({"encoder.onnx":"b08c9150c013ebdc39fc91eb374e4b5acbbea609b7b86065d917be237fab7259","encoder.onnx.data":"523545913dfd3a76e8ca58d0b7d4fd74353a571e6e2525cf10d73006ed02b526","cross_kv.onnx":"eb10975a209e5cb0abb01e0e272e236ae2455973e7702e82c0f9aa7193ee9db8","cross_kv.onnx.data":"dc560bf3c174c203df69d3d2bc323ba16e0d1901bfc49db853406f6fa5b8c918","decoder.onnx":"b848027adbd61f3d06dc3019d96f509ef19608d701cb32874b004ad7055927bd","decoder.onnx.data":"f64be74f42e7d2bc642881430df7d9fe28d9f7b3ccec46ad36e9d1a791a6747c","src.json":"02b0f3fbd801826e3ff7967695aec4cd6a01b771b516c0050aaab0fe89e2908c","tgt.json":"77470ef2ec82d3302f6d6ca30b4c5cd4cbba74f539ac85abe358fe6d83aea1c6",LICENSE:"383258420065a19d9fef0daf00d10792d3f8a5ccf783d94a91f5d6755386615b"}),R=Object.keys(P);function M(){return R.every(e=>z(m(B(),e)))}const H=e=>new Promise((r,n)=>{const o=Y("sha256");V(e).on("data",a=>o.update(a)).on("error",n).on("end",()=>r(o.digest("hex")))});async function Ae({log:e=()=>{},onProgress:r=()=>{},fetchImpl:n=fetch}={}){if(M())return;const o=B();W(o,{recursive:!0});for(const[a,t]of R.entries()){const c=m(o,t);if(z(c))continue;const s=await n(`${ye}/${t}`);if(!s.ok||!s.body)throw new Error(`${t}: HTTP ${s.status}${s.status===404?" — not on dl.chatpanel.net yet":""}`);const i=`${c}.part`;await new Promise((p,w)=>{const l=J(i),x=s.body.getReader(),h=()=>x.read().then(({done:D,value:E})=>{if(D){l.end(p);return}l.write(Buffer.from(E)),h()},w);l.on("error",w),h()});const u=P[t];if(u&&await H(i)!==u)throw U(i,{force:!0}),new Error(`${t} does not match its pinned hash — not used`);X(i,c),r({file:t,pct:Math.round((a+1)/R.length*100)}),e(`[indictrans] fetched ${t}`)}}let d="off",y=null,b=null,_=null,f=null,C=0,A=0,F=Promise.resolve(),I=null;const Ie=18,Se=8,ke=64,De=200;function Fe(){return d}function S(){return d==="ready"&&(!!_||!!I)}function Ne(){return{configured:d!=="off",ok:S(),state:d,model:te,error:y,onDisk:M()}}function k(){return C>0||A>0||d==="loading"||d==="downloading"}function je(){A++,f?.disarm()}function ze(){A=Math.max(0,A-1),!k()&&S()&&f?.arm()}async function Ee(){if(k())return!1;f?.disarm();const e=_;if(_=null,b=null,d="off",e)for(const r of[e.encoder,e.crossKv,e.decoder])try{await r.release?.()}catch{}return!0}async function $e({allowDownload:e=!0,log:r=()=>{},sessionOptions:n=null,fetchImpl:o}={}){if(!ne())return d="error",y="IndicTrans2 needs the npm gateway",!1;try{if(!M()){if(!e)throw new Error("model not on disk and downloads disabled");d="downloading",r("[indictrans] downloading IndicTrans2 indic→en (one-time, ~250 MB, from dl.chatpanel.net)…"),await Ae({log:r,fetchImpl:o})}d="loading";const a=B();for(const[l,x]of Object.entries(P))if(await H(m(a,l))!==x)throw U(m(a,l),{force:!0}),new Error(`${l} changed on disk — removed`);const t=await Q(),c={executionProviders:ee(),graphOptimizationLevel:"all",logSeverityLevel:3,...n||{}},[s,i,u]=await Promise.all(["encoder","cross_kv","decoder"].map(l=>t.InferenceSession.create(m(a,`${l}.onnx`),c))),p=JSON.parse(K(m(a,"src.json"),"utf8")),w=JSON.parse(K(m(a,"tgt.json"),"utf8"));return _={ort:t,encoder:s,crossKv:i,decoder:u,src:{scores:new Map(p.pieces.filter(l=>!l[2]).map(l=>[l[0],l[1]])),vocab:p.vocab,unk:p.unk,eos:p.eos},tgt:w},d="ready",y=null,r("[indictrans] ready — IndicTrans2 indic→en (int8, in-process, offline)"),!0}catch(a){return d="error",y=a.message,r(`[indictrans] unavailable (${a.message}) — Indian-language lines stay as spoken`),!1}}function Ke(e={}){if(b&&d!=="error")return b;d="loading";const r=typeof e.onLog=="function"?e.onLog:()=>{};return f=re({warmMs:e.warmMs,busy:k,log:r,unload:()=>Ee()}),b=$e({allowDownload:e.allowDownload!==!1,log:r,sessionOptions:e.sessionOptions||null,fetchImpl:e.fetchImpl}).then(n=>(n&&!k()&&f?.arm(),n)),b}function Ue(){return b?b.then(()=>S(),()=>!1):Promise.resolve(S())}function Ce(e,r){const[n,o,a]=[e.slice(0,e.indexOf(" ")),e.split(" ")[1],e.split(" ").slice(2).join(" ")];return[n,o,..._e(a,r)].map(c=>r.vocab[c]??r.unk).concat([r.eos])}async function Oe(e,r){const{ort:n,encoder:o,crossKv:a,decoder:t,src:c,tgt:s}=_,i=n.Tensor,{text:u,map:p}=he(e,r),w=Ce(u,c).slice(0,256),l=(await o.run({ids:new i("int64",BigInt64Array.from(w.map(BigInt)),[1,w.length])})).states,x=await a.run({states:l});let h=new i("float32",new Float32Array(0),[Ie,1,Se,0,ke]),D=h;const E=[];let N=s.start;for(let g=0;g<De;g++){const O=await t.run({ids:new i("int64",BigInt64Array.from([BigInt(N)]),[1,1]),pos:new i("int64",BigInt64Array.from([BigInt(g)]),[1]),self_k:h,self_v:D,cross_k:x.cross_k,cross_v:x.cross_v});h=O.new_self_k,D=O.new_self_v;const T=O.logits.data;let $=0,j=-1/0;for(let v=0;v<T.length;v++)T[v]>j&&(j=T[v],$=v);if($===s.eos)break;E.push($),N=$}const Z=E.map(g=>s.vocab[g]??"").filter(g=>!/^<.*>$/.test(g)||/^<ID\d+>$/.test(g));return ve(Z,p)}function Ge(e,r){const n=String(e||"").trim();if(!n||!oe(r)||!S())return Promise.resolve(null);C++,f?.disarm();const o=F.then(async()=>{try{return I?await I(n,r):await Oe(n,String(r).toLowerCase())||null}catch{return null}});return F=o.catch(()=>null),o.finally(()=>{C--,k()||f?.arm()})}function He(){f?.disarm(),f=null,d="off",y=null,b=null,_=null,I=null,A=0,C=0,F=Promise.resolve()}function Ze(e){I=e||null,d=e?"ready":"off"}export{G as FLORES,P as INDICTRANS_FILES,te as INDICTRANS_MODEL_ID,ye as INDICTRANS_SOURCE,He as _reset,Ze as _setForTest,_e as bpePieces,Ne as health,B as indictransDir,oe as indictransLanguage,M as indictransOnDisk,Ke as init,S as isReady,ve as postprocess,he as preprocess,Ue as ready,ze as release,je as retain,Ce as sourceIds,Fe as state,Ge as translate,Ee as unload};
|
package/src/parakeet-engine.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{join as
|
|
2
|
-
`)){if(!s)continue;const
|
|
1
|
+
import{join as i}from"node:path";import{existsSync as $,mkdirSync as tt,readFileSync as et,createWriteStream as nt,renameSync as ot,statSync as C}from"node:fs";import{Readable as rt}from"node:stream";import{modelRoot as st}from"./ner-engine.js";import{getOrt as at,ortProviders as ct}from"./ort.js";const it=new Set(["nemo-conformer-tdt","nemo-conformer-rnnt","parakeet_tdt","parakeet-tdt","parakeet_rnnt"]);function _t(t){return it.has(String(t||"").trim())}const D="int8";function Y(t){return t==="fp32"?"fp32":D}function V(t){const e=Y(t)==="fp32"?"":".int8",n=["config.json","vocab.txt","nemo128.onnx",`encoder-model${e}.onnx`,`decoder_joint-model${e}.onnx`];return e||n.push("encoder-model.onnx.data"),n}function E(t){return i(st(),...String(t).split("/"))}function lt(t,e=D){const n=E(t);if(!$(n))return!1;try{return V(e).every(s=>{const o=i(n,s);return $(o)&&C(o).size>0})}catch{return!1}}async function ft(t,e,n,{onProgress:s,log:o}={}){const r=`https://huggingface.co/${t}/resolve/main/${encodeURIComponent(e).replace(/%2F/g,"/")}`,a=await fetch(r,{redirect:"follow"});if(!a.ok||!a.body)throw new Error(`fetch ${e} → HTTP ${a.status}`);const w=Number(a.headers.get("content-length"))||0,l=i(n,`${e}.part`),f=nt(l);let h=0,d=-1;const p=rt.fromWeb(a.body);p.on("data",m=>{if(h+=m.length,w){const c=Math.round(h/w*100);c!==d&&(d=c,s?.({file:e,pct:c}))}}),await new Promise((m,c)=>{p.pipe(f),f.on("finish",m),f.on("error",c),p.on("error",c)}),ot(l,i(n,e)),o?.(`[parakeet] fetched ${e}`)}async function ut(t,e,{onProgress:n,log:s}={}){const o=E(t);tt(o,{recursive:!0});for(const r of V(e)){const a=i(o,r);$(a)&&C(a).size>0||(s?.(`[parakeet] downloading ${r}…`),await ft(t,r,o,{onProgress:n,log:s}))}return o}function dt(t){const e=[];let n=-1;for(const s of et(i(t,"vocab.txt"),"utf8").split(`
|
|
2
|
+
`)){if(!s)continue;const o=s.lastIndexOf(" ");if(o<0)continue;const r=parseInt(s.slice(o+1),10),a=s.slice(0,o);Number.isFinite(r)&&(e[r]=a.replace(/▁/g," "),a==="<blk>"&&(n=r))}return n<0&&(n=e.length-1),{vocab:e,blank:n}}function W(t,e,n){let s=e,o=t[e];for(let r=e+1;r<n;r++)t[r]>o&&(o=t[r],s=r);return s}const pt=5,H=10;async function xt({modelId:t,dtype:e=D,allowDownload:n=!0,onProgress:s,log:o=()=>{},sessionOptions:r=null}){const a=Y(e),w=lt(t,a);if(!w&&!n)throw new Error("model not on disk and downloads disabled");const l=w?E(t):await ut(t,a,{onProgress:s,log:o}),f=await at(),h=a==="fp32"?"":".int8",d={executionProviders:ct(),graphOptimizationLevel:"all",logSeverityLevel:3,...r||{}},[p,m,c]=await Promise.all([f.InferenceSession.create(i(l,"nemo128.onnx"),d),f.InferenceSession.create(i(l,`encoder-model${h}.onnx`),d),f.InferenceSession.create(i(l,`decoder_joint-model${h}.onnx`),d)]),{vocab:K,blank:_}=dt(l),x=_+1,u=f.Tensor;async function X(g){if(!(g instanceof Float32Array)||g.length<400)return"";const I=g.length,P=await p.run({waveforms:new u("float32",g,[1,I]),waveforms_lens:new u("int64",BigInt64Array.from([BigInt(I)]),[1])}),O=await m.run({audio_signal:P.features,length:P.features_lens}),R=O.outputs,[,A,G]=R.dims,L=Number(O.encoded_lengths.data[0]),J=R.data;let M=new Float32Array(2*640),N=new Float32Array(2*640);const y=[],z=new Float32Array(A);let b=0,k=0;const Q=L*(H+1)+8;for(let S=0;b<L&&S<Q;S++){for(let v=0;v<A;v++)z[v]=J[v*G+b];const Z=y.length?y[y.length-1]:_,T=await c.run({encoder_outputs:new u("float32",z,[1,A,1]),targets:new u("int32",Int32Array.from([Z]),[1,1]),target_length:new u("int32",Int32Array.from([1]),[1]),input_states_1:new u("float32",M,[2,1,640]),input_states_2:new u("float32",N,[2,1,640])}),U=T.outputs.data,F=W(U,0,x),j=W(U,x,x+pt)-x;F!==_&&(M=T.output_states_1.data,N=T.output_states_2.data,y.push(F),k++),j>0?(b+=j,k=0):(F===_||k>=H)&&(b+=1,k=0)}let B="";for(const S of y)B+=K[S]??"";return B.replace(/^\s+/,"").replace(/\s+/g," ").trimEnd()}function q(){for(const g of[p,m,c])try{g.release?.()}catch{}}return{transcribe:X,dispose:q,dtype:a,dir:l}}export{D as PARAKEET_DEFAULT_DTYPE,_t as isTransducerModelType,xt as loadRecognizer,E as parakeetDir,Y as parakeetDtype,lt as parakeetOnDisk};
|