@chatpanel/gateway 0.116.0 → 0.117.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 +1 -1
- package/src/aec-engine.js +1 -1
- package/src/egress.js +2 -2
- package/src/indic-engine.js +1 -1
- package/src/indictrans-engine.js +1 -1
- package/src/model-copies.js +1 -0
- package/src/model-sources.js +1 -0
- package/src/ner-engine.js +1 -1
- package/src/parakeet-engine.js +2 -2
- package/src/stt-engine.js +1 -1
- package/src/tts-engine.js +1 -1
- 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.117.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": {
|
package/src/aec-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as R,mkdirSync as
|
|
1
|
+
import{modelCopy as X,HF_HOST as G}from"./model-sources.js";import{existsSync as R,mkdirSync as J,createWriteStream as Q,renameSync as V,rmSync as H,readFileSync as Y}from"node:fs";import{createHash as Z}from"node:crypto";import{join as M}from"node:path";import{modelRoot as tt}from"./ner-engine.js";import{getOrt as et,ortProviders as ot,rawOrtAvailable as W}from"./ort.js";const rt=16e3,p=512,m=128,k=p/2+1,nt="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 M(tt(),"fastrepl","dtln-aec-128")}const B=new Map;function at(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 C(t,r,y=!1){const n=t.length;for(let o=1,a=0;o<n;o++){let l=n>>1;for(;a&l;l>>=1)a^=l;a^=l,o<a&&([t[o],t[a]]=[t[a],t[o]],[r[o],r[a]]=[r[a],r[o]])}const{c:i,s:f}=at(n);for(let o=2;o<=n;o<<=1){const a=n/o;for(let l=0;l<n;l+=o)for(let s=0;s<o/2;s++){const w=i[s*a],c=y?-f[s*a]:f[s*a],h=l+s,u=h+o/2,b=t[u]*w-r[u]*c,d=t[u]*c+r[u]*w;t[u]=t[h]-b,r[u]=r[h]-d,t[h]+=b,r[h]+=d}}if(y)for(let o=0;o<n;o++)t[o]/=n,r[o]/=n}function pt(t,r,{maxMs:y=1e3,minCorr:n=.3}={}){const i=rt/100,f=Math.floor(Math.min(t.length,r.length)/i);if(f<200)return{delay:0,corr:0};const o=c=>{const h=new Float64Array(f);for(let d=0;d<f;d++){let x=0;for(let g=0;g<i;g++)x+=c[d*i+g]**2;h[d]=Math.log10(x/i+1e-9)}let u=0;for(const d of h)u+=d;u/=f;let b=0;for(const d of h)b+=(d-u)**2;b=Math.sqrt(b/f)+1e-9;for(let d=0;d<f;d++)h[d]=(h[d]-u)/b;return h},a=o(t),l=o(r);let s=0,w=-1;for(let c=0;c<=Math.min(y/10,f-100);c++){let h=0;for(let u=c;u<f;u++)h+=a[u]*l[u-c];h/=f-c,h>w&&(w=h,s=c)}return w>n?{delay:s*i,corr:w}:{delay:0,corr:w}}function wt(t,r,y,{frame:n=1600,speakersOn:i=1e-5}={}){let f=0,o=0,a=0,l=0;for(let s=0;s+n<=t.length;s+=n){l++;let w=0;for(let c=s;c<s+n;c++)w+=y[c]*y[c];if(!(w/n<=i)){a++;for(let c=s;c<s+n;c++)f+=t[c]*t[c],o+=r[c]*r[c]}}return{share:l?a/l:0,db:a?10*Math.log10((f+1e-12)/(o+1e-12)):0}}function mt({share:t,db:r}){return t>.5&&r>10}let A="off",$=null,S=null,O=null,D=null,P=null;function bt(){return A}function z(){return A==="ready"&&(!!O||!!P)}function gt(){return{configured:A!=="off",ok:z(),state:A,error:$,available:W(),approxMB:q}}function st(){return Object.keys(E).every(t=>R(M(v(),t)))}const K=t=>Z("sha256").update(Y(t)).digest("hex");async function lt(t,{fetchImpl:r=fetch,log:y}){const n=v();J(n,{recursive:!0});const i=M(n,t),f=`${i}.part`,o=X("fastrepl/dtln-aec-128");let a=null;for(const l of[...o?[`${G}${o.repo}/resolve/${o.revision}/${t}`]:[],`${nt}/${t}`])try{if(a=await r(l),a.ok&&a.body)break}catch(s){a={ok:!1,status:s.message}}if(!a?.ok||!a.body)throw new Error(`HTTP ${a?.status} for ${t}`);if(await new Promise((l,s)=>{const w=Q(f),c=a.body.getReader(),h=()=>c.read().then(({done:u,value:b})=>{if(u){w.end(l);return}w.write(Buffer.from(b)),h()},s);w.on("error",s),h()}),K(f)!==E[t])throw H(f,{force:!0}),new Error(`${t} does not match its pinned hash — not used`);V(f,i),y(`[aec] fetched ${t}`)}async function ct({allowDownload:t=!0,log:r=()=>{},fetchImpl:y}={}){if(!W())return A="error",$="echo cancellation needs the npm gateway (the standalone binary cannot run it)",!1;try{if(!st()){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(M(v(),o))||await lt(o,{fetchImpl:y,log:r})}for(const[o,a]of Object.entries(E))if(K(M(v(),o))!==a)throw H(M(v(),o),{force:!0}),new Error(`${o} changed on disk — removed`);A="loading",D=await et();const n={executionProviders:ot(),intraOpNumThreads:1,interOpNumThreads:1},[i,f]=await Promise.all(Object.keys(E).map(o=>D.InferenceSession.create(M(v(),o),n)));return O={s1:i,s2:f},A="ready",$=null,r("[aec] ready — the microphone is cleaned against what the speakers play (DTLN-aec)"),!0}catch(n){return A="error",$=n.message,r(`[aec] unavailable (${n.message}) — the text-level echo guard alone`),!1}}function At(t={}){return S&&A!=="error"||(A="loading",S=ct({allowDownload:t.allowDownload!==!1,log:typeof t.onLog=="function"?t.onLog:()=>{},fetchImpl:t.fetchImpl})),S}function j(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 xt(){const t=[1,2,128,2];let r=null,y=null;const n=new Float32Array(p),i=new Float32Array(p),f=new Float32Array(p);let o=new Float32Array(0),a=new Float32Array(0);const l=new Float64Array(p),s=new Float64Array(p),w=new Float32Array(k),c=new Float32Array(k);async function h(u,b){n.copyWithin(0,m),n.set(u,p-m),i.copyWithin(0,m),i.set(b,p-m);for(let e=0;e<p;e++)l[e]=n[e],s[e]=0;C(l,s);const d=Float64Array.from(l.subarray(0,k)),x=Float64Array.from(s.subarray(0,k));for(let e=0;e<k;e++)w[e]=Math.hypot(d[e],x[e]);for(let e=0;e<p;e++)l[e]=i[e],s[e]=0;C(l,s);for(let e=0;e<k;e++)c[e]=Math.hypot(l[e],s[e]);const g=D.Tensor;r||=new g("float32",new Float32Array(256*2),t),y||=new g("float32",new Float32Array(256*2),t);const _=O.s1.inputNames,F=await O.s1.run({[_[0]]:new g("float32",Float32Array.from(w),[1,1,k]),[_[1]]:r,[_[2]]:new g("float32",Float32Array.from(c),[1,1,k])}),I=j(F,"main").data;r=j(F,"state");for(let e=0;e<k;e++)l[e]=d[e]*I[e],s[e]=x[e]*I[e];for(let e=1;e<p/2;e++)l[p-e]=l[e],s[p-e]=-s[e];C(l,s,!0);const L=new Float32Array(p);for(let e=0;e<p;e++)L[e]=l[e];const T=O.s2.inputNames,N=await O.s2.run({[T[0]]:new g("float32",L,[1,1,p]),[T[1]]:y,[T[2]]:new g("float32",Float32Array.from(i),[1,1,p])}),U=j(N,"main").data;y=j(N,"state"),f.copyWithin(0,m),f.fill(0,p-m);for(let e=0;e<p;e++)f[e]+=U[e];return f.slice(0,m)}return{async process(u,b){if(P)return P(u,b);if(!z())return u;const d=new Float32Array(o.length+u.length);d.set(o),d.set(u,o.length);const x=new Float32Array(a.length+b.length);x.set(a),x.set(b.subarray(0,u.length),a.length);const g=Math.floor(d.length/m),_=new Float32Array(g*m);for(let F=0;F<g;F++)_.set(await h(d.subarray(F*m,(F+1)*m),x.subarray(F*m,(F+1)*m)),F*m);return o=d.slice(g*m),a=x.slice(g*m),_}}}function Ft(){A="off",$=null,S=null,O=null,P=null}function kt(t){P=t||null,A=t?"ready":"off"}export{q as AEC_APPROX_MB,E as AEC_FILES,nt as AEC_SOURCE,p as BLOCK,m as HOP,rt as SAMPLE_RATE,Ft as _reset,kt as _setForTest,v as aecDir,xt as createCanceller,wt as echoDrop,pt as estimateDelay,C as fft,gt as health,At as init,z as isReady,st as modelOnDisk,mt as mostlyEcho,bt as state};
|
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"}),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
|
-
`)}export{
|
|
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 m}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 g=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:m(t,{allowLoopback:!1,allowPrivate:!1})&&!m(t,{allowLoopback:!0,allowPrivate:!0})};function P({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:g(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=P();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:g(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 A(){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("huggingface.co","model weights (NER, dictation, read-aloud, translation, meetings) — ChatPanel’s pinned copies in huggingface.co/ChatPanel, or the upstream repo",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id and file being downloaded"}),s("dl.chatpanel.net","model weights only when Hugging Face is failing (an outage or a network that blocks it), and the installer",{when:"a model download Hugging Face could not serve",off:"the same switches as huggingface.co",data:"the model id being downloaded"}),s("raw.githubusercontent.com","the meeting echo canceller's weights (DTLN-aec, ~7 MB, pinned commit and hashes) — only when ChatPanel’s copy on Hugging Face cannot be reached",{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:g(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:g(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:g(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=A(),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
|
+
`)}export{P as createEgressLedger,x as declaredEgress,O as egressAudit,A as egressLedger,_ as formatAudit,N as installEgressLedger};
|
package/src/indic-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as H,readFileSync as z,mkdirSync as
|
|
1
|
+
import{modelFetch as Q}from"./model-sources.js";import{existsSync as H,readFileSync as z,mkdirSync as V,createWriteStream as ee,createReadStream as te,renameSync as ne,rmSync as Z}from"node:fs";import{createHash as oe}from"node:crypto";import{join as A}from"node:path";import{modelRoot as re}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(re(),"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 U(){return Object.keys(D).every(a=>H(A($(),a)))}const q=a=>new Promise((r,s)=>{const i=oe("sha256");te(a).on("data",b=>i.update(b)).on("error",s).on("end",()=>r(i.digest("hex")))});async function De({licenseAccepted:a=null,onProgress:r=()=>{},log:s=()=>{},fetchImpl:i=Q()}={}){if(U())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,h]of d.entries()){const y=A(b,h);if(H(y))continue;const g=await i(`${le}/${h}`);if(!g.ok||!g.body)throw new Error(`${h}: HTTP ${g.status}`);const f=Number(g.headers.get("content-length"))||0,v=`${y}.part`;if(await new Promise((w,o)=>{const u=ee(v),n=g.body.getReader();let e=0;const c=()=>n.read().then(({done:t,value:p})=>{if(t){u.end(w);return}e+=p.length,f&&r({file:h,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[h])throw Z(v,{force:!0}),new Error(`${h} does not match its pinned hash — not used`);ne(v,y),s(`[indic] fetched ${h}`)}return b}const G=16e3,C=512,W=160,J=400,L=128,T=C/2+1,be=.97,pe=2**-24,me=1e-5,we=24,ue=8,he=128,K=new Set,X=3;function ge(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]-be*a[o-1];const d=Math.floor(i/W)+1,x=C/2,h=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,g=new Float64Array(C),f=new Float64Array(C),v=new Float64Array(T),w=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;g[n]=e?h(u+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+=r[c+t]*v[t];w[n*d+o]=Math.log(e+pe)}}for(let o=0;o<L;o++){const u=o*d;let n=0;for(let t=0;t<d;t++)n+=w[u+t];n/=d;let e=0;for(let t=0;t<d;t++)e+=(w[u+t]-n)**2;const c=Math.sqrt(e/Math.max(1,d-1))+me;for(let t=0;t<d;t++)w[u+t]=(w[u+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,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 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,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 xe(a){let r=String(a||"");for(const[s,i]of Ie)r=r.replace(s,i);return r}function ve(a,r){return a.map(s=>r[s]??"").join("").replace(/▁/g," ").trim()}async function Le({sessionOptions:a=null,log:r=()=>{}}={}){if(!se())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=$();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 ce(),b={executionProviders:ae(),graphOptimizationLevel:"all",logSeverityLevel:3,...a||{}},[d,x,h]=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;r("[indic] ready — Indic-Transcribe-core (int8, in-process, offline)");async function o(e,c,t){const p=await h.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 u(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,ue,0,he]),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 o(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<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:F}=await u(e);let I=null,O=c,P=1;if(!O){const m=n(F,t),k=Object.fromEntries(m);O=(E&&m.length?E(k):null)||m[0]?.[0]||p||"en",P=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 o(l,_[m],m);const R=[];for(let m=_.length;m<_.length+S;m++){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,m)}const j=_e(ve(R.filter(m=>!f.timestamp_ids.includes(m)),f.pieces));return{text:O==="en"?xe(j):j,lang:O,confidence:P}},async dispose(){for(const e of[d,x,h])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,G as SAMPLE_RATE,ve as decodeIds,De as ensureIndicFiles,$ as indicDir,U as indicOnDisk,Le as loadRecognizer,ge as melFeatures,xe as restoreApostrophes,_e as restoreCase};
|
package/src/indictrans-engine.js
CHANGED
|
@@ -1 +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};
|
|
1
|
+
import{modelFetch as W}from"./model-sources.js";import{existsSync as z,readFileSync as K,mkdirSync as J,createWriteStream as V,createReadStream as X,renameSync as Y,rmSync as H}from"node:fs";import{createHash as q}from"node:crypto";import{join as m}from"node:path";import{modelRoot as Q}from"./ner-engine.js";import{getOrt as ee,ortProviders as ne,rawOrtAvailable as re}from"./ort.js";import{makeWarmTimer as te}from"./warm-timer.js";const oe="ai4bharat/indictrans2-indic-en-dist-200M";function B(){return m(Q(),"ai4bharat","indictrans2-indic-en-int8")}const U=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 ae(e){return!!U[String(e||"").toLowerCase()]}const ce=[[/\r/g,""],[/\(\s*/g,"("],[/\s*\)/g,")"],[/\s:\s?/g,":"],[/\s;\s?/g,";"],[/[`´‘‚’]/g,"'"],[/[„“”«»]/g,'"'],[/[–—]/g,"-"],[/\.\.\./g,"..."],[/ %/g,"%"],[/ [?!;]/g,e=>e.trim()]];function se(e){for(const[r,n]of ce)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 ie=[2534,2790,3302,2406,1632,44016,2918,2662,7248,1776,3174];function le(e){return e.replace(/./gu,r=>{const n=r.codePointAt(0);for(const o of ie)if(n>=o&&n<=o+9)return String(n-o);return r})}const de=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}/g,ue=/\b(?<![\w/.])(?:(?:https?|ftp):\/\/)?(?:(?:[\w-]+\.)+(?!\.))(?:[\w/\-?#&=%.]+)+(?!\.\w+)\b/g,fe=/(~?\d+\.?\d*\s?%?\s?-?\s?~?\d+\.?\d*\s?%|~?\d+%|\d+[-/.,:']\d+[-/.,:'+]\d+(?:\.\d+)?|\d+[-/.:'+]\d+(?:\.\d+)?)/g,pe=/[A-Za-z0-9]*[#|@]\w+/g;function ge(e){const r=new Map;let n=1;for(const[o,a]of[[de,()=>!0],[ue,t=>t.replace(/\./g,"").length>=4],[fe,t=>t.replace(/[ .:]/g,"").length>=4],[pe,()=>!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 me(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 be="!\"#$%&'()*+,\\-./:;<=>?@[\\\\\\]^_`{|}~\\u0964\\u0965\\uAAF1\\uAAF0\\uABEB\\uABEC\\uABED\\uABEE\\uABEF\\u1C7E\\u1C7F",we=new RegExp(`([${be}])`,"g");function xe(e){let r=e.replace(/\t/g," ").replace(we," $1 ").replace(/[ ]+/g," ").replace(/^ +| +$/g,"");return r=r.replace(/([0-9]+ [,.:/] )+[0-9]+/g,n=>n.replace(/ /g,"")),r.split(" ")}function _e(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=U[r];if(!n)throw new Error(`IndicTrans2 has no ${r}`);const o=n.split("_")[1];let a=le(se(String(e||"")));const t=ge(a);a=t.text;const c=!["Arab","Aran","Olck","Mtei","Latn"].includes(o);let s=xe(me(a.trim(),o)).join(" ");return c&&(s=_e(s,o).replace(/ ् /g,"्")),{text:`${n} eng_Latn ${s.trim()}`,map:t.map}}function ve(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 ye(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 Ae="https://huggingface.co/ChatPanel/indictrans2-indic-en-int8/resolve/main",F=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"}),P=Object.keys(F);function R(){return P.every(e=>z(m(B(),e)))}const G=e=>new Promise((r,n)=>{const o=q("sha256");X(e).on("data",a=>o.update(a)).on("error",n).on("end",()=>r(o.digest("hex")))});async function Ie({log:e=()=>{},onProgress:r=()=>{},fetchImpl:n=W()}={}){if(R())return;const o=B();J(o,{recursive:!0});for(const[a,t]of P.entries()){const c=m(o,t);if(z(c))continue;const s=await n(`${Ae}/${t}`);if(!s.ok||!s.body)throw new Error(`${t}: HTTP ${s.status}${s.status===404,""}`);const i=`${c}.part`;await new Promise((p,w)=>{const l=V(i),x=s.body.getReader(),_=()=>x.read().then(({done:D,value:E})=>{if(D){l.end(p);return}l.write(Buffer.from(E)),_()},w);l.on("error",w),_()});const u=F[t];if(u&&await G(i)!==u)throw H(i,{force:!0}),new Error(`${t} does not match its pinned hash — not used`);Y(i,c),r({file:t,pct:Math.round((a+1)/P.length*100)}),e(`[indictrans] fetched ${t}`)}}let d="off",y=null,b=null,h=null,f=null,C=0,A=0,M=Promise.resolve(),I=null;const Se=18,ke=8,De=64,Ee=200;function je(){return d}function S(){return d==="ready"&&(!!h||!!I)}function ze(){return{configured:d!=="off",ok:S(),state:d,model:oe,error:y,onDisk:R()}}function k(){return C>0||A>0||d==="loading"||d==="downloading"}function Ke(){A++,f?.disarm()}function He(){A=Math.max(0,A-1),!k()&&S()&&f?.arm()}async function $e(){if(k())return!1;f?.disarm();const e=h;if(h=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 Ce({allowDownload:e=!0,log:r=()=>{},sessionOptions:n=null,fetchImpl:o}={}){if(!re())return d="error",y="IndicTrans2 needs the npm gateway",!1;try{if(!R()){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 Hugging Face)…"),await Ie({log:r,fetchImpl:o})}d="loading";const a=B();for(const[l,x]of Object.entries(F))if(await G(m(a,l))!==x)throw H(m(a,l),{force:!0}),new Error(`${l} changed on disk — removed`);const t=await ee(),c={executionProviders:ne(),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 h={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 Ue(e={}){if(b&&d!=="error")return b;d="loading";const r=typeof e.onLog=="function"?e.onLog:()=>{};return f=te({warmMs:e.warmMs,busy:k,log:r,unload:()=>$e()}),b=Ce({allowDownload:e.allowDownload!==!1,log:r,sessionOptions:e.sessionOptions||null,fetchImpl:e.fetchImpl}).then(n=>(n&&!k()&&f?.arm(),n)),b}function Ge(){return b?b.then(()=>S(),()=>!1):Promise.resolve(S())}function Oe(e,r){const[n,o,a]=[e.slice(0,e.indexOf(" ")),e.split(" ")[1],e.split(" ").slice(2).join(" ")];return[n,o,...ve(a,r)].map(c=>r.vocab[c]??r.unk).concat([r.eos])}async function Te(e,r){const{ort:n,encoder:o,crossKv:a,decoder:t,src:c,tgt:s}=h,i=n.Tensor,{text:u,map:p}=he(e,r),w=Oe(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 _=new i("float32",new Float32Array(0),[Se,1,ke,0,De]),D=_;const E=[];let N=s.start;for(let g=0;g<Ee;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:_,self_v:D,cross_k:x.cross_k,cross_v:x.cross_v});_=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 ye(Z,p)}function Ze(e,r){const n=String(e||"").trim();if(!n||!ae(r)||!S())return Promise.resolve(null);C++,f?.disarm();const o=M.then(async()=>{try{return I?await I(n,r):await Te(n,String(r).toLowerCase())||null}catch{return null}});return M=o.catch(()=>null),o.finally(()=>{C--,k()||f?.arm()})}function We(){f?.disarm(),f=null,d="off",y=null,b=null,h=null,I=null,A=0,C=0,M=Promise.resolve()}function Je(e){I=e||null,d=e?"ready":"off"}export{U as FLORES,F as INDICTRANS_FILES,oe as INDICTRANS_MODEL_ID,Ae as INDICTRANS_SOURCE,We as _reset,Je as _setForTest,ve as bpePieces,ze as health,B as indictransDir,ae as indictransLanguage,R as indictransOnDisk,Ue as init,S as isReady,ye as postprocess,he as preprocess,Ge as ready,He as release,Ke as retain,Oe as sourceIds,je as state,Ze as translate,$e as unload};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=Object.freeze({"ChatPanel/indic-transcribe-core-int8":Object.freeze({repo:"ChatPanel/indic-transcribe-core-int8",revision:"b4c0fe837b08848da00a34dfebf96ccc20078c24",upstreamRevision:"b4c0fe837b08848da00a34dfebf96ccc20078c24",licence:"other (Indic Open Model License v1.0)",files: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"})}),"ChatPanel/indictrans2-indic-en-int8":Object.freeze({repo:"ChatPanel/indictrans2-indic-en-int8",revision:"6ff7d97c0aed24658c10ebbb06246f5d1f204935",upstreamRevision:"6ff7d97c0aed24658c10ebbb06246f5d1f204935",licence:"mit",files: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"})}),"MoritzLaurer/ModernBERT-base-zeroshot-v2.0":Object.freeze({repo:"ChatPanel/ModernBERT-base-zeroshot-v2.0",revision:"1f3d0ba895fdc82405fddca9a222557824cca5cc",upstreamRevision:"d421c4545a438fd006fb43f8b981c5d908faa1e1",licence:"apache-2.0",files:Object.freeze({"tokenizer_config.json":"c5a7dfd44d93c5d7ed9b2ddcd7a6018e935ec7d53f1de45910ea9868e0ff1c17","special_tokens_map.json":"ea97ecdbcc73713039d8d64dbb05e3689495c96657fbd9a18f5bed381be81049","config.json":"d5c53ad1e5a23066144e958db475b1f8df7e8e45bf0ef6aba8a842c7f6450be1","tokenizer.json":"6c8aaa9a542084f2457eab775d4eeb51f92a70c0fd9de28d5edb0ddec3c08d30","onnx/model_quantized.onnx":"d49899e1fa3b04701a3e38b8040119d5b089ca9c0774736a23d1f5c9d9e6571f"})}),"Xenova/all-MiniLM-L6-v2":Object.freeze({repo:"ChatPanel/all-MiniLM-L6-v2",revision:"896b0eb884aec64387df172487c356dd67f31763",upstreamRevision:"751bff37182d3f1213fa05d7196b954e230abad9",licence:"apache-2.0",files:Object.freeze({"tokenizer_config.json":"9261e7d79b44c8195c1cada2b453e55b00aeb81e907a6664974b4d7776172ab3","special_tokens_map.json":"b6d346be366a7d1d48332dbc9fdf3bf8960b5d879522b7799ddba59e76237ee3","config.json":"7135149f7cffa1a573466c6e4d8423ed73b62fd2332c575bf738a0d033f70df7","tokenizer.json":"da0e79933b9ed51798a3ae27893d3c5fa4a201126cef75586296df9b4d2c62a0","vocab.txt":"07eced375cec144d27c900241f3e339478dec958f92fddbc551f295c992038a3","onnx/model_quantized.onnx":"afdb6f1a0e45b715d0bb9b11772f032c399babd23bfc31fed1c170afc848bdb1"})}),"Xenova/bert-base-NER":Object.freeze({repo:"ChatPanel/bert-base-NER",revision:"b99e1504f84f72d20f0a72fdbee9588030b74c58",upstreamRevision:"8e892123e8b7c2c0c2bd1dcb598b7d244c4e53aa",licence:"mit",files:Object.freeze({"tokenizer_config.json":"5be1a180e9badb4811a6c31502d70fb35a085af5457982937419c42d7530bae6","special_tokens_map.json":"b6d346be366a7d1d48332dbc9fdf3bf8960b5d879522b7799ddba59e76237ee3","config.json":"a73a2eccc921bbdea95a94b49a157d3694b5c2abbae7a6f3000e14404a9c31a8","tokenizer.json":"343989712a36cd8b253efeaf8baf6a08b9d2583f78e395e83832e8ee9f8d8ee1","vocab.txt":"eeaa9875b23b04b4c54ef759d03db9d1ba1554838f8fb26c5d96fa551df93d02","onnx/model_quantized.onnx":"caaee70a5518ec7f9e46e5308fcc9263a8c227703a9ce46cf61c69a552349648"})}),"Xenova/bert-base-multilingual-cased-ner-hrl":Object.freeze({repo:"ChatPanel/bert-base-multilingual-cased-ner-hrl",revision:"33e68447aad9399fafaeb4bbba5beb4e97fabd0d",upstreamRevision:"263e82c06569c8c2ac46238a7ae5107598934234",licence:"afl-3.0",files:Object.freeze({"tokenizer_config.json":"e6f3b96db926a37d4039995fbf5ad17de158dfb8f6343d607e4dbaad18d75f5a","special_tokens_map.json":"b6d346be366a7d1d48332dbc9fdf3bf8960b5d879522b7799ddba59e76237ee3","config.json":"7aa891abae067f95a40f5e2005b3de44824a083f256802934a993d301ec25076","tokenizer.json":"bf1b59b7b11c95f194f51708d918eea378e09d05f84c0e1656dc5180e8117088","vocab.txt":"fe0fda7c425b48c516fc8f160d594c8022a0808447475c1a7c6d6479763f310c","onnx/model_quantized.onnx":"5b65139844be260b624a2a13782b01d122e613d64ce16ed0ba4d82e0b816f1a9"})}),"Xenova/bge-reranker-base":Object.freeze({repo:"ChatPanel/bge-reranker-base",revision:"c6f7b72dc18d1a0894840f85af11ebf993170ac3",upstreamRevision:"280bcc27a84e0b898c251e06fddb25171bd9b101",licence:"mit",files:Object.freeze({"tokenizer_config.json":"a1d6bc8734a6f635dc158508bef000f8e2e5a759c7d92f984b2c86e5ff53425b","special_tokens_map.json":"d5469a60db23249c7f8945013d78df30b44b6bf686c6bb4740f4223f77b1b535","sentencepiece.bpe.model":"cfc8146abe2a0488e9e2a0c56de7952f7c11ab059eca145a0a727afce0db2865","config.json":"b6575b9d5be20d6747417c8e20c5a0db1636356e0b6d422d7244c628423c4d4c","tokenizer.json":"48564c5c7d3fa64d85d95e65414a542385f88b0f128fd8d4163fd7a57f2be05c","quantize_config.json":"98af4cceb8cfb971baa322d04dcf4146847112a73b2adbe85a2f9995380b30af","onnx/model_quantized.onnx":"dd98f3e67837d23210a6b7550c08cced4f61845b940ac45be3565840a10f3244"})}),"Xenova/distilbert-base-multilingual-cased-ner-hrl":Object.freeze({repo:"ChatPanel/distilbert-base-multilingual-cased-ner-hrl",revision:"6c6022f631f91e1d431b661f863ef0911fb5db51",upstreamRevision:"c2a4dbf593c57f47004c5bc2d3770d311aee9c43",licence:"afl-3.0",files:Object.freeze({"tokenizer_config.json":"2d61ce6c7646881e0e7ef08e3b5dd655a19553ab85c41b1a3c27090a63ff6f49","special_tokens_map.json":"b6d346be366a7d1d48332dbc9fdf3bf8960b5d879522b7799ddba59e76237ee3","config.json":"38847be4dc6699b1218a749ed69f888c2ccc7b4deba98e3c4a1cac8cb34d54c8","tokenizer.json":"bf1b59b7b11c95f194f51708d918eea378e09d05f84c0e1656dc5180e8117088","vocab.txt":"fe0fda7c425b48c516fc8f160d594c8022a0808447475c1a7c6d6479763f310c","onnx/model_quantized.onnx":"24a0b98f4dd4cd92842f5a541272f86f760225a64a29928eddef14bdb2edb986"})}),"Xenova/ms-marco-TinyBERT-L-2-v2":Object.freeze({repo:"ChatPanel/ms-marco-TinyBERT-L-2-v2",revision:"2c019ab060f9fec6b3e884031ac43075628b2960",upstreamRevision:"b76bb5e1fefd66aa36cd108622d768e86c015ff1",licence:"apache-2.0",files:Object.freeze({"tokenizer_config.json":"0b29c7bfc889e53b36d9dd3e686dd4300f6525110eaa98c76a5dafceb2029f53","special_tokens_map.json":"b6d346be366a7d1d48332dbc9fdf3bf8960b5d879522b7799ddba59e76237ee3","config.json":"463d8bce12140e74c56e008b1212b056487a76acdca8f31f9627d202f6e5a7bd","tokenizer.json":"d241a60d5e8f04cc1b2b3e9ef7a4921b27bf526d9f6050ab90f9267a1f9e5c66","vocab.txt":"07eced375cec144d27c900241f3e339478dec958f92fddbc551f295c992038a3","quantize_config.json":"ee36a0badc2f33788395258253a5bbd92c9575c294ee87ddcf8541ef4e4b922c","onnx/model_quantized.onnx":"026c2ec3257cd351696e45bbd6040bb83cf818ba89059b4344bd6350138b62ce"})}),"Xenova/multilingual-e5-small":Object.freeze({repo:"ChatPanel/multilingual-e5-small",revision:"200e4cc38871bec69fd3ecdeb9e52530746b1044",upstreamRevision:"761b726dd34fb83930e26aab4e9ac3899aa1fa78",licence:"mit",files:Object.freeze({"tokenizer_config.json":"a1d6bc8734a6f635dc158508bef000f8e2e5a759c7d92f984b2c86e5ff53425b","special_tokens_map.json":"d05497f1da52c5e09554c0cd874037a083e1dc1b9cfd48034d1c717f1afc07a7","quant_config.json":"59d175f15264115f18c698d76e443b5d49fc6c8c599911c421405ef4f236e87d","sentencepiece.bpe.model":"cfc8146abe2a0488e9e2a0c56de7952f7c11ab059eca145a0a727afce0db2865","config.json":"cb99455288675345e1a4f411438d5d0adbba5fbd3a67ea4fb03c015433b996c1","tokenizer.json":"0b44a9d7b51c3c62626640cda0e2c2f70fdacdc25bbbd68038369d14ebdf4c39","onnx/model_quantized.onnx":"f80102d3f2a1229f387d3c81909990d8945513e347b0eab049f7de3c6f98c193"})}),"Xenova/opus-mt-mul-en":Object.freeze({repo:"ChatPanel/opus-mt-mul-en",revision:"edbd7141e6d5270423c5835a1210bbe11e4e6ad0",upstreamRevision:"72a05e47cee89c718a9db4dc70d02fef3bc39de8",licence:"apache-2.0",files:Object.freeze({"tokenizer_config.json":"0e5fceb4caf753096870f0a74ec2a0a9825327cefd1cc06e0b8dc71e75257cf7","special_tokens_map.json":"5e4d1f5e759d74cb1c2fe1d165cfc62b5237aa904de759380cd6f43042eec723","config.json":"115093532b9893a6e3ec64951db15bafbad200f34929304f9570c3cd7f1dff94","tokenizer.json":"7ae61d18c438de0cf069a5cd25edc0d9d899353d710bf0e774819f97201049b9","generation_config.json":"66300b2138c7a98fe085d16b590ecbc01d64d46e9db240ee3dab4eadd3a3b1b9","vocab.json":"b1a8216e6f605e72eff0ebfbfc4956e3a906f965c18943843650595e7639bafb","quantize_config.json":"3310158b57ff031ae71ef32d36394f01a5920f8deb233c5760c0a4d0262a56a4","onnx/encoder_model_quantized.onnx":"5ce609a524375dbdd9c66b62b82b41abc667799022667ce424f20c245bd56925","onnx/decoder_model_merged_quantized.onnx":"6add167a0cd3f78aa298b8f927d2e8645e33cb17df11e92967f0c5b5703c8c4d"})}),"Xenova/speecht5_hifigan":Object.freeze({repo:"ChatPanel/speecht5_hifigan",revision:"5a79f70573ab97463ff573df84efe33f6c8dac07",upstreamRevision:"cf980c3610d7b7f20919960031066ef7905737bd",licence:"mit",files:Object.freeze({"config.json":"ac281bbb65c617a3fe7c5c082c8106f5a35b14d236b6a12f99cbbb12e576ab96","onnx/model_quantized.onnx":"d092ea63bbc7839f7317657b5f531ebb68377ee05ec866ec096dba25911f9feb"})}),"Xenova/speecht5_tts":Object.freeze({repo:"ChatPanel/speecht5_tts",revision:"90853f7b1b308f51bc2926bd646f8050f94981b0",upstreamRevision:"1723781b8ce2d02f0400c8337be04ae8ee3d6d56",licence:"mit",files:Object.freeze({"added_tokens.json":"74be21ecff0a1fb1f304fe7c72ab21e4f0c046f8359fdf2852eb1b80967069ad","tokenizer_config.json":"08d5008bb9b6148708903afe05005e07de62c28e4ccbb6bdaa49aa8bfcd2f715","special_tokens_map.json":"2a098b61fe8ec4cfd7674832ca00b4268c07569743a4ad15c8164e8f60ebf981","config.json":"0b47e6ea983aff5da32c3350f994b9e18990828e189403f552bf9bb10fb6e2c8","tokenizer.json":"1381e2dfcd93595198d95641e3d39a949a2e4182b9861e4af4f48a7169eff630","generation_config.json":"514529d2e14e72ef46f694571b4eb4e4aeb5e5c8f19008b6d03d88dd67ea6eca","quantize_config.json":"a71e676420e72dd003c0a7e9d64f6b49b69af9537891f4aea6188bd5fb95592b","spm_char.model":"7fcc48f3e225f627b1641db410ceb0c8649bd2b0c982e150b03f8be3728ab560","preprocessor_config.json":"10d99213ddec28d60d84ffe9a3bc0cde226f75bbcd43cec8bdb61616739e295c","onnx/decoder_postnet_and_vocoder_quantized.onnx":"d092ea63bbc7839f7317657b5f531ebb68377ee05ec866ec096dba25911f9feb","onnx/encoder_model_quantized.onnx":"407375255d220d8ddf81e9a06d4100f80f870f8446e77d4f20951d2a4c08a156","onnx/decoder_model_merged_quantized.onnx":"6afe602f82ecdb34a2db003f45ccc1419c77aaf0032c263b4f6a0f8bf5835798"})}),"fastrepl/dtln-aec-128":Object.freeze({repo:"ChatPanel/dtln-aec-128",revision:"a178b10d8d820181e54df15b7b8f2d4a691a736b",upstreamRevision:"b14809dcd80fe80c5158c8a9f5a19fa173878b12",licence:"mit",files:Object.freeze({LICENSE:"38569841148e8eaec6ffa093c02ba0c15ef2481dbf08a763c0e356c24cfeec3e","model_128_1.onnx":"a060e46a6bebed03d6360262d814851dc6c2806cec7c1b6a388e617cae7c082c","model_128_2.onnx":"6b6e312f701a3fad2aac2981ca1ed978d25dffa0bc8da9f33235a2e91f56705a"})}),"istupakov/parakeet-tdt-0.6b-v3-onnx":Object.freeze({repo:"ChatPanel/parakeet-tdt-0.6b-v3-onnx",revision:"bf2e9dcbaa087a5b0649e1fef96298f2c3a2e3db",upstreamRevision:"8f23f0c03c8761650bdb5b40aaf3e40d2c15f1ce",licence:"cc-by-4.0",files:Object.freeze({"encoder-model.int8.onnx":"6139d2fa7e1b086097b277c7149725edbab89cc7c7ae64b23c741be4055aff09","nemo128.onnx":"a9fde1486ebfcc08f328d75ad4610c67835fea58c73ba57e3209a6f6cf019e9f","config.json":"666903c76b9798caf2c210afd4f6cd60b08a8dbf9800ec8d7a3bc0d2148ac466","decoder_joint-model.int8.onnx":"eea7483ee3d1a30375daedc8ed83e3960c91b098812127a0d99d1c8977667a70","vocab.txt":"d58544679ea4bc6ac563d1f545eb7d474bd6cfa467f0a6e2c1dc1c7d37e3c35d"})}),"jinaai/jina-reranker-v1-tiny-en":Object.freeze({repo:"ChatPanel/jina-reranker-v1-tiny-en",revision:"560d54caeff43e119009bbae1d27ebc3c2018912",upstreamRevision:"aca45de6945b5dc6399abcd2a9c55ded5dc9111f",licence:"apache-2.0",files:Object.freeze({"tokenizer_config.json":"d291c6652d96d56ffdbcf1ea19d9bae5ed79003f7648c627e725a619227ce8fa","special_tokens_map.json":"06e405a36dfe4b9604f484f6a1e619af1a7f7d09e34a8555eb0b77b66318067f","config.json":"dc70646aa6c9e75e3c513cc9c037f35ad54308001c3961d45c0f69749bcfb022","tokenizer.json":"0046da43cc8c424b317f56b092b0512aaaa65c4f925d2f16af9d9eeb4d0ef902","merges.txt":"34c90c55c32ada402c943c79555515b9eea2cbaf5bbcd970b012a2bc8e0ad331","vocab.json":"62a861857691f39b92935580e929a31e7869056e5de5119ef81f5c62ffa1a4b5","onnx/model_quantized.onnx":"5fa8508528828b4ad9bc97c97b6e020984e3b745fbcb53f0a907e68704f8a18a"})}),"onnx-community/Kokoro-82M-v1.0-ONNX":Object.freeze({repo:"ChatPanel/Kokoro-82M-v1.0-ONNX",revision:"79c493ccafbfea9761ab75d41d29095cf7dcd238",upstreamRevision:"1939ad2a8e416c0acfeecc08a694d14ef25f2231",licence:"apache-2.0",files:Object.freeze({"tokenizer_config.json":"be1cb066d6ef6b074b3f15e6a6dd21ac88ff3cdaedf325f0aaed686c70f75d20","config.json":"df34b4f930b23447cd4dc410fabfb42eb3f24e803e6c3f97d618fb359380a36f","tokenizer.json":"77a02c8e164413299b4b4c403b14f8e0e1c1b727db4d46a09d6327b861060a34","onnx/model.onnx":"8fbea51ea711f2af382e88c833d9e288c6dc82ce5e98421ea61c058ce21a34cb","onnx/model_quantized.onnx":"fbae9257e1e05ffc727e951ef9b9c98418e6d79f1c9b6b13bd59f5c9028a1478","voices/em_alex.bin":"27809e9eafdcbcfff90a3016c697568676531de2a2c39cee29c96c7bd6b83e95","voices/pm_alex.bin":"0175c753f59c54e7fd5a995bedef0c5ff2fb67e0043dd3dcb2ae74ec2acbeb2a","voices/zf_xiaoni.bin":"08892b62a39af0a615cd0581238db7e19e44c578e8fa0bfd0e586e93327d9cba","voices/jf_tebukuro.bin":"29c6c0561b4288d59639677bebe7533c919743d5ea68d0d2ae992644beea6696","voices/af_nicole.bin":"cd2191ab31b914ed7b318416b0e4440fdf392ddad9106a060819aa600a64f59a","voices/am_michael.bin":"1d1f21dd8da39c30705cd4c75d039d265e9bc4a2a93ed09bc9e1b1225eb95ba1","voices/bf_emma.bin":"669fe0647f9dd04fcab92f1439a40eeb4c8b4ab1f82e4996fe3d918ce4a63b73","voices/zm_yunxia.bin":"6b2b8fc15b3df19a368daebe5c581c7fabf433ee5b8a17ffd6b3d723cff8936d","voices/jf_nezumi.bin":"13cb71eebb0b48739d444558322aa35a8c9a489b80e1e631f14d2e6aea93026b","voices/am_puck.bin":"fcf73c989033e9233e0b98713eca600c8c74dcc1614b37009d5450ff4a2274a0","voices/am_onyx.bin":"da5d135b424164916d75a68ffb4c2abce3d7d5ccc82dd1ee6cf447ce286145e6","voices/bf_lily.bin":"5e0ee32ebe64a467124976b14e69590746f1c4ce41a12b587a50c862edfea335","voices/am_eric.bin":"e8b5be17edd1e3636901ce7598baafe2dc8dd8ff707a0c23bf9e461add7e2832","voices/hf_beta.bin":"cd83ae0bb9b2e4e4fb92b4973bd8d1822ca0036d3c498bf4fc89aa8e33917cc7","voices/im_nicola.bin":"bc578e510d52a96d6940d46f12e96d7b3df00905dbea075113226d100e6e1ab0","voices/zm_yunxi.bin":"7243892fb4e560d47014090ddf010f8b8b790f3c6b029ff82b2ac06aa4e27c8b","voices/af.bin":"a4f11d9d055a12bfa0db2668a3e4f0ef8fd1f1ccca69494479718e44dbf9e41a","voices/af_bella.bin":"f69d836209b78eb8c66e75e3cda491e26ea838a3674257e9d4e5703cbaf55c8b","voices/bm_daniel.bin":"6b3194bbceffb746733cbc22c8f593dd44e401a71d53895a2dca891bc595a1e8","voices/am_echo.bin":"3968b92c3c4cd1c4416dbded36c13eaa388a90d5788d02a13e4d781f5f8cf3c3","voices/jm_kumo.bin":"09e959d239724c734d65661f06f14cdabcddfd476bfaaad905a937099ae9e64f","voices/af_aoede.bin":"4a004c33430762e2461eedb2013fad808ef4ab3121f5300f554476caf58d8361","voices/ff_siwis.bin":"a35f5675ad08948e326ae75fd0ea16ba5d0042e4f76b5f3d1df77d0a48c54861","voices/hm_psi.bin":"644daf88ba8aeb7bd08950bbdcd4453bb280864e49dc4df93fabc6be32e03f37","voices/af_river.bin":"00a2bcf82b1d86e8f19902ede58c65ccf6c0e43b44b7d74fad54e5d8933c9c30","voices/af_sarah.bin":"4409fbc125afabacc615d94db5398d847006a737b0247d6892b7a9a0007a2f0a","voices/em_santa.bin":"ad43b774e1ca24d05c6161297d8aeb770ac3d29bb95daf516727af5f7d543683","voices/bm_lewis.bin":"b8f671cef828c30e66fdf0b0756a76bba58f6bb3398cbbf27058642acbcedb97","voices/hf_alpha.bin":"040be6a4425411cc01fda5fd06693c76bfa78572632852bc8cda9c99232ffb56","voices/am_fenrir.bin":"c27989f741f7ee34d273a39d8a595cc0837d35f5ced9a29b7cc162614616df43","voices/ef_dora.bin":"f66ec66bd295acb18372e37008533a9a3228483ccd294e7538d5d9294ac9a532","voices/pf_dora.bin":"3da7b5b2d91847ebf5646f57631af6ececae3c29a89cd300f06edf9aa6cfe9ee","voices/zm_yunjian.bin":"de48a00bdbf3649f07162269a2b6e0513604389bfac8a2e6c75cb34b323ad6fa","voices/if_sara.bin":"409b69248798fcdc2542330c76953d230710f19b057e59cb82fdc3c4cf71265c","voices/jf_gongitsune.bin":"0f1181f3772d27b7c12aaf4bcd71e31b186c4146e330d074a3dc64ee392af396","voices/hm_omega.bin":"b02d9222d9ed00ce26b302173a862c2c93f96cc40b5c422b8d14910b9ff34137","voices/af_kore.bin":"9be5221b6a941c04b561959b8ff0b06e809444dcc4ab7e75a7b23606f691819e","voices/bf_alice.bin":"08afa6ba24da61ea5e8efa139e5aadc938d83f0a6da5a900adaf763ac1da5573","voices/pm_santa.bin":"8b012db3185778afe2e45a62cbad69db73021774fe68dda634bcc748a982eede","voices/bm_george.bin":"c4b235a4c1f2cd3b939fed08b899ce9385638b763f7b73a59616c4fc9bd6c9bc","voices/zm_yunyang.bin":"261e2c89470534dbbcb8fd98b8fdc495ec94063d9bb6c8277f7be43cccba3f42","voices/jf_alpha.bin":"56b479360aad9f367aeb8cef908f9201cf48b4555e488c5f4590c9dfcd978bb6","voices/af_heart.bin":"d583ccff3cdca2f7fae535cb998ac07e9fcb90f09737b9a41fa2734ec44a8f0b","voices/zf_xiaoyi.bin":"bc1555c5c486099196ac254bae5e0bb543c121952a3092f50b7d8724f1bc36b3","voices/am_liam.bin":"52403be32fd047c6a44517cb0bcd6b134f2a18baa73e70ef41651e0eab921ade","voices/af_jessica.bin":"a240a5e3c15b43563d6e923bdca8ef5613a23471d9b77653694012435df23bd8","voices/bm_fable.bin":"f889083196807b4adb15e9204252165f503b8d33d3982e681c52443c49d798f1","voices/af_nova.bin":"18778272caa0d0eebaea251c35fd635f038434f9eee5e691d02a174bd328414f","voices/am_adam.bin":"162b035ed91cfc48b6046982184c645f72edcdd1b82843347f605d7bf7b15716","voices/am_santa.bin":"61150cf726ab6c5ed7a99f90a304f91f5a72c00c592e89ec94e5df11c319227a","voices/bf_isabella.bin":"3754352c4aaa46d17f27654ab7518d65b62ad6163a0f55a5f4330c2da2c4e94f","voices/zf_xiaobei.bin":"5dde6e1c9c4f12c8b327bc29c0cee361a23b52b952c04636858ba637ec66e640","voices/af_alloy.bin":"c4a6b876047fd7fb472edf4ebd63cfac7c3b958a7cae7c106e8f038ca6308c45","voices/af_sky.bin":"4435255c9744f3f31659e0d714ab7689bf65d9e77ec1cce060f083912614f0b9","voices/zf_xiaoxiao.bin":"03adb5d5e3ddd88b047954e974e651cb0a4b524c985057e5d872e962c7be1169"})}),"onnx-community/Kokoro-82M-v1.1-zh-ONNX":Object.freeze({repo:"ChatPanel/Kokoro-82M-v1.1-zh-ONNX",revision:"1ee15f22e2f70c2a44a5937a9ad4195f7aa32679",upstreamRevision:"6cc0f0d2ebe369a68b0df87c2b65c1af8c0ac3e3",licence:"apache-2.0",files:Object.freeze({"tokenizer_config.json":"be1cb066d6ef6b074b3f15e6a6dd21ac88ff3cdaedf325f0aaed686c70f75d20","config.json":"df34b4f930b23447cd4dc410fabfb42eb3f24e803e6c3f97d618fb359380a36f","tokenizer.json":"5715a60b09d5e4b9074435d68c6ccd5675b9d48b220e109fdea3cda681e23d15","onnx/model.onnx":"94b973941b1852754f979be5d5e20be666d5c81d9bb886b88ae1dc85c9b895ca","onnx/model_quantized.onnx":"a39469be791eeaa3089c1ed5e58b8731d1f2462ea0e7dae2bc44388e58f973d8","voices/zf_092.bin":"ffd200defd2867f79886eb0e45540d53ed0dc00ceb222c5fa692f004958d3e11","voices/zm_037.bin":"535ec47cb6ed66c203f61ace51eddbc7a13ecaca2458c1d8d5a928fb3db4b315","voices/zf_086.bin":"c228ba018bf56d5de1339bde10dcbea7700797b85351e4d57ee5307ac7d3ee99","voices/zf_051.bin":"64df55d707d3c28dec15c5c9051653b6a6cbbbf85c52e56183d3922e53415e76","voices/zf_079.bin":"2df9a9fbbd39a54077a2c5073c04c7e685ce0342b34f22fc85c25a1f7a3954c7","voices/zf_078.bin":"82d591700a9ecb3cb14d3d05ec5aab18bd7a482d677bf6522cf96ed4c064b23b","voices/zf_044.bin":"e166c8b2a680d3f51f1765cedc4ed7a29308ea40081b03347d5cd95f52119cc0","voices/zf_087.bin":"e0347f1430b80781d910bf1499cf64d231c34b70d6e46f30f3598254d5114d44","voices/zf_093.bin":"d736ac1738c5ba567f8e5e9bfac8d9a774e9e3a3d001b5976a5d005c9179f811","voices/zm_020.bin":"2a25ca83ddfd003c0b82d97899ff38734db8faf48e5e4076d68c69aea17705c8","voices/zf_085.bin":"2451d63f576c9ffbe91acd11f2720b6e76dc75b293d7350a9620a28c23da9ef8","voices/zm_034.bin":"b371bef26b75c826de15c836103da3e037a44f605ffe744d68ad485d17e370ab","voices/zf_046.bin":"73e8881e76670cfe803c8ab0ccc6b5daae22efdc3a67f8e0e80658a4be21d3af","voices/bf_vale.bin":"2536f7922d31d96e994135ac2bb73f5a3c01326476200513c57d988822c6ca4d","voices/zf_047.bin":"620f92a680c5a28bd8eb601738721047b73008bdf5b880f34075181afbfdcb62","voices/zm_009.bin":"7b74d6ed22f201e2fa28758e78ce6197082779f2b80e69ea1bf877908609514a","voices/zm_035.bin":"8b1c603f6e1eae300ac1a6f1199a5bb1ce9814d3e1e61f7536d21b564d680476","voices/zf_090.bin":"fe90b3e651c3741edf6bc08a543c531c798ec53fab1fd944ab537e9257270c68","voices/zf_084.bin":"2b2d4fdefa9a6c3d9f472d91600308be8b827a929955ec66afe81aca50c99968","voices/zm_025.bin":"cbb4cd1df85b5dde4cf742c61d9b93e179574935c1162d06604bc4be6a8e990d","voices/zf_094.bin":"b37b96e3c51d12f152c9476cae42396ac38cdab76f09cc935f2fbcd8fa012f42","voices/zm_031.bin":"a5974232ed634be2ae40526101ee7c653120fdb354b1584f2bb38ed4fae4a39e","voices/zf_043.bin":"7d257954b651436e354712738b22e8365ed908923a5d0f154690188b2c73ea78","voices/zf_042.bin":"713160091b44d962ab73e3bf66f0c2f0b9677aaf0c2f0e62faa94ed451540d1e","voices/zm_030.bin":"32f8fe4d5f626dfb67adb73499690fd4f5952763746efbcadcf2daad4a3560a6","voices/zf_083.bin":"5557cbc381e0f2cd2a29759fdda25eca664492f1cfa3fcc241e7adeaf4164661","voices/zf_040.bin":"bae25bd2c4dd717ce65effa2350b28a55a73f53a0bcc2cca5876a15e984eaa2d","voices/zm_033.bin":"758e64c15efad492beebf575eb96951e0500da980bf5e8a3850d078d0430dda1","voices/zm_054.bin":"4f7aeb1627fa1d406bcc1a83e4eeb8b014509dca492dec0ae7dd4d0d1cdbe8b3","voices/zm_068.bin":"ae265665e29656ea0d151f3315c649d892ecf053391c3c3bec5f10bf18531a58","voices/zf_032.bin":"2ab0b9b1fe2f1e4cfa08b0126581df3316c12aadeadc51136c826255debd2058","voices/zm_097.bin":"e60ec05738261c2eb13c43f7429ece6b32e0992223b0a6336a9fcdec90fb8da4","voices/zf_026.bin":"2a2434fed129796276c61947fc65bf7dadd569468ea4edaca81f3d59802bdc32","voices/zf_027.bin":"9301e7a0b80eedff7f314076e07f9eb74b687afb7fcb2c64ca94168469858aae","voices/zm_082.bin":"7351d7652d97ec5fcb7632b317d7c4e062fff3cf4ed0246167d3d15e97046c01","voices/zm_096.bin":"e6b76d86ca459d8ce87d2a41c812319b11e9563ecf1ba80a4e86a368d6c02fbc","voices/zm_069.bin":"54ac2dc25ee5d1dfa72f777ff538faf69033705019a9e15f3138deb79a965774","voices/zm_041.bin":"8b7bd5649a00c62e87a6099eb31d683664bfb0fd55bcd5211da62e95b3b78ffc","voices/zm_055.bin":"3cf77a37899053b5a7c224f51a22371dc37d30667d87e1b481e760ac0f8f0da8","voices/zm_057.bin":"29cb23f82add956f25c7b663db2027d5a50abb7035c7cb15ee608e193a412f51","voices/zm_080.bin":"cbbcae6bfd6c2f3875b2163fffc8851aeae1b8bad2f1006a94ea4e6f9b44ae9e","voices/zf_019.bin":"ab5906846335ac1227c47fd04be8b7b10a47c3ee77729296cc4c0f3f8fe79073","voices/zf_018.bin":"a9ee6566c7500ce90cbd177f1d6f6cae533356e5f0e37edf3adbd0a8f2d44020","voices/zm_095.bin":"4d4dac7245ea4c4c4740137fca229932055e376aed2b1ad7cd0e3e3859a13b75","voices/zf_024.bin":"2d0f2df7b25482f6870cfbe8e83c7d1e74ed8ef8ae72df749207ea9cec7c9102","voices/zm_081.bin":"ffc1341f044c95ad8ef598079df9e3a85d81d093268ae8422848a9b81d386fd2","voices/zm_056.bin":"d5f48143152f376a940182741589fb1f588387e09f1a9263760981f8702af816","voices/zm_052.bin":"e775a71cd74c5462d5a6c3f0ff7681f04419053043ad2dcbabaa13d0c6de0b08","voices/zf_008.bin":"23e20843a71fb8c5f6b984c8d4e74dd590251aeb8f620cb07a57e1485d726b0c","voices/zm_091.bin":"6ab4a21b702ec57161f48e350de3fa0b0bd1d13a890657398cfa21452d85a9b3","voices/zf_021.bin":"c16f939c566f786150be3e3cb6a61f7fd8d4214a26a46d3e80e1d61de06d54ec","voices/zm_053.bin":"a549dcf0456b2ba1515455e0a30d111b00d24e748880e03da1965cd4ff10baf7","voices/zm_045.bin":"68d5e7f3415811a076326178c2d9f5d3aa168cf27deb6ae3f0395ab97ad45225","voices/zf_023.bin":"d02846dc3b8a89b4f81634b407ce8dd30d80db40fc952d54f05853a8e26a2190","voices/zf_022.bin":"c1cde40b2fd522355d2ae152d06d1033b04ad3528b7273cf25dd68f28a5563db","voices/zf_036.bin":"b72873066ef9d57d4ea0605d32a82b2655010af51edbaecd6f926250d84efa4e","voices/af_sol.bin":"87c1d6d6a3f13f89ed54a6a67cc1ff75b926aebc3a2aac3086e6dd109a8147e6","voices/zm_050.bin":"7869f25a5e71ea9b67a1893777e375ac411bdbfb75feff5efe25fad2fc766c8d","voices/zm_061.bin":"d57141bd480e7a4f1a3b5d3365ce53ac04cfe6dd9d0f2d3a052213f80657046d","voices/zf_007.bin":"23b6c4312208de7f195e4e78eef0ec9e498cd52907b1678ecb7a0a1996a51573","voices/zm_100.bin":"112de52f1aab3b370fd01f4e2e1d8bb37fee2725e77e14b81c802d50687e0e6e","voices/zf_006.bin":"52dee405a0e609d6d2869eef05984745db435a73aea49db7418494d5cb53bf9d","voices/zm_062.bin":"171d8811bfeb198714b0d3733ed740eb56be0aa3e6d2bd7b127904116a199f93","voices/zf_004.bin":"81fe28be1c496ccffa73078d5c2e6d9cc5e5f91e354d6ae0f494a9c28a42064d","voices/zf_038.bin":"569bb54ebf05c00c89eaf56218992474a8a0494d8f94a14e933ae6a5ea9f7e31","voices/zm_089.bin":"f4315ceab376b4082cc9cdd8028d37f9aa7d43ad67ddb85902a247df0913ca89","voices/zf_039.bin":"92ad68f36d16860dcf125fdf87a4572c7ab6d7efbe6a7197d6772242a2cbbb56","voices/zf_005.bin":"a91d2c2adecbb7c191dac4fa35e213e8d370e0c733a9bf36797f513924dcb84c","voices/zm_063.bin":"6fbe326e5852cd9dbac7eb7e9c9989a604e51074d251a8ff8365e050c83b2a6e","voices/zm_098.bin":"7dd142334e863af31c7e0d0fbe491b8d54083ff5322441d550fcfc5e4111480d","voices/zf_001.bin":"0a89ec12bb93fb9c74077924daf02568baad64e1f869389f5aaee01a386035f8","voices/zf_028.bin":"8d15e55ad315708010c1528c633828e3179d5cbf0bfcd2db0fec27f63001eaec","voices/zm_066.bin":"fcdd1d4c8b2808c4456418c76ed2321910b3f1b5c2646365af4ee0e8c6c53c4d","voices/zm_058.bin":"0cafc2ef83710c4ce55b384107426cfdcb23aabf5699e106ff392f9571b4d4f3","voices/zm_064.bin":"6e712d18758f2d8654c97fb274c23b5148dbafc1027ee6539446d4c8aff308cd","voices/zf_002.bin":"452f96e1e3c20b14b228b5336a8d7e833b105f837d98ef53b4ddfce18eed39bf","voices/zf_003.bin":"a70654663d013a700f8afe42d57d1ce03ff49af8bdedbbb56c7e3da6e820b788","voices/zf_017.bin":"9c6513e77a8efb7172a4e4ebeb48b3b010152d8cd6a0f2fa1adb353248fd91ed","voices/zm_065.bin":"77918a32b75bf7902a6cee310cd22fb16de7ecbb9aa438a05039ebec73f9e0e8","voices/zm_016.bin":"4dc408a11f1e8925ff8bca40c885e7596d08be63c2c61571234b96170f8e6d1b","voices/zf_070.bin":"f225305611865b09dc8cb36439143c02a404299b00508e00676655bb117342e2","voices/zf_059.bin":"f12fd6e34f602445173f930c4f41b4d064e1a981b39b664591ad2476fb7425cc","voices/zf_071.bin":"454cd5aaa9458f3b028e973d19902a002eb59fc743eb94fb3c7c9d5d7a190a07","voices/zm_015.bin":"e695c8d72b3eb4a864f4735db7f4f93de100ff62704e619edfddbebfafb07312","voices/zm_029.bin":"ff78cb9f64d43fe6179c9479257775bea94dc31eade9362b0c630749025d8ecd","voices/zf_067.bin":"5669caef309a3746a47588d893d58fa61c721a94ca07e431c732ea9a2b4abc6a","voices/zf_073.bin":"b8ecf6945ae7bb2a0353422b7af32d3b928c5fdccf3ea553bc61227a57bf4a2c","voices/af_maple.bin":"bd5b230b916ea98c67a3a7a833a3ce43e535ce56a81503f4166ee9390b9ddeeb","voices/zf_072.bin":"2274b572b44723e80eee422a914c96b37ee42bf9b5ca60e7f656bede7860a1d3","voices/zf_099.bin":"9582b2ffb5027c695f6775161a8856108fa68530c6c1e29d2354d455d9eaa937","voices/zm_014.bin":"565aa48a99d8a196ebdd1c72f4a0e5760fed65aa95992c887385d3aad9e1d2f8","voices/zm_010.bin":"73b088f7e0dc47adca4d6a642ee68843df90ff56ec2800c29d96609989d6de0a","voices/zf_076.bin":"58351a1be5aa04f874bea0e5228fc0e0047dc2ee801e915d4f59513ca60a3194","voices/zf_077.bin":"e2fd07f3b62e204cd6632696e2a975678e7e6aa5a9b2cb4927f94d875c113625","voices/zm_011.bin":"ec4d7d934b9aa47e0e98e6ec802bb7b0a221be6f1b67d923d33b7082d9bbfe9f","voices/zf_088.bin":"ee1e80cdeaffb55e1f6c41005c4966b8979b16bb808fa451739e06953d343c13","voices/zm_013.bin":"2caa23e98910fb232a2bf6aab563666588a82bc37c99b67963ab304c5be66dff","voices/zf_049.bin":"4808ba6dfc1c13af9921bb5072faf875b69bc54777281eb549592b1aa7e8a4bc","voices/zf_075.bin":"84e70ca9aac5178ceaeb1eae95dd77278d71e60cfacaf9af99852922b4355560","voices/zf_060.bin":"429ad8ffb6fc8b68d3b77f2ccafba5be50e4ec31d25f890d739a16449ca01748","voices/zf_074.bin":"8e6726977c7494dfd567c580963630834c0971f66111e06c9467e6f7d912ea1e","voices/zf_048.bin":"24e0aa66d1cb264e86adac5ea143f7fb0a9672a8b237ba1ad017aacc1fb0290a","voices/zm_012.bin":"50d1986f71ea1a2b3ab1bfc0c95bedc59e8de45e650bc5bde87fd99ceb83cdfb"})}),"onnx-community/multilang-pii-ner-ONNX":Object.freeze({repo:"ChatPanel/multilang-pii-ner-ONNX",revision:"2bc78e45ebe3e0d3b9ddb86e72d58283c25f1c11",upstreamRevision:"730c579658f8258600cc8a069b2fad1615289201",licence:"mit",files:Object.freeze({"tokenizer_config.json":"9c8ae206d3538c14363c221d3bf5872fb06bad35b80fd1af7f8cd2cddf257b60","special_tokens_map.json":"8c785abebea9ae3257b61681b4e6fd8365ceafde980c21970d001e834cf10835","config.json":"3503fb27021640b315b1e7636933f7df9c209746251cae4975bdef46be4e8158","tokenizer.json":"8373f9cd3d27591e1924426bcc1c8799bc5a9affc4fc857982c5d66668dd1f41","quantize_config.json":"9b60b5877b9a1687b5cddbc06124a974cb7536af9dbf5295279bf73c3823170c","onnx/model_quantized.onnx":"1d02f3829ad90d95dea5e64d35f5528f96d7b223c1e056a96075c6229a484356"})}),"onnx-community/pyannote-segmentation-3.0":Object.freeze({repo:"ChatPanel/pyannote-segmentation-3.0",revision:"9b3289a96db9cff868171b80132d3cd4358e8dab",upstreamRevision:"733a93b6473d019a773298e08cefa686894b1854",licence:"mit",files:Object.freeze({"config.json":"5a4c6bb4f49f1b47c9bd398aac78b8cd4a9f30a0ff91b5c2dc68d05e13e160cf","preprocessor_config.json":"dfc7d35a3895f8997eb94521e28b1921c03480a34fa9bcbb6bef1f1934f81480","onnx/model_quantized.onnx":"93a3eb106923c9b76a7d8af07ac337dd24c2d0dcd20f1b6c55f21133e944d658"})}),"onnx-community/silero-vad":Object.freeze({repo:"ChatPanel/silero-vad",revision:"ff06e9ebfc661bdda5bb7e2ac91426d73630232c",upstreamRevision:"e71cae966052b992a7eca6b17738916ce0eca4ec",licence:"mit",files:Object.freeze({"onnx/model.onnx":"a4a068cd6cf1ea8355b84327595838ca748ec29a25bc91fc82e6c299ccdc5808"})}),"onnx-community/wespeaker-voxceleb-resnet34-LM":Object.freeze({repo:"ChatPanel/wespeaker-voxceleb-resnet34-LM",revision:"d4208aceb97daec8f5850ea1c2d99f4986ac32b3",upstreamRevision:"6a61a1833ff2583aabeba044f5c8221f00b67ceb",licence:"cc-by-4.0",files:Object.freeze({"config.json":"4a65a1544d2085d7819632f130583d83f6815f49ef6c8ba6c8eb460bd4085041","preprocessor_config.json":"a81bbded0530b1bf5c3d395d2c5c7c266686e348be5989171290ace960f24ec2","onnx/model_quantized.onnx":"f73f647730ae440ae411c2241290f42ff5b2106dd3176c897fe6fbb1950d5393"})}),"onnx-community/whisper-base":Object.freeze({repo:"ChatPanel/whisper-base",revision:"03e65a7c6935960b5fe834376d915456bfe4b165",upstreamRevision:"27a07b4b52b3a4c5886134bb4320e93e1a4bbc7c",licence:"apache-2.0",files:Object.freeze({"added_tokens.json":"9715fd2243b6f06a5858b5e32950d2853f73dd5bc201aafcf76f5082a2d8acd1","tokenizer_config.json":"2e036e4dbacfdeb7242c7d4ec4149f4a16e86026048f94d1637e3a8ee9c6a573","special_tokens_map.json":"e67ae3a0aaa99abcd9f187138e12db1f65c16a14761c50ef10eef2c174a7a691","config.json":"f4d0608f7d918166da7edb3e188de5ef1bfe70d9802e785d271fd88111e9cf4b","tokenizer.json":"27fc476bfe7f17299480be2273fc0608e4d5a99aba2ab5dec5374b4482d1a566","generation_config.json":"61070cf8de25b1e9256e8e102ded49d8d24a8369ed36ef84fdf21549e68125a0","normalizer.json":"bf1c507dc8724ca9cf9903640dacfb69dae2f00edee4f21ceba106a7392f26dd","merges.txt":"2df2990a395e35e8dfbc7511e08c12d56018d8d04691e0133e5d63b21e154dc6","vocab.json":"50d6a919f0a0601d56a04eb583c780d18553aa388254ba3158eb6a00f13e2c1a","quantize_config.json":"6e0e27f293a5c17ff2ca8046f06079c0120aa2ede6456faac8ec4b3203471a55","preprocessor_config.json":"a6a76d28c93edb273669eb9e0b0636a2bddbb1272c3261e47b7ca6dfdbac1b8d","onnx/encoder_model_quantized.onnx":"5862993336bf33acd23736071aae2b32261d3b1b2f37780194460d4ef974dd46","onnx/decoder_model_merged_quantized.onnx":"fa3ef9902734ce5ae6f9ef2bdb2ba9a6c4b5785b09f4f420ce036573dc9d090b"})}),"onnx-community/whisper-large-v3-turbo":Object.freeze({repo:"ChatPanel/whisper-large-v3-turbo",revision:"a063f6bb91780f41231b77bf5b1f5b6d29e5b2f4",upstreamRevision:"360ebcde2559d60bb474678be3c1de9ef347d01a",licence:"mit",files:Object.freeze({"added_tokens.json":"3c51f66c4c21f9e126970078f11ae77a78c74aee8df606ee9daba86e467108e0","tokenizer_config.json":"844b642c73a91359722f47b35705f7174686df33d252695d8572cf9ac03a6389","special_tokens_map.json":"baea4ea09372eb4fca86b4e4346139fd73cb807d5087e9de0948e971739c3e74","config.json":"35cd83669f75bc2867f3b3a4461850392d5e308cd6ea951c3700539883c28df1","tokenizer.json":"6d8cbd7cd0d8d5815e478dac67b85a26bbe77c1f5e0c6d76d1ce2abc0e5f21ca","generation_config.json":"16f95291d2f47c944d3c2b19390bba7965666555c1ea2a0bdc850d1fab45612f","normalizer.json":"bf1c507dc8724ca9cf9903640dacfb69dae2f00edee4f21ceba106a7392f26dd","merges.txt":"2df2990a395e35e8dfbc7511e08c12d56018d8d04691e0133e5d63b21e154dc6","vocab.json":"e2aa043ef015641d363d8288e7c241c85e36a5c761fb303598e0710233344387","quantize_config.json":"8da6e4e50ef7c210ba66a98a4256e6d60e38cef8a9a9c74d327251aaf4e78767","preprocessor_config.json":"7ccc62c6f2765af1f3b46c00c9b5894426835a05021c8b9c01eecb6dfb542711","onnx/encoder_model_quantized.onnx":"d2f853dc3254fdc0079f55dd4433ea716ac98ec5574d3b475f288f2a77cebba9","onnx/decoder_model_merged_quantized.onnx":"61481bd3be3a445d5a4b9070e8f8b2c6cc4fbbbbdc9f0e7ed048a132b8b84e0d"})}),"onnx-community/whisper-small":Object.freeze({repo:"ChatPanel/whisper-small",revision:"0fbc13f026bf704d669faac49985eabd5af2dde6",upstreamRevision:"36050c46d777d46dc4b5f43f6d90574fc38f8732",licence:"apache-2.0",files:Object.freeze({"added_tokens.json":"9715fd2243b6f06a5858b5e32950d2853f73dd5bc201aafcf76f5082a2d8acd1","tokenizer_config.json":"2a4c4281cf9f51ac6ccc406fdc711a087afe6530f671fa7b80953edc498275ce","special_tokens_map.json":"e67ae3a0aaa99abcd9f187138e12db1f65c16a14761c50ef10eef2c174a7a691","config.json":"457854d452f17661e197d74aee12b8e74fb75ba30ebfaa7426d0d61ea1e08a18","tokenizer.json":"27fc476bfe7f17299480be2273fc0608e4d5a99aba2ab5dec5374b4482d1a566","generation_config.json":"f538b28220c6a6d6f1af1458d4141cacb4ef4963df3de98a19490440c412ddf0","normalizer.json":"bf1c507dc8724ca9cf9903640dacfb69dae2f00edee4f21ceba106a7392f26dd","merges.txt":"2df2990a395e35e8dfbc7511e08c12d56018d8d04691e0133e5d63b21e154dc6","vocab.json":"50d6a919f0a0601d56a04eb583c780d18553aa388254ba3158eb6a00f13e2c1a","quantize_config.json":"6e0e27f293a5c17ff2ca8046f06079c0120aa2ede6456faac8ec4b3203471a55","preprocessor_config.json":"a6a76d28c93edb273669eb9e0b0636a2bddbb1272c3261e47b7ca6dfdbac1b8d","onnx/encoder_model_quantized.onnx":"a43a83f3c5361cd591cfa7c36f14b43cf7cb22f47a415cc14a8d557be800fa92","onnx/decoder_model_merged_quantized.onnx":"ec07c3cbb64172c39791e26ee870a65ac22b458c36722bfe2776b3dbf741e0c9"})}),"onnx-community/whisper-tiny.en":Object.freeze({repo:"ChatPanel/whisper-tiny.en",revision:"04c2edaec92ca2ba876c3faa47a812cac2498e01",upstreamRevision:"794207fec2761281fe63a23a94b7e9f53a4efbc1",licence:"apache-2.0",files:Object.freeze({"added_tokens.json":"560be47bea388757f8d4cc185c5d82067426cbb6361e38016dd90ddc01ab203a","tokenizer_config.json":"93879c3dccdd4b976f709acd85b44778873f30c275e67026f30ca1e4c975230c","special_tokens_map.json":"98bdf3ec5b32e31575b02f64b0a32bde7c0449075d34484a7df9bdd3cdeb9fb9","config.json":"251ea843b5901a99efa58c0b99b8052c6019aa3e7d2baf46693a1128ff606233","tokenizer.json":"5eb60cec1e77aeeb6869a2bb5a8e01a84c3fe5d072d75369343021fe6f5310d0","generation_config.json":"7b2e8451ed5f118e75fdd991409d72119d21d2fef1eba9723f68fb9c57fe5dc9","normalizer.json":"bf1c507dc8724ca9cf9903640dacfb69dae2f00edee4f21ceba106a7392f26dd","merges.txt":"1ce1664773c50f3e0cc8842619a93edc4624525b728b188a9e0be33b7726adc5","vocab.json":"f6bd25a65e4e63ca31360e9fb11c7e4f9a391a78385d640acd814092dd6eee4f","quantize_config.json":"6e0e27f293a5c17ff2ca8046f06079c0120aa2ede6456faac8ec4b3203471a55","preprocessor_config.json":"a6a76d28c93edb273669eb9e0b0636a2bddbb1272c3261e47b7ca6dfdbac1b8d","onnx/encoder_model_quantized.onnx":"e93ec822f16a8fd264e7de972ad17d615ea7334b75a52d54c50c2e18dd503a25","onnx/decoder_model_merged_quantized.onnx":"c0592d0749413c960569e1c7fb806b060d5d18f3ebad4a95cbf9a77dc6e9be52"})}),"openai/privacy-filter":Object.freeze({repo:"ChatPanel/privacy-filter",revision:"d01aadcddb683ab4d951fa3d65bfd26fb4b5399c",upstreamRevision:"7ffa9a043d54d1be65afb281eddf0ffbe629385b",licence:"apache-2.0",files:Object.freeze({"tokenizer_config.json":"6c14af9ce1a284d3c3c5146b26efe4cd589c68e1dd4e9d94455606ec911ba774","config.json":"b2b26a4a4a000639ad30b0c264adbefe365bdb567fbd7bb27303b8c438375bd1","tokenizer.json":"0614fe83cadab421296e664e1f48f4261fa8fef6e03e63bb75c20f38e37d07d3","viterbi_calibration.json":"bbc8611ef08a55ed72d64856cbbbb9a91db8dfa881f0a92e2afbad6e4bbc775a","onnx/model_quantized.onnx_data":"50f4c8c7f3c27fbc1fe16d4f74f6f7c3b74ba8f18a262e8b6911854c64c33a6d","onnx/model_quantized.onnx":"a325fb5341567a73c94e91ec5e49060d38d9b16111f518ad34773039a0c9c098"})})});export{e as MODEL_COPIES};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{MODEL_COPIES as d}from"./model-copies.js";const $="https://huggingface.co/",g="https://dl.chatpanel.net/models/",y=/^https:\/\/(?:huggingface\.co|dl\.chatpanel\.net\/models)\/([^/]+\/[^/]+)\/resolve\/([^/]+)\/(.+)$/;function m(e){const r=y.exec(String(e||"").split("?")[0]);if(!r)return null;let t;try{t=decodeURIComponent(r[3])}catch{return null}return{id:r[1],rev:r[2],file:t}}const u=e=>e.split("/").map(encodeURIComponent).join("/");function w(e,{copies:r=d}={}){const t=m(e);if(!t)return[String(e)];const n=[],s=r[t.id];return s&&(!s.files||s.files[t.file])&&n.push(`${$}${s.repo}/resolve/${s.revision}/${u(t.file)}`),n.push(`${$}${t.id}/resolve/${t.rev}/${u(t.file)}`),n.push(`${g}${t.id}/resolve/${t.rev}/${u(t.file)}`),[...new Set(n)]}function M(e=globalThis.fetch,{copies:r=d}={}){return async function(n,s){const f=typeof n=="string"?n:n?.url??String(n),a=w(f,{copies:r});if(a.length===1)return e(a[0],s);const p=m(f),v=`${$}${p.id}/resolve/${p.rev}/${u(p.file)}`,S=c=>c.status>=500||c.status===429;let l=null,i=null;for(const c of a){const h=c===v,x=c.startsWith(g);try{const o=await e(c,s);if(o.ok||o.status===304||h&&!S(o))return o;if((h||!l&&!x)&&(l=o,i=null),o!==l)try{await o.body?.cancel?.()}catch{}}catch(o){(h||!l&&!i)&&(i=o)}}if(l)return l;throw i||new Error(`model file unavailable: ${f}`)}}function O(e,{copies:r=d}={}){return r[e]||null}export{$ as HF_HOST,g as MIRROR_HOST,O as modelCopy,M as modelFetch,m as parseModelUrl,w as sourceUrls};
|
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 ut,readdirSync as V,readFileSync as ft}from"node:fs";import{DEFAULT_MODEL as X,isMirroredModel as pt}from"./models.js";import{isLoopbackHost as dt,isPrivateHost as mt,isMetadataHost as ht}from"@chatpanel/pii";import{recaseForDetection as gt}from"@chatpanel/pii/pii-detect.js";import{recasedSpanOk as yt}from"@chatpanel/pii/recased-spans.js";import{verifyModelWeights as wt}from"./model-integrity.js";import{runtimeName as _t}from"./model-runtime.js";import{nativeOrtFailure as Mt}from"./ort.js";import{makeWarmTimer as Z}from"./warm-timer.js";import{makeModelFileCache as xt}from"./model-file-cache.js";import{onLane as bt}from"./inference-lane.js";const H="https://dl.chatpanel.net/models/";function Lt(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 H;const n=a=>(console.warn(`[models] ignoring ${e} (${r}): ${a} — using ${H}`),H);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(ht(o.hostname))return n("points at cloud metadata");const s=dt(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 ${H}`),r.replace(/\/*$/,"/"))}const Tt=Lt();let m="off",y=null,w=null,b=null,T=null,C=null,L=null,h=null,M=null,N=0,E=null;const g=new Map;let I=Promise.resolve();function ee({host:t=null,allowRemote:e=!1}={},r){const n=I.then(async()=>{const o=await z(),s=o.env.remoteHost,a=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=a}catch{}}});return I=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 ne(){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)&&At(S(t,r.name,n.name))&&e.push(o)}}catch{}return e}function At(t){try{return(JSON.parse(ft(S(t,"config.json"),"utf8")).architectures||[]).some(r=>/ForTokenClassification$/.test(String(r)))}catch{return!1}}function oe(){return m}function O(){return m==="ready"&&!!w}function re(){return{configured:m!=="off",ok:O(),state:m,model:y,error:b,runtime:_t(),dtype:w?"q8":null,stats:Rt(),companions:Ct(),warmMs:M?.warmMs??null}}async function St(t,{signal:e,strict:r=!1}={}){if(!O())return[];if(e?.aborted)return[];const n=String(t||""),o=await tt(n,e);if(!o)return[];const s=[];for(const f of o||[]){if(et(f,r))continue;let i=String(f.word??"");const u=f.entity_group??f.entity??"ENTITY";if(i.startsWith("##")&&s.length&&s[s.length-1].type===u){s[s.length-1].value+=i.slice(2);continue}i=i.replace(/##/g,"").trim(),i&&s.push({value:i,type:u})}const a=new Set,c=[];for(const f of s){const i=Dt(n,Ft(n,f.value.trim()));if(i.length<=1)continue;const u=`${f.type}:${i.toLowerCase()}`;a.has(u)||(a.add(u),c.push({value:i,type:f.type}))}return c}async function tt(t,e){N++;try{return await Ot(t,e)}finally{N--,$()||M?.arm()}}async function Ot(t,e){const r=performance.now(),n=[],o=[{text:t,key:"orig"}];if(F){const s=gt(t);s.changed&&o.push({text:s.text,key:"recased"})}for(const{model:s,pipe:a}of rt())for(const c of o){let f=0;for(const i of Ht(c.text,a.tokenizer)){if(e?.aborted)return null;const u=c.text.indexOf(i,f),d=await bt(()=>a(i,{aggregation_strategy:"simple"}));for(const l of d||[])n.push({...l,_win:u<0?f:u,_winText:i,_model:s,_pass:c.key,_passText:c.text});u>=0&&(f=Math.max(f,u+1))}}return Pt(performance.now()-r,t.length,n.length),n}let F=!0;function se(t){F=t!==!1}const et=(t,e)=>!e&&t._pass==="recased"&&!yt(String(t.word??"").replace(/##/g,""),t.entity_group??t.entity);async function ie(t,{signal:e,strict:r=!1}={}){if(!O())return[];const n=String(t||""),o=await tt(n,e);if(!o)return[];const s=[],a=new Set;let c=-1,f=-1,i=null,u=null;for(const l of o){if(et(l,r))continue;const p=String(l.word??"").replace(/##/g,"").trim();if(!p)continue;(l._win!==f||l._model!==i||l._pass!==u)&&(f=l._win,i=l._model,u=l._pass,c=l._win);const v=l._passText||n;let x=v.indexOf(p,c);if(x<0&&(x=v.indexOf(p,l._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(l.entity_group??l.entity??"ENTITY"),J=`${x}:${A}:${B}`;if(a.has(J))continue;a.add(J);const G=Number(l.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:l._model})}s.sort((l,p)=>l.start-p.start||l.end-p.end);const d=[];for(const l of s){const p=d[d.length-1];if(p&&p.type===l.type&&p.end===l.start){p.end=l.end,p.value=n.slice(p.start,p.end),p.score=Math.min(p.score,l.score);continue}d.push({...l})}return g.size||F?$t(d):d}const nt=["secret","ssn","card","iban","account","id","email","phone","address","person","org","loc"];function vt(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=nt.indexOf(vt(t.type));return e<0?nt.length:e}let k=[];function kt(t){k=Array.isArray(t)?t.slice():[],h&&(h={...h,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 $t(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 ae(){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 le(){const t=Number(w?.tokenizer?.model_max_length);return Number.isFinite(t)&&t>0&&t<=65536?t:null}function Ct(){return[...g].map(([t,e])=>({model:t,state:e.state,error:e.error||null}))}async function ot(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 it(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 ce(t){const e=g.get(t);if(!e)return!1;g.delete(t);try{await e.pipe?.dispose?.()}catch{}return!0}function rt(){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 Et=160,st=256;function Ht(t,e){if(!t||typeof e!="function")return[t];const r=Number(e.model_max_length),o=Math.min(st,Number.isFinite(r)&&r>0?r:st)-8,s=i=>{try{return e(i).input_ids.dims[1]}catch{return 1/0}};if(s(t)<=o)return[t];const a=[];let c=0,f=Math.max(64,Math.floor(o*3));for(;c<t.length;){let i=Math.min(t.length,c+f);if(i<t.length){const p=t.lastIndexOf(" ",i);p>c+f/2&&(i=p)}let u=t.slice(c,i);for(;s(u)>o&&u.length>32;){f=Math.max(32,Math.floor(u.length/2)),i=c+f;const p=t.lastIndexOf(" ",i);p>c+f/2&&(i=p),u=t.slice(c,i)}if(a.push(u),i>=t.length)break;const d=Math.max(c+1,i-Et),l=t.indexOf(" ",d);c=l>0&&l<i?l+1:i}return a}const Nt=200,_=[];function Pt(t,e,r){_.push({ms:t,chars:e,spans:r}),_.length>Nt&&_.shift()}function Rt(){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 Ft(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 Dt(t,e){if(!e)return e;const r=t.indexOf(e);if(r<0)return e;const n=a=>!!a&&/[\p{L}\p{N}'’-]/u.test(a);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 ue(t,e={}){let r="",n=!1;try{const s=JSON.parse(e.body||"{}");r=s.text||"",n=s.strict===!0}catch{}const o=await St(r,{signal:e.signal,strict:n});return new Response(JSON.stringify({entities:o}),{status:200,headers:{"content-type":"application/json"}})}function fe(){return L}async function z(){if(C)return C;const t=P();try{ut(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(l){throw e?l:new Error(Mt(l))}const{env:n,pipeline:o,Tensor:s,AutoModel:a,AutoProcessor:c,AutoTokenizer:f,AutoModelForSequenceClassification:i,LogLevel:u}=r;if(n.cacheDir=t,e&&u)try{n.logLevel=u.ERROR}catch{}n.localModelPath=t,e||(n.useCustomCache=!0,n.customCache=xt(t,{remoteHost:()=>n.remoteHost}));try{n.remoteHost=Tt}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 C={env:n,pipeline:(l,p,v={})=>o(l,p,v.progress_callback&&n.allowRemoteModels===!1?{...v,progress_callback:void 0}:v),Tensor:s,AutoModel:a,AutoProcessor:c,AutoTokenizer:f,AutoModelForSequenceClassification:i,AutoModelForAudioFrameClassification:r.AutoModelForAudioFrameClassification},C}function Wt({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 it(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 a=o.env.remoteHost,c=!pt(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:Wt()};let u;try{u=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,u=await o.pipeline("token-classification",t,i)}if(!s)try{wt(t,{modelsDir:P(),log:e})}catch(d){try{await u.dispose?.()}catch{}throw d}return{pipe:u,haveLocal:s}}finally{try{o.env.remoteHost=a}catch{}}}async function at(t,{log:e=()=>{},allowDownload:r=!0}={}){const n=w,o=y;try{await z()}catch(a){return m="error",b=`engine load failed: ${a.message}`,e(`[ner] transformers.js not available (${a.message}) — deterministic-only`),!1}const s=R(t);if(!s&&!r)return m="error",b="model not on disk and downloads disabled",e(`[ner] model ${t} not installed and downloads disabled — deterministic-only`),!1;m=s?"loading":"downloading",s||(L={model:t,file:null,pct:0});try{const{pipe:a}=await it(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=a,y=t,m="ready",b=null,L=null,h&&(h={...h,model:t}),n&&n!==a)try{await n.dispose?.()}catch{}return e(`[ner] ready — model ${t} (in-process, no Python) — entity detection active`),$()||M?.arm(),!0}catch(a){return b=a.message,L=null,n?(w=n,y=o,m="ready"):m="error",e(`[ner] model load failed (${a.message})${n?" — keeping previous model":" — deterministic-only"}`),!1}}function Ut(t={}){if(T)return T;const e=typeof t.onLog=="function"?t.onLog:()=>{};h=t,y=t.model||X,m="loading";const r=t.allowDownload!==!1;return M=Z({warmMs:t.warmMs,busy:$,log:e,unload:()=>lt({log:e})}),T=at(y,{log:e,allowDownload:r}).then(async n=>{const o=Array.isArray(t.union)?t.union:[];kt(o);for(const s of o)await ot(s,{log:e,allowDownload:r});return O()&&!$()&&M?.arm(),n}),T}function $(){if(N>0||m==="loading"||m==="downloading")return!0;for(const t of g.values())if(t.state==="loading"||t.state==="downloading")return!0;return!1}async function lt({log:t=()=>{}}={}){if($())return!1;M?.disarm();const e=rt().map(r=>r.pipe);w=null,T=null,L=null,b=null,g.clear(),m=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 jt(){try{m==="idle"&&(E||h)?await(E?E():Ut(h)):T&&await T,O()&&await ct()}catch{}return O()}let U=null;function ct(){const t=k.filter(e=>e&&e!==y&&!g.has(e));return t.length?(U||=(async()=>{const e=typeof h?.onLog=="function"?h.onLog:()=>{};for(const r of t)g.has(r)||(j?await j(r):await ot(r,{log:e,allowDownload:h?.allowDownload!==!1}))})().catch(()=>{}).finally(()=>{U=null}),U):Promise.resolve()}let j=null;function pe(t){j=t}async function de(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&&m==="idle")return jt();const o=g.get(t);if(o?.pipe){const a=w;if(w=o.pipe,y=t,m="ready",b=null,g.delete(t),a)try{await a.dispose?.()}catch{}return r(`[ner] ${t} promoted from the union to primary`),h&&(h={...h,model:t}),!0}const s=await at(t,{log:r,allowDownload:n});return s&&(h&&(h={...h,model:t}),await ct()),s}function me(){m="off",y=null,w=null,b=null,T=null,C=null,L=null,_.length=0,g.clear(),F=!0,k=[],M?.disarm(),M=null,h=null,N=0,E=null,j=null,U=null}function he(t,e){g.set(t,{pipe:e,state:"ready",error:null})}function ge(t,{model:e="test/model",warmMs:r=null,reload:n=null}={}){w=t,y=e,m="ready",b=null,_.length=0,n&&(E=n),r!==null&&(M=Z({warmMs:r,busy:$,unload:()=>lt()}),t&&M.arm())}export{me as _reset,he as _setCompanionForTest,pe as _setCompanionLoaderForTest,ge as _setForTest,ot as addCompanion,Ct as companions,St as detect,ie as detectSpans,jt as ensure,z as ensureLib,ue as fetchAdapter,re as health,Ut as init,O as isReady,ae as labels,le as maxTokens,R as modelOnDisk,P as modelRoot,ne as modelsOnDisk,fe as progress,ce as removeCompanion,Lt as resolveModelHost,Wt as sessionOptionsFor,se as setCaseRecovery,de as setModel,kt as setUnionOrder,oe as state,Rt as stats,$t as unionSpans,lt as unload,Ht as windowsFor,ee as withModelSource};
|
|
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};
|
package/src/parakeet-engine.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{join as i}from"node:path";import{existsSync as $,mkdirSync as
|
|
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
|
|
1
|
+
import{modelFetch as tt}from"./model-sources.js";import{join as i}from"node:path";import{existsSync as $,mkdirSync as et,readFileSync as nt,createWriteStream as ot,renameSync as rt,statSync as C}from"node:fs";import{Readable as st}from"node:stream";import{modelRoot as at}from"./ner-engine.js";import{getOrt as ct,ortProviders as it}from"./ort.js";const lt=new Set(["nemo-conformer-tdt","nemo-conformer-rnnt","parakeet_tdt","parakeet-tdt","parakeet_rnnt"]);function bt(t){return lt.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(at(),...String(t).split("/"))}function ft(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 dt(t,e,n,{onProgress:s,log:o}={}){const r=`https://huggingface.co/${t}/resolve/main/${encodeURIComponent(e).replace(/%2F/g,"/")}`,a=await tt()(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=ot(l);let h=0,u=-1;const p=st.fromWeb(a.body);p.on("data",m=>{if(h+=m.length,w){const c=Math.round(h/w*100);c!==u&&(u=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)}),rt(l,i(n,e)),o?.(`[parakeet] fetched ${e}`)}async function ut(t,e,{onProgress:n,log:s}={}){const o=E(t);et(o,{recursive:!0});for(const r of V(e)){const a=i(o,r);$(a)&&C(a).size>0||(s?.(`[parakeet] downloading ${r}…`),await dt(t,r,o,{onProgress:n,log:s}))}return o}function pt(t){const e=[];let n=-1;for(const s of nt(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 mt=5,H=10;async function kt({modelId:t,dtype:e=D,allowDownload:n=!0,onProgress:s,log:o=()=>{},sessionOptions:r=null}){const a=Y(e),w=ft(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 ct(),h=a==="fp32"?"":".int8",u={executionProviders:it(),graphOptimizationLevel:"all",logSeverityLevel:3,...r||{}},[p,m,c]=await Promise.all([f.InferenceSession.create(i(l,"nemo128.onnx"),u),f.InferenceSession.create(i(l,`encoder-model${h}.onnx`),u),f.InferenceSession.create(i(l,`decoder_joint-model${h}.onnx`),u)]),{vocab:K,blank:_}=pt(l),x=_+1,d=f.Tensor;async function X(g){if(!(g instanceof Float32Array)||g.length<400)return"";const I=g.length,P=await p.run({waveforms:new d("float32",g,[1,I]),waveforms_lens:new d("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 d("float32",z,[1,A,1]),targets:new d("int32",Int32Array.from([Z]),[1,1]),target_length:new d("int32",Int32Array.from([1]),[1]),input_states_1:new d("float32",M,[2,1,640]),input_states_2:new d("float32",N,[2,1,640])}),U=T.outputs.data,F=W(U,0,x),j=W(U,x,x+mt)-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,bt as isTransducerModelType,kt as loadRecognizer,E as parakeetDir,Y as parakeetDtype,ft as parakeetOnDisk};
|
package/src/stt-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join as Qe}from"node:path";import{deflateSync as Je}from"node:zlib";import ve from"node:os";import{existsSync as Ze,readdirSync as et}from"node:fs";import{randomUUID as tt}from"node:crypto";import{ensureLib as Ne,modelRoot as Oe}from"./ner-engine.js";import{runtimeDtype as ie,runtimeName as Pe,DTYPE_SUFFIX as nt}from"./model-runtime.js";import{verifyModelWeights as ot}from"./model-integrity.js";import{DEFAULT_STT_MODEL as Re,isEnglishOnly as me,sttModelDtype as he,isKnownSttModel as rt,sttModelEngine as z}from"./stt-models.js";import*as B from"./parakeet-engine.js";import*as _e from"./coreml-stt-engine.js";import*as ne from"./indic-engine.js";import*as U from"./diarize-engine.js";import*as Y from"./segment-engine.js";import{turnsFromSpans as lt,mainLocal as at,timeByLocal as st,audioOfLocal as it}from"@chatpanel/events/speaker-turns.js";import{diarizeApproxMB as ct}from"./diarize-models.js";import*as oe from"./translate-engine.js";import*as Z from"./indictrans-engine.js";import{rawOrtAvailable as ut}from"./ort.js";import*as R from"./vad-engine.js";import*as ee from"./echo-pair.js";import{mostlyEcho as ft}from"./aec-engine.js";import{pickSegmentLanguage as dt,detectTextLanguage as gt,needsTranslation as pt,localTranslatable as mt,normalizeLanguages as ht,normalizeLanguage as _t,decodeLanguages as wt,lineLanguage as yt,autoCandidates as Mt,AUTO_LEARN_CONFIDENCE as Tt,AUTO_LEARN_SECONDS as St,ANY_LANGUAGE_CONFIDENCE as Et,AUTO_LANGUAGES as Lt}from"@chatpanel/events/speech-language.js";import{makeWarmTimer as we}from"./warm-timer.js";const p=16e3,Fe=p,Ce=3*p,At=2,xt=new Set(["thank you","thanks","thank you for watching","thanks for watching","you","uh","um","hmm","hm","mm","amen","bye","okay","ok","yeah","oh","the","that","so","and","i","a","me","we","yes","no","thank you very much","subtitles by the amara.org community","you you"]);function bt(e,t){if(t>At*p)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?xt.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}const kt=12,ye=3;function Dt(e){const t=String(e||"").split(/\s+/).filter(Boolean);if(t.length<ye)return{text:String(e||"").trim(),removed:0,total:t.length};const n=l=>l.toLowerCase().replace(/[^\p{L}\p{N}']/gu,""),o=[];let r=0;for(let l=0;l<t.length;){let i=0,s=0;for(let a=1;a<=kt&&l+a*ye<=t.length;a++){let c=1;for(;l+(c+1)*a<=t.length&&t.slice(l+c*a,l+(c+1)*a).every((u,g)=>n(u)===n(t[l+g]));)c++;c>=ye&&(c-1)*a>i&&(i=(c-1)*a,s=a)}i?(o.push(...t.slice(l,l+s)),r+=i,l+=s+i):(o.push(t[l]),l++)}return{text:o.join(" "),removed:r,total:t.length}}const vt=.6,$e=2.4;function He(e){const t=Buffer.from(String(e||""),"utf8");return t.length<40?1:t.length/Je(t).length}function Nt(e){return String(e||"").replace(/([^\d\s]{1,8}?)\1{4,}/gu,"$1")}function Ot({cores:e=ve.availableParallelism?.()??ve.cpus().length,env:t=process.env}={}){const n=Number(t.CHATPANEL_STT_THREADS);return Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(4,Math.floor(e/2)))}function re(e){return{intraOpNumThreads:Ot(e),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}const Pt=.12,ze=.8,Ue=.15,Rt=.999,Ft=2.5;function ce(e={}){return(e.en??0)>=Ue?"en":Object.entries(e).sort((t,n)=>n[1]-t[1])[0]?.[0]||null}function Ct(e,t=[]){const n=[];return e.forEach((o,r)=>{const l=t[r]??o.lang,i=n[n.length-1];i&&i.lang===l?i.to=o.to:n.push({from:o.from,to:o.to,lang:l})}),n}function $t(e,{base:t=null,rate:n=p}={}){const o=e||[],r=a=>{const[c,u]=Object.entries(a.scores||{}).sort((g,A)=>A[1]-g[1])[0]||[];return c&&c!=="en"&&u>=Rt?c:null},l=new Array(o.length).fill(null);for(let a=0;a<o.length;){const c=r(o[a]);let u=a+1;if(c)for(;u<o.length&&r(o[u])===c;)u++;if(c&&(o[u-1].to-o[a].from)/n>=Ft)for(let g=a;g<u;g++)l[g]=c;a=u}const i=[];let s=t;return o.forEach((a,c)=>{l[c]?s=l[c]:s!=="en"&&(a.scores?.en??0)>=Ue&&(s="en");const u=i[i.length-1];u&&u.lang===s?u.to=a.to:i.push({from:a.from,to:a.to,lang:s})}),i}function Ht(e,t,{frame:n=Math.round(.03*p),minPause:o=Pt*p,minPiece:r=ze*p}={}){const l=[];let i=0,s=-1;for(let a=0;a+n<=e;a+=n){const c=t(a,a+n)===!1;if(c&&s<0&&(s=a),(!c||a+2*n>e)&&s>=0){const u=c?a+n:a,g=Math.round((s+u)/2);u-s>=o&&g-i>=r&&e-g>=r&&(l.push(g),i=g),s=-1}}return l}const zt=.12;function Ut(e,t=Math.round(.03*p)){const n=Math.floor(e.length/t);if(n<3)return 0;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=Q(e,r*t,(r+1)*t);return o.sort(),Math.max(1e-4,o[Math.floor(n*.9)]*zt)}let m="off",E=null,h=null,D=null,q=null,T=null,X=null,N=null;function Gt(e=E||Re,t=he(e)||ie()){if(z(e)==="parakeet-tdt")return B.parakeetOnDisk(e,B.parakeetDtype(t));if(z(e)==="coreml-tdt")return _e.coremlOnDisk(e);if(z(e)==="indic-canary")return ne.indicOnDisk();const n=Qe(Oe(),...e.split("/"),"onnx");if(!Ze(n))return!1;const o=nt[t]??"";try{const r=et(n);return r.includes(`encoder_model${o}.onnx`)&&r.some(l=>l===`decoder_model_merged${o}.onnx`||l===`decoder_model${o}.onnx`)}catch{return!1}}function An(){return m}function ue(){return m==="ready"&&!!h}function xn(){return T}function bn(){return{configured:m!=="off",ok:ue(),state:m,model:E,dtype:X,runtime:Pe(),error:D,warmMs:N?.warmMs??null,vad:R.state()}}function kn(){return!!N?.pending()}function le(){return C.size>0||m==="loading"||m==="downloading"}async function Me({log:e=()=>{}}={}){if(le())return!1;N?.disarm();const t=h;if(h=null,q=null,X=null,T=null,D=null,m="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((N?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function Ge(e){return e.then(t=>(t&&!le()&&N?.arm(),t))}async function je(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null,licenseAccepted:r=null}={}){if(z(e)==="parakeet-tdt")return jt(e,{log:t,allowDownload:n,dtype:o});if(z(e)==="coreml-tdt")return Xt(e,{log:t,allowDownload:n});if(z(e)==="indic-canary")return Kt(e,{log:t,allowDownload:n,licenseAccepted:r});const l=h,i=E;let s;try{s=await Ne()}catch(L){return m="error",D=`engine load failed: ${L.message}`,t(`[stt] transformers.js not available (${L.message}) — dictation falls back to the browser engine`),!1}const c=(o&&o!=="auto"?o:null)||he(e)||ie(),u=Gt(e,c);if(s.env.allowRemoteModels=u?!1:!!n,!u&&!n)return m="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const g=s.env.remoteHost,A=!rt(e);if(!u&&A)try{s.env.remoteHost="https://huggingface.co/"}catch{}m=u?"loading":"downloading",u||(T={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${A?", from Hugging Face":""})…`));try{const L=d=>{if(!d)return;const J=typeof d.progress=="number"?Math.round(d.progress):T?.pct??0;d.status==="progress"||d.status==="download"||d.status==="initiate"?T={model:e,file:d.file||T?.file||null,pct:J}:d.status==="done"&&d.file&&t(`[stt] fetched ${d.file}`)};let w;try{w=await s.pipeline("automatic-speech-recognition",e,{dtype:c,progress_callback:L,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:re()}})}catch(d){if(u||A||!n)throw d;t(`[stt] mirror fetch failed (${String(d.message).slice(0,80)}) — retrying from Hugging Face…`),s.env.remoteHost="https://huggingface.co/",s.env.allowRemoteModels=!0,w=await s.pipeline("automatic-speech-recognition",e,{dtype:c,progress_callback:L,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:re()}})}if(!u)try{ot(e,{modelsDir:Oe(),log:t})}catch(d){try{await w.dispose?.()}catch{}throw d}if(h=w,E=e,m="ready",D=null,T=null,X=c,l&&l!==w)try{await l.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${c} (in-process, offline) — local dictation active`),!0}catch(L){return D=L.message,T=null,l?(h=l,E=i,m="ready"):m="error",t(`[stt] model load failed (${L.message})${l?" — keeping previous model":""}`),!1}finally{try{s.env.remoteHost=g}catch{}}}async function jt(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null}={}){const r=h,l=E,i=B.parakeetDtype(o&&o!=="auto"?o:Bt()),s=B.parakeetOnDisk(e,i);if(!s&&!n)return m="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;m=s?"loading":"downloading",s||(T={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const a=await B.loadRecognizer({modelId:e,dtype:i,allowDownload:n,log:t,sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:re(),onProgress:u=>{T={model:e,file:u.file||null,pct:typeof u.pct=="number"?u.pct:T?.pct??0}}}),c=async u=>({text:await a.transcribe(u)});if(c.__transducer=!0,c.dispose=()=>a.dispose(),h=c,E=e,m="ready",D=null,T=null,X=i,r&&r!==c)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(a){return D=a.message,T=null,r?(h=r,E=l,m="ready"):m="error",t(`[stt] model load failed (${a.message})${r?" — keeping previous model":""}`),!1}}function Bt(){return B.PARAKEET_DEFAULT_DTYPE}const Be="fp16";async function Xt(e,{log:t=()=>{},allowDownload:n=!0}={}){const o=h,r=E,l=_e.coremlOnDisk(e);if(!l&&!n)return m="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;m=l?"loading":"downloading",l||(T={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let i=null;const s=await _e.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:a=>{T={model:e,file:a.file||null,pct:typeof a.pct=="number"?a.pct:T?.pct??0}},onExit:a=>{h===i&&(h=null,q=null,m="error",D=a,N?.disarm(),t(`[stt] ${a} — reloads on the next dictation`))}});if(i=async a=>({text:await s.transcribe(a)}),i.__transducer=!0,i.dispose=()=>s.dispose(),h=i,E=e,m="ready",D=null,T=null,X=Be,o&&o!==i)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} (Core ML on the Neural Engine, helper ${s.version}, windows ${s.windows.join("/")} s, offline) — local dictation active`),!0}catch(i){return D=i.message,T=null,o?(h=o,E=r,m="ready"):m="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}async function Kt(e,{log:t=()=>{},allowDownload:n=!0,licenseAccepted:o=null}={}){const r=h,l=E,i=ne.indicOnDisk();if(!i&&!n)return m="error",D="model not on disk and downloads disabled",!1;m=i?"loading":"downloading",i||(T={model:e,file:null,pct:0},t(`[stt] downloading ${e} (one-time, ~1.5 GB, from dl.chatpanel.net)…`));try{i||await ne.ensureIndicFiles({licenseAccepted:o,log:t,onProgress:c=>{T={model:e,file:c.file,pct:c.pct}}});const s=await ne.loadRecognizer({sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:re(),log:t}),a=async(c,u={})=>s.transcribe(c,u);if(a.identify=(c,u)=>s.identify(c,u),a.__transducer=!0,a.__indic=!0,a.dispose=()=>s.dispose(),h=a,E=e,m="ready",D=null,T=null,X="int8",r&&r!==a)try{await r.dispose?.()}catch{}return t(`[stt] ready — ${e} (Indic-Transcribe, int8, in-process, offline) — ${ne.INDIC_LICENSE.attribution}`),!0}catch(s){return D=s.message,T=null,r?(h=r,E=l,m="ready"):m="error",t(`[stt] model load failed (${s.message})${r?" — keeping previous model":""}`),!1}}const Wt=30;function Xe({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:o=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof o=="number"&&o<=Wt||e==="download"?{allowDownload:!0}:null}function Te(e,{log:t=()=>{},warmMs:n,allowDownload:o=!0}={}){const r=Xe({mode:e,onDisk:U.modelOnDisk(),ready:U.isReady(),approxMB:ct(U.activeModel())});if(r&&U.init({allowDownload:r.allowDownload&&o!==!1,warmMs:n,onLog:t}),e==="off"||Se)return;const l=Xe({mode:e,onDisk:Y.modelOnDisk(),ready:Y.isReady(),approxMB:Y.SEGMENT_MODEL_APPROX_MB});l&&Y.init({allowDownload:l.allowDownload&&o!==!1,warmMs:n,onLog:t})}let Se=!1,Ee=null;function Le(e={},{log:t=()=>{}}={}){e.vad!==!1&&(Ee={vad:e.vad,allowDownload:e.allowDownload,warmMs:e.warmMs},(R.state()==="off"||R.state()==="error")&&R.init({allowDownload:e.allowDownload!==!1,warmMs:e.warmMs,onLog:t}))}function Dn(e={}){if(q&&m!=="error")return q;const t=typeof e.onLog=="function"?e.onLog:()=>{};return E=e.model||Re,Se=e.segment===!1,m="loading",N=we({warmMs:e.warmMs,busy:le,log:t,unload:()=>Me({log:t})}),q=Ge(je(E,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype,licenseAccepted:e.licenseAccepted||null})).then(n=>(n&&(Te(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),Le(e,{log:t})),n)),q}async function vn(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(Se=t.segment===!1);const o=z(e)==="parakeet-tdt"?B.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:B.PARAKEET_DEFAULT_DTYPE):z(e)==="coreml-tdt"?Be:z(e)==="indic-canary"?"int8":t.dtype&&t.dtype!=="auto"?t.dtype:he(e)||ie();if(e===E&&ue()&&X===o)return Te(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;N??=we({warmMs:t.warmMs,busy:le,log:n,unload:()=>Me({log:n})});const r=await Ge(je(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype,licenseAccepted:t.licenseAccepted||null}));return r&&(Te(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),Le(t,{log:n})),r}const Yt=8,qt=12e4,It=6e4,Vt=1200,fe=12,Ae=700,xe=.008,Qt=.002,Jt=4;function Zt(e){return e>0?Math.min(xe,Math.max(Qt,e*Jt)):xe}function en(e){const t=Math.round(.1*p),n=Math.floor(e.length/t);if(n<5)return null;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=Q(e,r*t,(r+1)*t);return o.sort(),o[Math.floor(n*.1)]}const Ke=30,tn=15e3,C=new Map,I=new Map;let V=Promise.resolve();function Nn(){return C.size}const nn=300,on=3e3;function rn(e){const t=Number(e);return Number.isFinite(t)?Math.min(on,Math.max(nn,Math.round(t))):Ae}function On({lang:e,langs:t=null,translateTo:n=null,translateLoad:o=null,echo:r=null,redact:l=!1,diarize:i=!1,speakerLabel:s=null,endSilenceMs:a=Ae,interims:c=!0,remote:u=null,poll:g=!1}={}){if(C.size>=Yt){const d=new Error("too many concurrent dictation sessions");throw d.code="too_many_sessions",d}const A=Array.isArray(t)?ht(t):null,L=typeof e=="string"&&e?e.slice(0,12):null,w={id:tt(),endSilenceMs:rn(a),lang:A?A.length===1?A[0]:A.length?null:L:L,langs:A,lastLang:null,lastDecoded:null,learned:new Set,translateTo:_t(n)||null,translateLoad:o||{},translations:Promise.resolve(),echo:r&&typeof r=="object"?ee.join(r.group,r.role):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!l,diarize:!!i,speakerLabel:typeof s=="string"&&s?s.slice(0,40):null,diarizer:i?new U.Diarizer:null,remote:u||null,interims:c!==!1&&!u,chunks:[],samples:0,listeners:new Set,poll:g?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return C.set(w.id,w),N?.disarm(),w.diarizer&&(U.retain(),Y.retain()),w.translateTo&&(oe.retain(),Z.retain()),R.retain(),Ee&&(R.state()==="off"||R.state()==="error")&&Le(Ee),We(w),{id:w.id}}function de(e){return C.get(String(e||""))||null}function Pn(e,t){const n=de(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function K(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function Rn(e){const t=String(e||""),n=C.get(t);if(n)return n.poll?n.poll.splice(0):null;const o=I.get(t);return o?(clearTimeout(o.timer),I.delete(t),o.session.poll.splice(0)):null}function Fn(e){return I.get(String(e||""))?.session||null}function We(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>cn(e.id).catch(()=>{}),It),e.idleTimer.unref?.()}function Cn(e,t){const n=de(e);if(!n||n.closed){const o=new Error("no such session");throw o.code="no_session",o}if(!(!(t instanceof Float32Array)||!t.length)){if(We(n),n.echo?.role==="mic"){ee.pushMic(n.echo,t),Ye(n);return}n.echo?.role==="reference"&&ee.pushReference(n.echo,t),n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,Ye(n)}}function $n(e){const t=de(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),V=V.then(()=>be(t).catch(()=>{})),V)}function Hn(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let o=0;o<n.length;o++)n[o]=e.readFloatLE(o*4);return n}function Ye(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+Vt-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,V=V.then(()=>be(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function qe(e){const t=new Float32Array(e.samples);let n=0;for(const o of e.chunks)t.set(o,n),n+=o.length;return t}function ln(e,t,n){const o=p/100,r=Math.max(0,e.length-t),l=Math.floor((e.length-r)/o),i=Math.max(1,Math.round(n/o));if(l<=i)return 0;const s=new Float32Array(l);for(let g=0;g<l;g++){let A=0;const L=r+g*o;for(let w=0;w<o;w++)A+=e[L+w]*e[L+w];s[g]=A/o}let a=-1,c=1/0,u=0;for(let g=0;g<i;g++)u+=s[g];for(let g=0;g+i<=l;g++)g>0&&(u+=s[g+i-1]-s[g-1]),u<c&&(c=u,a=g);return a<0?0:r+Math.round((a+i/2)*o)}function Q(e,t=0,n=e.length){let o=0;const r=Math.max(1,n-t);for(let l=t;l<n;l++)o+=e[l]*e[l];return Math.sqrt(o/r)}function an(e,t=xe){const n=Math.round(.02*p);let o=0,r=e.length;for(let l=0;l+n<=e.length;l+=n)if(Q(e,l,l+n)>=t){o=l;break}for(let l=e.length-n;l>=0;l-=n)if(Q(e,l,l+n)>=t){r=l+n;break}return r>o?e.subarray(o,r):e}async function Ie(e){try{const t=await Ne(),n=h?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const o=e.length>p*8?e.subarray(0,p*8):e,r=await h.processor(o),l=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),i=await h.model({...r,decoder_input_ids:l}),s={};for(const[a,c]of Object.entries(n.lang_to_id))s[a.slice(2,-2)]=Number(i.logits.data[c]);return s}catch{return null}}async function sn(e){const t=await Ie(e);if(!t)return null;let n=null,o=-1/0;for(const[r,l]of Object.entries(t))l>o&&(o=l,n=r);return n}async function be(e,{flush:t=!1}={}){if(e.closed&&!t)return;if(e.echo?.role==="mic"){const f=await ee.drain(e.echo,{force:t});f.length&&(e.chunks.push(f),e.samples+=f.length,e.pushed+=f.length)}if(!e.remote&&!ue()||!e.samples)return;e.lastDecodeAt=Date.now();let n=qe(e);const o=n.length,r=Math.max(0,(e.pushed||0)-e.samples),l=Math.round((e.endSilenceMs||Ae)/1e3*p),i=en(n);i!==null&&(e.noiseFloor==null||i<e.noiseFloor)&&(e.noiseFloor=i);const s=Zt(e.noiseFloor);let a=null,c=null;R.isReady()&&(e.vad||=R.createStream(),await e.vad.advance(n,r)&&(a=e.vad.speechIn(r,r+n.length,R.ONSET),n.length>l&&(c=e.vad.speechIn(r+n.length-l,r+n.length,R.OFFSET))));const u=n.length>l&&(c!==null?!c:Q(n,n.length-l)<s);if(a===!1||a===null&&Q(n)<s){n.length>p*5&&(e.chunks=[n.subarray(n.length-p)],e.samples=p);return}if(!e.interims&&!t&&!u&&n.length<fe*p)return;let g=null;if(!t&&!u&&o>=fe*p&&o<Ke*p){const f=ln(n,3*p,Math.round(.2*p));f>0&&f<n.length&&(g=n.subarray(f),n=n.subarray(0,f))}const A=!e.remote&&!me(E)&&!h?.__transducer;if(A&&!e.langs&&!e.lang&&!e.langTried&&n.length>=p){e.langTried=!0;const f=await sn(n);f&&(e.lang=f,K(e,{type:"language",lang:f}))}const L=t||u||o>=fe*p;let w=e.lang;if(A&&e.langs&&!e.lang){const f=e.langs.length>0,O=f?wt(e.langs):Mt([...e.learned]);if(O.length===1)w=O[0];else if(w=O.includes(e.lastDecoded)?e.lastDecoded:null,(L||!w)&&n.length>=p/2){const b=await Ie(n);if(b){const M=dt({scores:b,allowed:O,seconds:n.length/p,last:e.lastDecoded});w=!f&&!M.inherited&&M.confidence<Et?e.lastDecoded||"en":M.lang,!f&&L&&!M.inherited&&M.confidence>=Tt&&n.length>=St*p&&e.learned.add(M.lang)}}L&&w&&(e.lastDecoded=w)}let d="",J=null,$=null,ge=null;try{if(e.remote){const f=await e.remote.transcribe(n,{lang:e.lang,langs:e.langs});d=f.text,ge=f.lang||null}else{const f=h.__indic?e.langs?.length?{langs:[...new Set([...e.langs,"en"])],last:e.lastLang,choose:ce}:e.lang?{lang:e.lang}:{langs:[...Lt],last:e.lastLang,choose:ce}:me(E)?{}:{language:w||void 0,task:"transcribe"},O=h.__indic&&h.identify&&L&&f.langs&&n.length>=2*ze*p?Ht(n.length,(M=>(_,v)=>Q(n,_,v)>=M)(Ut(n))):[];let b=null;if(O.length){const M=await h.identify(n,{langs:f.langs}),_=[0,...O,n.length],v=[];for(let k=0;k+1<_.length;k++){const S=await h.identify(n.subarray(_[k],_[k+1]),{langs:f.langs});v.push({from:_[k],to:_[k+1],scores:S?.scores||{}})}if(b=$t(v,{base:M?.scores?ce(M.scores):null}),b.length>1){const k=[];for(let S=0;S<b.length;S++){const G=b[S],te=G.lang&&G.lang!=="en"&&(b[S-1]?.lang==="en"||b[S+1]?.lang==="en");k.push(te?ce((await h.identify(n.subarray(G.from,G.to),{langs:f.langs}))?.scores||{}):G.lang)}b=Ct(b,k)}b.length<2&&(b=null)}if(b){$=[];for(const _ of b){const v=await h(n.subarray(_.from,_.to),_.lang?{lang:_.lang}:{...f}),k=String(v?.text||"").trim(),S=v?.lang||_.lang||null;k&&$.push({text:k,lang:S,from:_.from,to:_.to}),S&&(f.last=S)}d=$.map(_=>_.text).join(" ");const M=new Map;for(const _ of $)_.lang&&M.set(_.lang,(M.get(_.lang)||0)+(_.to-_.from));J=[...M].sort((_,v)=>v[1]-_[1])[0]?.[0]||null,($.length<2||M.size<2)&&($=null)}else{const M=await h(n,f);d=String(M?.text||"").trim(),h.__indic&&(J=M?.lang||null)}}}catch(f){K(e,{type:"error",code:"decode_failed",message:f.message,fatal:!1});return}if(!d)return;{const f=Dt(d);if(f.removed&&f.removed/f.total>=vt&&f.total>=12?d="":d=f.text,d&&He(d)>$e){const O=Nt(d);d=O.replace(/[\s\p{P}]/gu,"").length<12||He(O)>$e?"":O}if(!d)return}const Ve=o>=fe*p,ke=o>=Ke*p;if(t||u||Ve||ke){const f=t?"flush":u?"silence":ke?"overflow":"length",O=f==="flush"||f==="silence",b=e.samples-o,M=[];g&&M.push(g),b>0&&M.push(qe(e).subarray(o)),e.chunks=M,e.samples=M.reduce((y,x)=>y+x.length,0),e.lastInterim="";const _=an(n,s);if(bt(d,_?_.length:0)||e.echo?.role==="mic"&&ft(ee.verdict(e.echo,r,r+n.length)))return;let v=null,k=null;if(e.diarizer)try{const y=e.speakerLabel?null:await Y.spans(n),x=y?lt(y):[];if(x.length){const P=new Map;for(const{local:F}of st(x)){const H=it(n,x,F),ae=H.length?await U.embed(H):null,se=H.length<Fe,W=H.length<Ce;P.set(F,e.diarizer.assign(ae,{pinnedLabel:null,weak:se,thin:W}))}const j=Math.round(r/p*1e3);k=x.map(F=>({startMs:j+Math.round(F.start*1e3),durationMs:Math.round((F.end-F.start)*1e3),speaker:P.get(F.local)})).filter(F=>F.speaker),v=P.get(at(x))||null}}catch{}if(e.diarizer&&!v)try{const y=_,x=y?await U.embed(y):null,P=!!y&&y.length<Fe,j=!!y&&y.length<Ce;v=e.diarizer.assign(x,{pinnedLabel:e.speakerLabel,weak:P,thin:j})}catch{}let S=null;(e.langs||e.translateTo)&&(J?S=J:ge?S=ge:me(E)&&!e.remote?S="en":A?S=yt(d,w||e.lang)||null:S=e.lang||gt(d,{allowed:e.langs||[],last:e.lastLang}).lang,S&&S!==e.lastLang&&(e.lastLang=S,K(e,{type:"language",lang:S})));const G=Math.round(r/p*1e3),te=$&&(e.langs||e.translateTo)?$.map((y,x)=>({text:y.text,lang:y.lang,startMs:G+Math.round(y.from/p*1e3),durationMs:Math.round((y.to-y.from)/p*1e3),last:x===$.length-1})):[{text:d,lang:S,startMs:G,durationMs:Math.round(n.length/p*1e3),last:!0}];for(const y of te){te.length>1&&y.lang&&y.lang!==e.lastLang&&(e.lastLang=y.lang,K(e,{type:"language",lang:y.lang}));const{text:x,lang:P,startMs:j}=y,F=(x.match(new RegExp("\\p{Script=Latin}","gu"))||[]).length/Math.max(1,(x.match(new RegExp("\\p{L}","gu"))||[]).length),H=Z.indictransLanguage(P)&&F<.5&&Z.state()!=="error"&&ut(),ae=!!e.translateTo&&pt(P,e.translateTo)&&(H||mt(x,P)&&oe.state()!=="error"),se=te.length>1&&k?k.filter(W=>W.startMs<j+y.durationMs&&W.startMs+W.durationMs>j):k;if(K(e,{type:"final",text:x,reason:f,endOfTurn:y.last?O:!1,durationMs:y.durationMs,startMs:j,...P?{lang:P}:{},...ae?{translating:!0}:{},...v?{speaker:v}:{},...se?.length?{turns:se}:{}}),ae){const W=e.translateTo,pe=H?Z:oe;pe.state()==="off"&&pe.init({...e.translateLoad,...H?{sessionOptions:re()}:{}}),e.translations=e.translations.then(async()=>{await pe.ready();const De=H?await Z.translate(x,P):await oe.translate(x);K(e,{type:"translation",startMs:j,lang:P,to:W,text:De||null,...De?{}:{failed:!0}})}).catch(()=>{})}}}else d!==e.lastInterim&&(e.lastInterim=d,K(e,{type:"interim",text:d}))}async function cn(e){const t=de(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(V=V.then(()=>be(t,{flush:!0}).catch(()=>{}))),await Promise.race([t.translations,new Promise(n=>setTimeout(n,tn).unref?.())])}finally{if(K(t,{type:"end"}),t.listeners.clear(),C.delete(t.id),t.poll){const n=setTimeout(()=>I.delete(t.id),qt);n.unref?.(),I.set(t.id,{session:t,timer:n})}t.diarizer&&(U.release(),Y.release()),t.translateTo&&(oe.release(),Z.release()),R.release(),ee.leave(t.echo),C.size===0&&ue()&&N?.arm()}return!0}function zn(){for(const e of C.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);C.clear();for(const e of I.values())clearTimeout(e.timer);I.clear(),N?.disarm(),N=null,m="off",E=null,h=null,D=null,q=null,T=null}function Un(e,t="test/fake",{warmMs:n=null,dtype:o=null}={}){h=e,E=t,m=e?"ready":"off",X=o,n!==null&&(N=we({warmMs:n,busy:le,unload:()=>Me()}),e&&N.arm())}export{Wt as AUTO_FETCH_MAX_MB,$e as COMPRESSION_LIMIT,Rt as FROM_ENGLISH,Ft as FROM_ENGLISH_RUN_S,vt as LOOP_DROP,zt as PAUSE_SHARE,ze as PIECE_MIN_S,Pt as PIECE_PAUSE_S,p as SAMPLE_RATE,Ce as THIN_SPEAKER_SAMPLES,Ue as TO_ENGLISH,Fe as WEAK_SPEAKER_SAMPLES,zn as _reset,Un as _setPipeForTest,rn as clampEndSilence,Dt as collapseLoops,Nt as collapseRuns,He as compressionRatio,On as createSession,$n as decodeNow,Rn as drainEvents,cn as endSession,Fn as endedSession,de as getSession,bn as health,Dn as init,ue as isReady,$t as languageGroups,bt as looksHallucinated,Gt as modelOnDisk,en as noiseFloorOf,Ht as pauseCuts,Ut as pauseLevel,xn as progress,Cn as pushAudio,ln as quietestCut,Ct as relabelGroups,ie as runtimeDtype,Pe as runtimeName,ce as segmentLanguage,Nn as sessionCount,vn as setModel,Zt as silenceGate,Xe as speakerPlan,An as state,re as sttSessionOptions,Ot as sttThreads,Pn as subscribe,Hn as toFloat32,Me as unload,kn as warmPending};
|
|
1
|
+
import{join as Qe}from"node:path";import{deflateSync as Je}from"node:zlib";import ve from"node:os";import{existsSync as Ze,readdirSync as et}from"node:fs";import{randomUUID as tt}from"node:crypto";import{ensureLib as Ne,modelRoot as Oe}from"./ner-engine.js";import{runtimeDtype as ie,runtimeName as Pe,DTYPE_SUFFIX as nt}from"./model-runtime.js";import{verifyModelWeights as ot}from"./model-integrity.js";import{DEFAULT_STT_MODEL as Re,isEnglishOnly as me,sttModelDtype as he,isKnownSttModel as rt,sttModelEngine as z}from"./stt-models.js";import*as B from"./parakeet-engine.js";import*as _e from"./coreml-stt-engine.js";import*as ne from"./indic-engine.js";import*as U from"./diarize-engine.js";import*as Y from"./segment-engine.js";import{turnsFromSpans as lt,mainLocal as at,timeByLocal as st,audioOfLocal as it}from"@chatpanel/events/speaker-turns.js";import{diarizeApproxMB as ct}from"./diarize-models.js";import*as oe from"./translate-engine.js";import*as Z from"./indictrans-engine.js";import{rawOrtAvailable as ut}from"./ort.js";import*as R from"./vad-engine.js";import*as ee from"./echo-pair.js";import{mostlyEcho as ft}from"./aec-engine.js";import{pickSegmentLanguage as dt,detectTextLanguage as gt,needsTranslation as pt,localTranslatable as mt,normalizeLanguages as ht,normalizeLanguage as _t,decodeLanguages as wt,lineLanguage as yt,autoCandidates as Mt,AUTO_LEARN_CONFIDENCE as Tt,AUTO_LEARN_SECONDS as St,ANY_LANGUAGE_CONFIDENCE as Et,AUTO_LANGUAGES as Lt}from"@chatpanel/events/speech-language.js";import{makeWarmTimer as we}from"./warm-timer.js";const p=16e3,Fe=p,Ce=3*p,At=2,xt=new Set(["thank you","thanks","thank you for watching","thanks for watching","you","uh","um","hmm","hm","mm","amen","bye","okay","ok","yeah","oh","the","that","so","and","i","a","me","we","yes","no","thank you very much","subtitles by the amara.org community","you you"]);function bt(e,t){if(t>At*p)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?xt.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}const kt=12,ye=3;function Dt(e){const t=String(e||"").split(/\s+/).filter(Boolean);if(t.length<ye)return{text:String(e||"").trim(),removed:0,total:t.length};const n=l=>l.toLowerCase().replace(/[^\p{L}\p{N}']/gu,""),o=[];let r=0;for(let l=0;l<t.length;){let i=0,s=0;for(let a=1;a<=kt&&l+a*ye<=t.length;a++){let c=1;for(;l+(c+1)*a<=t.length&&t.slice(l+c*a,l+(c+1)*a).every((u,g)=>n(u)===n(t[l+g]));)c++;c>=ye&&(c-1)*a>i&&(i=(c-1)*a,s=a)}i?(o.push(...t.slice(l,l+s)),r+=i,l+=s+i):(o.push(t[l]),l++)}return{text:o.join(" "),removed:r,total:t.length}}const vt=.6,$e=2.4;function He(e){const t=Buffer.from(String(e||""),"utf8");return t.length<40?1:t.length/Je(t).length}function Nt(e){return String(e||"").replace(/([^\d\s]{1,8}?)\1{4,}/gu,"$1")}function Ot({cores:e=ve.availableParallelism?.()??ve.cpus().length,env:t=process.env}={}){const n=Number(t.CHATPANEL_STT_THREADS);return Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(4,Math.floor(e/2)))}function re(e){return{intraOpNumThreads:Ot(e),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}const Pt=.12,ze=.8,Ue=.15,Rt=.999,Ft=2.5;function ce(e={}){return(e.en??0)>=Ue?"en":Object.entries(e).sort((t,n)=>n[1]-t[1])[0]?.[0]||null}function Ct(e,t=[]){const n=[];return e.forEach((o,r)=>{const l=t[r]??o.lang,i=n[n.length-1];i&&i.lang===l?i.to=o.to:n.push({from:o.from,to:o.to,lang:l})}),n}function $t(e,{base:t=null,rate:n=p}={}){const o=e||[],r=a=>{const[c,u]=Object.entries(a.scores||{}).sort((g,A)=>A[1]-g[1])[0]||[];return c&&c!=="en"&&u>=Rt?c:null},l=new Array(o.length).fill(null);for(let a=0;a<o.length;){const c=r(o[a]);let u=a+1;if(c)for(;u<o.length&&r(o[u])===c;)u++;if(c&&(o[u-1].to-o[a].from)/n>=Ft)for(let g=a;g<u;g++)l[g]=c;a=u}const i=[];let s=t;return o.forEach((a,c)=>{l[c]?s=l[c]:s!=="en"&&(a.scores?.en??0)>=Ue&&(s="en");const u=i[i.length-1];u&&u.lang===s?u.to=a.to:i.push({from:a.from,to:a.to,lang:s})}),i}function Ht(e,t,{frame:n=Math.round(.03*p),minPause:o=Pt*p,minPiece:r=ze*p}={}){const l=[];let i=0,s=-1;for(let a=0;a+n<=e;a+=n){const c=t(a,a+n)===!1;if(c&&s<0&&(s=a),(!c||a+2*n>e)&&s>=0){const u=c?a+n:a,g=Math.round((s+u)/2);u-s>=o&&g-i>=r&&e-g>=r&&(l.push(g),i=g),s=-1}}return l}const zt=.12;function Ut(e,t=Math.round(.03*p)){const n=Math.floor(e.length/t);if(n<3)return 0;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=Q(e,r*t,(r+1)*t);return o.sort(),Math.max(1e-4,o[Math.floor(n*.9)]*zt)}let m="off",E=null,h=null,D=null,q=null,T=null,X=null,N=null;function Gt(e=E||Re,t=he(e)||ie()){if(z(e)==="parakeet-tdt")return B.parakeetOnDisk(e,B.parakeetDtype(t));if(z(e)==="coreml-tdt")return _e.coremlOnDisk(e);if(z(e)==="indic-canary")return ne.indicOnDisk();const n=Qe(Oe(),...e.split("/"),"onnx");if(!Ze(n))return!1;const o=nt[t]??"";try{const r=et(n);return r.includes(`encoder_model${o}.onnx`)&&r.some(l=>l===`decoder_model_merged${o}.onnx`||l===`decoder_model${o}.onnx`)}catch{return!1}}function An(){return m}function ue(){return m==="ready"&&!!h}function xn(){return T}function bn(){return{configured:m!=="off",ok:ue(),state:m,model:E,dtype:X,runtime:Pe(),error:D,warmMs:N?.warmMs??null,vad:R.state()}}function kn(){return!!N?.pending()}function le(){return C.size>0||m==="loading"||m==="downloading"}async function Me({log:e=()=>{}}={}){if(le())return!1;N?.disarm();const t=h;if(h=null,q=null,X=null,T=null,D=null,m="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((N?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function Ge(e){return e.then(t=>(t&&!le()&&N?.arm(),t))}async function je(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null,licenseAccepted:r=null}={}){if(z(e)==="parakeet-tdt")return jt(e,{log:t,allowDownload:n,dtype:o});if(z(e)==="coreml-tdt")return Xt(e,{log:t,allowDownload:n});if(z(e)==="indic-canary")return Kt(e,{log:t,allowDownload:n,licenseAccepted:r});const l=h,i=E;let s;try{s=await Ne()}catch(L){return m="error",D=`engine load failed: ${L.message}`,t(`[stt] transformers.js not available (${L.message}) — dictation falls back to the browser engine`),!1}const c=(o&&o!=="auto"?o:null)||he(e)||ie(),u=Gt(e,c);if(s.env.allowRemoteModels=u?!1:!!n,!u&&!n)return m="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const g=s.env.remoteHost,A=!rt(e);if(!u&&A)try{s.env.remoteHost="https://huggingface.co/"}catch{}m=u?"loading":"downloading",u||(T={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${A?", from Hugging Face":""})…`));try{const L=d=>{if(!d)return;const J=typeof d.progress=="number"?Math.round(d.progress):T?.pct??0;d.status==="progress"||d.status==="download"||d.status==="initiate"?T={model:e,file:d.file||T?.file||null,pct:J}:d.status==="done"&&d.file&&t(`[stt] fetched ${d.file}`)};let w;try{w=await s.pipeline("automatic-speech-recognition",e,{dtype:c,progress_callback:L,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:re()}})}catch(d){if(u||A||!n)throw d;t(`[stt] mirror fetch failed (${String(d.message).slice(0,80)}) — retrying from Hugging Face…`),s.env.remoteHost="https://huggingface.co/",s.env.allowRemoteModels=!0,w=await s.pipeline("automatic-speech-recognition",e,{dtype:c,progress_callback:L,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:re()}})}if(!u)try{ot(e,{modelsDir:Oe(),log:t})}catch(d){try{await w.dispose?.()}catch{}throw d}if(h=w,E=e,m="ready",D=null,T=null,X=c,l&&l!==w)try{await l.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${c} (in-process, offline) — local dictation active`),!0}catch(L){return D=L.message,T=null,l?(h=l,E=i,m="ready"):m="error",t(`[stt] model load failed (${L.message})${l?" — keeping previous model":""}`),!1}finally{try{s.env.remoteHost=g}catch{}}}async function jt(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null}={}){const r=h,l=E,i=B.parakeetDtype(o&&o!=="auto"?o:Bt()),s=B.parakeetOnDisk(e,i);if(!s&&!n)return m="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;m=s?"loading":"downloading",s||(T={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const a=await B.loadRecognizer({modelId:e,dtype:i,allowDownload:n,log:t,sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:re(),onProgress:u=>{T={model:e,file:u.file||null,pct:typeof u.pct=="number"?u.pct:T?.pct??0}}}),c=async u=>({text:await a.transcribe(u)});if(c.__transducer=!0,c.dispose=()=>a.dispose(),h=c,E=e,m="ready",D=null,T=null,X=i,r&&r!==c)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(a){return D=a.message,T=null,r?(h=r,E=l,m="ready"):m="error",t(`[stt] model load failed (${a.message})${r?" — keeping previous model":""}`),!1}}function Bt(){return B.PARAKEET_DEFAULT_DTYPE}const Be="fp16";async function Xt(e,{log:t=()=>{},allowDownload:n=!0}={}){const o=h,r=E,l=_e.coremlOnDisk(e);if(!l&&!n)return m="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;m=l?"loading":"downloading",l||(T={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let i=null;const s=await _e.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:a=>{T={model:e,file:a.file||null,pct:typeof a.pct=="number"?a.pct:T?.pct??0}},onExit:a=>{h===i&&(h=null,q=null,m="error",D=a,N?.disarm(),t(`[stt] ${a} — reloads on the next dictation`))}});if(i=async a=>({text:await s.transcribe(a)}),i.__transducer=!0,i.dispose=()=>s.dispose(),h=i,E=e,m="ready",D=null,T=null,X=Be,o&&o!==i)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} (Core ML on the Neural Engine, helper ${s.version}, windows ${s.windows.join("/")} s, offline) — local dictation active`),!0}catch(i){return D=i.message,T=null,o?(h=o,E=r,m="ready"):m="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}async function Kt(e,{log:t=()=>{},allowDownload:n=!0,licenseAccepted:o=null}={}){const r=h,l=E,i=ne.indicOnDisk();if(!i&&!n)return m="error",D="model not on disk and downloads disabled",!1;m=i?"loading":"downloading",i||(T={model:e,file:null,pct:0},t(`[stt] downloading ${e} (one-time, ~1.5 GB, from Hugging Face)…`));try{i||await ne.ensureIndicFiles({licenseAccepted:o,log:t,onProgress:c=>{T={model:e,file:c.file,pct:c.pct}}});const s=await ne.loadRecognizer({sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:re(),log:t}),a=async(c,u={})=>s.transcribe(c,u);if(a.identify=(c,u)=>s.identify(c,u),a.__transducer=!0,a.__indic=!0,a.dispose=()=>s.dispose(),h=a,E=e,m="ready",D=null,T=null,X="int8",r&&r!==a)try{await r.dispose?.()}catch{}return t(`[stt] ready — ${e} (Indic-Transcribe, int8, in-process, offline) — ${ne.INDIC_LICENSE.attribution}`),!0}catch(s){return D=s.message,T=null,r?(h=r,E=l,m="ready"):m="error",t(`[stt] model load failed (${s.message})${r?" — keeping previous model":""}`),!1}}const Wt=30;function Xe({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:o=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof o=="number"&&o<=Wt||e==="download"?{allowDownload:!0}:null}function Te(e,{log:t=()=>{},warmMs:n,allowDownload:o=!0}={}){const r=Xe({mode:e,onDisk:U.modelOnDisk(),ready:U.isReady(),approxMB:ct(U.activeModel())});if(r&&U.init({allowDownload:r.allowDownload&&o!==!1,warmMs:n,onLog:t}),e==="off"||Se)return;const l=Xe({mode:e,onDisk:Y.modelOnDisk(),ready:Y.isReady(),approxMB:Y.SEGMENT_MODEL_APPROX_MB});l&&Y.init({allowDownload:l.allowDownload&&o!==!1,warmMs:n,onLog:t})}let Se=!1,Ee=null;function Le(e={},{log:t=()=>{}}={}){e.vad!==!1&&(Ee={vad:e.vad,allowDownload:e.allowDownload,warmMs:e.warmMs},(R.state()==="off"||R.state()==="error")&&R.init({allowDownload:e.allowDownload!==!1,warmMs:e.warmMs,onLog:t}))}function Dn(e={}){if(q&&m!=="error")return q;const t=typeof e.onLog=="function"?e.onLog:()=>{};return E=e.model||Re,Se=e.segment===!1,m="loading",N=we({warmMs:e.warmMs,busy:le,log:t,unload:()=>Me({log:t})}),q=Ge(je(E,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype,licenseAccepted:e.licenseAccepted||null})).then(n=>(n&&(Te(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),Le(e,{log:t})),n)),q}async function vn(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(Se=t.segment===!1);const o=z(e)==="parakeet-tdt"?B.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:B.PARAKEET_DEFAULT_DTYPE):z(e)==="coreml-tdt"?Be:z(e)==="indic-canary"?"int8":t.dtype&&t.dtype!=="auto"?t.dtype:he(e)||ie();if(e===E&&ue()&&X===o)return Te(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;N??=we({warmMs:t.warmMs,busy:le,log:n,unload:()=>Me({log:n})});const r=await Ge(je(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype,licenseAccepted:t.licenseAccepted||null}));return r&&(Te(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),Le(t,{log:n})),r}const Yt=8,qt=12e4,It=6e4,Vt=1200,fe=12,Ae=700,xe=.008,Qt=.002,Jt=4;function Zt(e){return e>0?Math.min(xe,Math.max(Qt,e*Jt)):xe}function en(e){const t=Math.round(.1*p),n=Math.floor(e.length/t);if(n<5)return null;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=Q(e,r*t,(r+1)*t);return o.sort(),o[Math.floor(n*.1)]}const Ke=30,tn=15e3,C=new Map,I=new Map;let V=Promise.resolve();function Nn(){return C.size}const nn=300,on=3e3;function rn(e){const t=Number(e);return Number.isFinite(t)?Math.min(on,Math.max(nn,Math.round(t))):Ae}function On({lang:e,langs:t=null,translateTo:n=null,translateLoad:o=null,echo:r=null,redact:l=!1,diarize:i=!1,speakerLabel:s=null,endSilenceMs:a=Ae,interims:c=!0,remote:u=null,poll:g=!1}={}){if(C.size>=Yt){const d=new Error("too many concurrent dictation sessions");throw d.code="too_many_sessions",d}const A=Array.isArray(t)?ht(t):null,L=typeof e=="string"&&e?e.slice(0,12):null,w={id:tt(),endSilenceMs:rn(a),lang:A?A.length===1?A[0]:A.length?null:L:L,langs:A,lastLang:null,lastDecoded:null,learned:new Set,translateTo:_t(n)||null,translateLoad:o||{},translations:Promise.resolve(),echo:r&&typeof r=="object"?ee.join(r.group,r.role):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!l,diarize:!!i,speakerLabel:typeof s=="string"&&s?s.slice(0,40):null,diarizer:i?new U.Diarizer:null,remote:u||null,interims:c!==!1&&!u,chunks:[],samples:0,listeners:new Set,poll:g?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return C.set(w.id,w),N?.disarm(),w.diarizer&&(U.retain(),Y.retain()),w.translateTo&&(oe.retain(),Z.retain()),R.retain(),Ee&&(R.state()==="off"||R.state()==="error")&&Le(Ee),We(w),{id:w.id}}function de(e){return C.get(String(e||""))||null}function Pn(e,t){const n=de(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function K(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function Rn(e){const t=String(e||""),n=C.get(t);if(n)return n.poll?n.poll.splice(0):null;const o=I.get(t);return o?(clearTimeout(o.timer),I.delete(t),o.session.poll.splice(0)):null}function Fn(e){return I.get(String(e||""))?.session||null}function We(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>cn(e.id).catch(()=>{}),It),e.idleTimer.unref?.()}function Cn(e,t){const n=de(e);if(!n||n.closed){const o=new Error("no such session");throw o.code="no_session",o}if(!(!(t instanceof Float32Array)||!t.length)){if(We(n),n.echo?.role==="mic"){ee.pushMic(n.echo,t),Ye(n);return}n.echo?.role==="reference"&&ee.pushReference(n.echo,t),n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,Ye(n)}}function $n(e){const t=de(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),V=V.then(()=>be(t).catch(()=>{})),V)}function Hn(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let o=0;o<n.length;o++)n[o]=e.readFloatLE(o*4);return n}function Ye(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+Vt-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,V=V.then(()=>be(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function qe(e){const t=new Float32Array(e.samples);let n=0;for(const o of e.chunks)t.set(o,n),n+=o.length;return t}function ln(e,t,n){const o=p/100,r=Math.max(0,e.length-t),l=Math.floor((e.length-r)/o),i=Math.max(1,Math.round(n/o));if(l<=i)return 0;const s=new Float32Array(l);for(let g=0;g<l;g++){let A=0;const L=r+g*o;for(let w=0;w<o;w++)A+=e[L+w]*e[L+w];s[g]=A/o}let a=-1,c=1/0,u=0;for(let g=0;g<i;g++)u+=s[g];for(let g=0;g+i<=l;g++)g>0&&(u+=s[g+i-1]-s[g-1]),u<c&&(c=u,a=g);return a<0?0:r+Math.round((a+i/2)*o)}function Q(e,t=0,n=e.length){let o=0;const r=Math.max(1,n-t);for(let l=t;l<n;l++)o+=e[l]*e[l];return Math.sqrt(o/r)}function an(e,t=xe){const n=Math.round(.02*p);let o=0,r=e.length;for(let l=0;l+n<=e.length;l+=n)if(Q(e,l,l+n)>=t){o=l;break}for(let l=e.length-n;l>=0;l-=n)if(Q(e,l,l+n)>=t){r=l+n;break}return r>o?e.subarray(o,r):e}async function Ie(e){try{const t=await Ne(),n=h?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const o=e.length>p*8?e.subarray(0,p*8):e,r=await h.processor(o),l=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),i=await h.model({...r,decoder_input_ids:l}),s={};for(const[a,c]of Object.entries(n.lang_to_id))s[a.slice(2,-2)]=Number(i.logits.data[c]);return s}catch{return null}}async function sn(e){const t=await Ie(e);if(!t)return null;let n=null,o=-1/0;for(const[r,l]of Object.entries(t))l>o&&(o=l,n=r);return n}async function be(e,{flush:t=!1}={}){if(e.closed&&!t)return;if(e.echo?.role==="mic"){const f=await ee.drain(e.echo,{force:t});f.length&&(e.chunks.push(f),e.samples+=f.length,e.pushed+=f.length)}if(!e.remote&&!ue()||!e.samples)return;e.lastDecodeAt=Date.now();let n=qe(e);const o=n.length,r=Math.max(0,(e.pushed||0)-e.samples),l=Math.round((e.endSilenceMs||Ae)/1e3*p),i=en(n);i!==null&&(e.noiseFloor==null||i<e.noiseFloor)&&(e.noiseFloor=i);const s=Zt(e.noiseFloor);let a=null,c=null;R.isReady()&&(e.vad||=R.createStream(),await e.vad.advance(n,r)&&(a=e.vad.speechIn(r,r+n.length,R.ONSET),n.length>l&&(c=e.vad.speechIn(r+n.length-l,r+n.length,R.OFFSET))));const u=n.length>l&&(c!==null?!c:Q(n,n.length-l)<s);if(a===!1||a===null&&Q(n)<s){n.length>p*5&&(e.chunks=[n.subarray(n.length-p)],e.samples=p);return}if(!e.interims&&!t&&!u&&n.length<fe*p)return;let g=null;if(!t&&!u&&o>=fe*p&&o<Ke*p){const f=ln(n,3*p,Math.round(.2*p));f>0&&f<n.length&&(g=n.subarray(f),n=n.subarray(0,f))}const A=!e.remote&&!me(E)&&!h?.__transducer;if(A&&!e.langs&&!e.lang&&!e.langTried&&n.length>=p){e.langTried=!0;const f=await sn(n);f&&(e.lang=f,K(e,{type:"language",lang:f}))}const L=t||u||o>=fe*p;let w=e.lang;if(A&&e.langs&&!e.lang){const f=e.langs.length>0,O=f?wt(e.langs):Mt([...e.learned]);if(O.length===1)w=O[0];else if(w=O.includes(e.lastDecoded)?e.lastDecoded:null,(L||!w)&&n.length>=p/2){const b=await Ie(n);if(b){const M=dt({scores:b,allowed:O,seconds:n.length/p,last:e.lastDecoded});w=!f&&!M.inherited&&M.confidence<Et?e.lastDecoded||"en":M.lang,!f&&L&&!M.inherited&&M.confidence>=Tt&&n.length>=St*p&&e.learned.add(M.lang)}}L&&w&&(e.lastDecoded=w)}let d="",J=null,$=null,ge=null;try{if(e.remote){const f=await e.remote.transcribe(n,{lang:e.lang,langs:e.langs});d=f.text,ge=f.lang||null}else{const f=h.__indic?e.langs?.length?{langs:[...new Set([...e.langs,"en"])],last:e.lastLang,choose:ce}:e.lang?{lang:e.lang}:{langs:[...Lt],last:e.lastLang,choose:ce}:me(E)?{}:{language:w||void 0,task:"transcribe"},O=h.__indic&&h.identify&&L&&f.langs&&n.length>=2*ze*p?Ht(n.length,(M=>(_,v)=>Q(n,_,v)>=M)(Ut(n))):[];let b=null;if(O.length){const M=await h.identify(n,{langs:f.langs}),_=[0,...O,n.length],v=[];for(let k=0;k+1<_.length;k++){const S=await h.identify(n.subarray(_[k],_[k+1]),{langs:f.langs});v.push({from:_[k],to:_[k+1],scores:S?.scores||{}})}if(b=$t(v,{base:M?.scores?ce(M.scores):null}),b.length>1){const k=[];for(let S=0;S<b.length;S++){const G=b[S],te=G.lang&&G.lang!=="en"&&(b[S-1]?.lang==="en"||b[S+1]?.lang==="en");k.push(te?ce((await h.identify(n.subarray(G.from,G.to),{langs:f.langs}))?.scores||{}):G.lang)}b=Ct(b,k)}b.length<2&&(b=null)}if(b){$=[];for(const _ of b){const v=await h(n.subarray(_.from,_.to),_.lang?{lang:_.lang}:{...f}),k=String(v?.text||"").trim(),S=v?.lang||_.lang||null;k&&$.push({text:k,lang:S,from:_.from,to:_.to}),S&&(f.last=S)}d=$.map(_=>_.text).join(" ");const M=new Map;for(const _ of $)_.lang&&M.set(_.lang,(M.get(_.lang)||0)+(_.to-_.from));J=[...M].sort((_,v)=>v[1]-_[1])[0]?.[0]||null,($.length<2||M.size<2)&&($=null)}else{const M=await h(n,f);d=String(M?.text||"").trim(),h.__indic&&(J=M?.lang||null)}}}catch(f){K(e,{type:"error",code:"decode_failed",message:f.message,fatal:!1});return}if(!d)return;{const f=Dt(d);if(f.removed&&f.removed/f.total>=vt&&f.total>=12?d="":d=f.text,d&&He(d)>$e){const O=Nt(d);d=O.replace(/[\s\p{P}]/gu,"").length<12||He(O)>$e?"":O}if(!d)return}const Ve=o>=fe*p,ke=o>=Ke*p;if(t||u||Ve||ke){const f=t?"flush":u?"silence":ke?"overflow":"length",O=f==="flush"||f==="silence",b=e.samples-o,M=[];g&&M.push(g),b>0&&M.push(qe(e).subarray(o)),e.chunks=M,e.samples=M.reduce((y,x)=>y+x.length,0),e.lastInterim="";const _=an(n,s);if(bt(d,_?_.length:0)||e.echo?.role==="mic"&&ft(ee.verdict(e.echo,r,r+n.length)))return;let v=null,k=null;if(e.diarizer)try{const y=e.speakerLabel?null:await Y.spans(n),x=y?lt(y):[];if(x.length){const P=new Map;for(const{local:F}of st(x)){const H=it(n,x,F),ae=H.length?await U.embed(H):null,se=H.length<Fe,W=H.length<Ce;P.set(F,e.diarizer.assign(ae,{pinnedLabel:null,weak:se,thin:W}))}const j=Math.round(r/p*1e3);k=x.map(F=>({startMs:j+Math.round(F.start*1e3),durationMs:Math.round((F.end-F.start)*1e3),speaker:P.get(F.local)})).filter(F=>F.speaker),v=P.get(at(x))||null}}catch{}if(e.diarizer&&!v)try{const y=_,x=y?await U.embed(y):null,P=!!y&&y.length<Fe,j=!!y&&y.length<Ce;v=e.diarizer.assign(x,{pinnedLabel:e.speakerLabel,weak:P,thin:j})}catch{}let S=null;(e.langs||e.translateTo)&&(J?S=J:ge?S=ge:me(E)&&!e.remote?S="en":A?S=yt(d,w||e.lang)||null:S=e.lang||gt(d,{allowed:e.langs||[],last:e.lastLang}).lang,S&&S!==e.lastLang&&(e.lastLang=S,K(e,{type:"language",lang:S})));const G=Math.round(r/p*1e3),te=$&&(e.langs||e.translateTo)?$.map((y,x)=>({text:y.text,lang:y.lang,startMs:G+Math.round(y.from/p*1e3),durationMs:Math.round((y.to-y.from)/p*1e3),last:x===$.length-1})):[{text:d,lang:S,startMs:G,durationMs:Math.round(n.length/p*1e3),last:!0}];for(const y of te){te.length>1&&y.lang&&y.lang!==e.lastLang&&(e.lastLang=y.lang,K(e,{type:"language",lang:y.lang}));const{text:x,lang:P,startMs:j}=y,F=(x.match(new RegExp("\\p{Script=Latin}","gu"))||[]).length/Math.max(1,(x.match(new RegExp("\\p{L}","gu"))||[]).length),H=Z.indictransLanguage(P)&&F<.5&&Z.state()!=="error"&&ut(),ae=!!e.translateTo&&pt(P,e.translateTo)&&(H||mt(x,P)&&oe.state()!=="error"),se=te.length>1&&k?k.filter(W=>W.startMs<j+y.durationMs&&W.startMs+W.durationMs>j):k;if(K(e,{type:"final",text:x,reason:f,endOfTurn:y.last?O:!1,durationMs:y.durationMs,startMs:j,...P?{lang:P}:{},...ae?{translating:!0}:{},...v?{speaker:v}:{},...se?.length?{turns:se}:{}}),ae){const W=e.translateTo,pe=H?Z:oe;pe.state()==="off"&&pe.init({...e.translateLoad,...H?{sessionOptions:re()}:{}}),e.translations=e.translations.then(async()=>{await pe.ready();const De=H?await Z.translate(x,P):await oe.translate(x);K(e,{type:"translation",startMs:j,lang:P,to:W,text:De||null,...De?{}:{failed:!0}})}).catch(()=>{})}}}else d!==e.lastInterim&&(e.lastInterim=d,K(e,{type:"interim",text:d}))}async function cn(e){const t=de(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(V=V.then(()=>be(t,{flush:!0}).catch(()=>{}))),await Promise.race([t.translations,new Promise(n=>setTimeout(n,tn).unref?.())])}finally{if(K(t,{type:"end"}),t.listeners.clear(),C.delete(t.id),t.poll){const n=setTimeout(()=>I.delete(t.id),qt);n.unref?.(),I.set(t.id,{session:t,timer:n})}t.diarizer&&(U.release(),Y.release()),t.translateTo&&(oe.release(),Z.release()),R.release(),ee.leave(t.echo),C.size===0&&ue()&&N?.arm()}return!0}function zn(){for(const e of C.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);C.clear();for(const e of I.values())clearTimeout(e.timer);I.clear(),N?.disarm(),N=null,m="off",E=null,h=null,D=null,q=null,T=null}function Un(e,t="test/fake",{warmMs:n=null,dtype:o=null}={}){h=e,E=t,m=e?"ready":"off",X=o,n!==null&&(N=we({warmMs:n,busy:le,unload:()=>Me()}),e&&N.arm())}export{Wt as AUTO_FETCH_MAX_MB,$e as COMPRESSION_LIMIT,Rt as FROM_ENGLISH,Ft as FROM_ENGLISH_RUN_S,vt as LOOP_DROP,zt as PAUSE_SHARE,ze as PIECE_MIN_S,Pt as PIECE_PAUSE_S,p as SAMPLE_RATE,Ce as THIN_SPEAKER_SAMPLES,Ue as TO_ENGLISH,Fe as WEAK_SPEAKER_SAMPLES,zn as _reset,Un as _setPipeForTest,rn as clampEndSilence,Dt as collapseLoops,Nt as collapseRuns,He as compressionRatio,On as createSession,$n as decodeNow,Rn as drainEvents,cn as endSession,Fn as endedSession,de as getSession,bn as health,Dn as init,ue as isReady,$t as languageGroups,bt as looksHallucinated,Gt as modelOnDisk,en as noiseFloorOf,Ht as pauseCuts,Ut as pauseLevel,xn as progress,Cn as pushAudio,ln as quietestCut,Ct as relabelGroups,ie as runtimeDtype,Pe as runtimeName,ce as segmentLanguage,Nn as sessionCount,vn as setModel,Zt as silenceGate,Xe as speakerPlan,An as state,re as sttSessionOptions,Ot as sttThreads,Pn as subscribe,Hn as toFloat32,Me as unload,kn as warmPending};
|
package/src/tts-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join as $}from"node:path";import{existsSync as z,mkdirSync as
|
|
1
|
+
import{modelFetch as nt}from"./model-sources.js";import{join as $}from"node:path";import{existsSync as z,mkdirSync as rt,readFileSync as ot,writeFileSync as st,renameSync as lt,statSync as B}from"node:fs";import{ensureLib as it,modelRoot as at}from"./ner-engine.js";import{runtimeDtype as C,runtimeName as G,DTYPE_SUFFIX as ut}from"./model-runtime.js";import{DEFAULT_TTS_MODEL as L,DEFAULT_TTS_VOICE as q,STYLE_DIM as U,ttsModelDtype as N,isKnownTtsModel as ct,isValidVoiceId as J,voiceLang as ft,ttsModelEngine as Q,ttsModel as Z}from"./tts-models.js";import{bundleOnDisk as dt}from"./pocket-tts-engine.js";import{makeWarmTimer as K}from"./warm-timer.js";const O=24e3;let f="off",w=null,R=0,h=null,y=null,M=null,P=null,T=null,_=null,A=null,p=null,D=null,g=null,k=null,v=O;const H=new Map,pt={style_text_to_speech_2:"style-tts2",vits:"vits",speecht5:"speecht5"},x="pocket-tts",ht="Xenova/speecht5_hifigan";function mt(){return p==="speecht5"||p===x}function Ut(){return p===x}function Ot(){return g?.builtinVoices?.()||[]}async function Vt({allowDownload:t=!0,log:e=()=>{}}={}){if(w?.arm(),g)return g;const{PocketTTS:n,bundleOnDisk:r,DEFAULT_BUNDLE:o}=await import("./pocket-tts-engine.js");if(!r(o)&&!t)return null;if(k)return k;const s=new n;return await s.load(o,{log:e}),k=s,s}function Rt(){return p}function Ht(){return v}function wt(){return p==="style-tts2"}function zt(){return f}function V(){return f==="ready"&&!!y}function Bt(){return _}function Ct(){return{configured:f!=="off",ok:V(),state:f,model:h,dtype:P,runtime:G(),error:T,arch:p,sampleRate:v,voices:wt(),customVoices:mt(),warmMs:w?.warmMs??null}}function Nt(){return!!w?.pending()}function F(){return R>0||f==="loading"||f==="downloading"}async function j({log:t=()=>{}}={}){if(F())return!1;w?.disarm();const e=!!(y||g||k),n=[y,D,g,k];y=null,M=null,D=null,g=null,k=null,p=null,P=null,A=null,_=null,T=null,f="off",v=O,H.clear();for(const r of new Set(n))if(r)try{await r.dispose?.()}catch{}return e&&t(`[tts] idle for ${Math.round((w?.warmMs||0)/6e4)} min — model unloaded (reloads on next speech)`),!0}function yt(t){return t.then(e=>(e&&!F()&&w?.arm(),e))}function W(t){return $(at(),...String(t).split("/"))}function gt(t=h||L,e=N(t)||C()){if(Q(t)===x)return dt(Z(t)?.bundle);const n=W(t),r=ut[e]??"",o=[$(n,"onnx",`model${r}.onnx`),$(n,"tokenizer.json")];try{return o.every(s=>z(s)&&B(s).size>0)}catch{return!1}}function Kt(t,e=h||L){if(!J(t))return!1;const n=$(W(e),"voices",`${t}.bin`);try{return z(n)&&B(n).size>0}catch{return!1}}function jt(t={}){const e=t.tts||{};if(e.enabled===!1){f="off";return}h=e.model||L,w=K({warmMs:e.warmMs,busy:F,unload:()=>j()})}async function _t(t,{log:e=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(Q(t)===x)return Tt(t,{log:e,allowDownload:n});const o=y,s=h;let c;try{c=await it()}catch(i){return f="error",T=`engine load failed: ${i.message}`,e(`[tts] transformers.js not available (${i.message}) — read-aloud falls back to browser speech`),!1}const d=(r&&r!=="auto"?r:null)||N(t)||C(),l=gt(t,d);if(c.env.allowRemoteModels=l?!1:!!n,!l&&!n)return f="error",T="model not on disk and downloads disabled",e(`[tts] model ${t} not installed and downloads disabled`),!1;const u=c.env.remoteHost;if(!l&&(!!1||!ct(t)))try{c.env.remoteHost="https://huggingface.co/"}catch{}f=l?"loading":"downloading",l||(_={model:t,file:null,pct:0},e(`[tts] downloading voice model ${t} (one-time)…`));try{const i=await import("@huggingface/transformers");let E="";try{const b=await i.AutoConfig.from_pretrained(t);E=String(b?.model_type||"").toLowerCase()}catch{}const S=pt[E]||(E?null:"style-tts2");if(!S)throw new Error(`unsupported TTS architecture "${E}" — this engine drives Kokoro (style_text_to_speech_2) and VITS/MMS`);const X=b=>{b?.status==="progress"&&b.file&&(_={model:t,file:b.file,pct:Math.round(b.progress||0)})},tt=S==="vits"?i.VitsModel:S==="speecht5"?i.SpeechT5ForTextToSpeech:i.StyleTextToSpeech2Model,[Y,et]=await Promise.all([tt.from_pretrained(t,{dtype:d,progress_callback:X}),i.AutoTokenizer.from_pretrained(t)]);return D=S==="speecht5"?await i.SpeechT5HifiGan.from_pretrained(ht,{dtype:d,progress_callback:X}):null,y=Y,M=et,h=t,P=d,p=S,v=Number(Y?.config?.sampling_rate)||(S==="style-tts2"?O:16e3),f="ready",T=null,_=null,e(`[tts] ready — model ${t} @ ${d} (${S}, ${v} Hz, ${G()}, offline) — local speech active`),!0}catch(i){return y=o,h=s,f=o?"ready":"error",T=i.message,_=null,e(`[tts] model load failed (${i.message})`),!1}finally{try{c.env.remoteHost=u}catch{}}}async function Tt(t,{log:e=()=>{},allowDownload:n=!0}={}){const r=p,o=g,s=h,{PocketTTS:c,bundleOnDisk:m,DEFAULT_BUNDLE:d,SAMPLE_RATE:l}=await import("./pocket-tts-engine.js"),u=Z(t)?.bundle||d;if(!m(u)&&!n)return f="error",T="model not on disk and downloads disabled",!1;f=m(u)?"loading":"downloading",f==="downloading"&&(_={model:t,file:null,pct:0});try{const a=new c;return await a.load(u,{log:e,onProgress:({file:i,pct:E})=>{_={model:t,file:i,pct:E}}}),g=a,y=a,M=null,D=null,h=t,p=x,P="int8",v=l,f="ready",T=null,_=null,!0}catch(a){return g=o,p=r,h=s,f=o||y?"ready":"error",T=a.message,_=null,e(`[pocket-tts] load failed (${a.message})`),!1}}async function Et(t,{onLog:e=()=>{},allowDownload:n=!0,dtype:r="auto"}={}){const o=r&&r!=="auto"?r:N(t)||C();return t===h&&V()&&P===o?!0:(w??=K({warmMs:void 0,busy:F,unload:()=>j()}),A=yt(_t(t,{log:e,allowDownload:n,dtype:r})),A)}async function Wt({onLog:t=()=>{},allowDownload:e=!0,model:n=null,dtype:r="auto"}={}){return V()?!0:A||Et(n||h||L,{onLog:t,allowDownload:e,dtype:r})}async function St(t,{allowDownload:e=!0,log:n=()=>{}}={}){if(!J(t))throw new Error(`invalid voice id: ${t}`);const r=H.get(t);if(r)return r;const o=$(W(h||L),"voices"),s=$(o,`${t}.bin`);if(!(z(s)&&B(s).size>0)){if(!e)throw new Error(`voice ${t} not on disk and downloads disabled`);rt(o,{recursive:!0});const d=`https://huggingface.co/${h||L}/resolve/main/voices/${t}.bin`,l=await nt()(d,{redirect:"follow"});if(!l.ok)throw new Error(`fetch voice ${t} → HTTP ${l.status}`);const u=`${s}.part`;st(u,Buffer.from(await l.arrayBuffer())),lt(u,s),n(`[tts] fetched voice ${t}`)}const c=ot(s),m=new Float32Array(c.buffer,c.byteOffset,Math.floor(c.byteLength/4));return H.set(t,m),m}function xt(t,e=300){const n=(o,s)=>{if(o.length<=e)return[o];if(!s.length){const u=[];for(let a=0;a<o.length;a+=e)u.push(o.slice(a,a+e).trim());return u.filter(Boolean)}const[c,...m]=s,d=[];let l="";for(const u of o.split(c)){const a=u.trim();if(!a)continue;const i=l?`${l} ${a}`:a;i.length>e&&l?(d.push(...n(l,m)),l=a):l=i}return l&&d.push(...n(l,m)),d},r=[];for(const o of String(t).split(/(?<=[.!?])\s+|\n{2,}/)){const s=o.trim();s&&r.push(...n(s,[/(?<=[,;:])\s+/,/\s+/]))}return r}async function I(t,{voice:e=q,speed:n=1,speakerEmbedding:r=null}={}){if(!V())throw new Error("tts model not ready");const o=await import("@huggingface/transformers");if(p==="vits"){const i=M(String(t));return(await y(i)).waveform.data}if(p===x){const i=r?.data?.length?r:e;if(!i)throw new Error("this model needs a voice — pick a built-in one or record your own");return g.synth(String(t),{voice:i})}if(p==="speecht5"){if(!r||r.length!==512)throw new Error("this model needs a saved voice — record one in Settings → Text-to-speech");const{input_ids:i}=M(String(t)),E=new o.Tensor("float32",Float32Array.from(r),[1,512]),{waveform:S}=await y.generate_speech(i,E,{vocoder:D});return S.data}const{phonemize:s}=await import("phonemizer"),c=(await s(String(t),ft(e))).join(" "),{input_ids:m}=M(c,{truncation:!0}),d=await St(e),l=Math.min(Math.max(m.dims.at(-1)-2,0),Math.floor(d.length/U)-1),u=d.slice(l*U,l*U+U);return(await y({input_ids:m,style:new o.Tensor("float32",u,[1,U]),speed:new o.Tensor("float32",[n],[1])})).waveform.data}async function Xt(t,e={}){R++,w?.disarm();try{return await Mt(t,e)}finally{R--,!F()&&V()&&w?.arm()}}async function Mt(t,{voice:e=q,speed:n=1,speakerEmbedding:r=null,onChunk:o=null}={}){if(p===x)return I(t,{voice:e,speed:n,speakerEmbedding:r});const s=xt(t),c=[];for(const u of s){const a=await I(u,{voice:e,speed:n,speakerEmbedding:r});c.push(a),o?.(a)}if(c.length===1)return c[0];const m=c.reduce((u,a)=>u+a.length,0),d=new Float32Array(m);let l=0;for(const u of c)d.set(u,l),l+=u.length;return d}function Yt(t,e=O){const n=Buffer.alloc(44+t.length*2);n.write("RIFF",0),n.writeUInt32LE(36+t.length*2,4),n.write("WAVE",8),n.write("fmt ",12),n.writeUInt32LE(16,16),n.writeUInt16LE(1,20),n.writeUInt16LE(1,22),n.writeUInt32LE(e,24),n.writeUInt32LE(e*2,28),n.writeUInt16LE(2,32),n.writeUInt16LE(16,34),n.write("data",36),n.writeUInt32LE(t.length*2,40);for(let r=0;r<t.length;r++){const o=Math.max(-1,Math.min(1,t[r]));n.writeInt16LE(Math.round(o*32767),44+r*2)}return n}function Gt(t,{warmMs:e=null}={}){y=t,g=t,p=t?x:null,h=t?"test/fake":null,f=t?"ready":"off",e!==null&&(w=K({warmMs:e,busy:F,unload:()=>j()}),t&&w.arm())}function qt(){w?.disarm(),w=null,R=0,f="off",h=null,y=null,M=null,P=null,T=null,_=null,A=null,p=null,v=O,D=null,g=null,k=null,H.clear()}export{x as POCKET_ARCH,O as SAMPLE_RATE,ht as SPEECHT5_VOCODER,pt as SUPPORTED_ARCH,qt as _reset,Gt as _setForTest,Rt as arch,Ot as builtinVoices,Ct as health,jt as init,Ut as isPocket,V as isReady,W as modelDir,gt as modelOnDisk,Vt as pocketForEncoding,Bt as progress,Wt as ready,Ht as sampleRate,Et as setModel,xt as splitSentences,zt as state,mt as supportsCustomVoices,wt as supportsVoices,Xt as synth,I as synthChunk,Yt as toWav,j as unload,Kt as voiceOnDisk,Nt as warmPending};
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.117.0";export{o as VERSION};
|