@chatpanel/gateway 0.116.0 → 0.118.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/aec-engine.js +1 -1
- package/src/diarize-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/link-host.js +1 -1
- package/src/model-copies.js +1 -0
- package/src/model-hashes.json +105 -1
- package/src/model-integrity.js +1 -1
- package/src/model-sources.js +1 -0
- package/src/ner-engine.js +1 -1
- package/src/parakeet-engine.js +2 -2
- package/src/segment-engine.js +1 -1
- package/src/server.js +19 -19
- package/src/stt-engine.js +1 -1
- package/src/stt-models.js +1 -1
- package/src/translate-engine.js +1 -1
- package/src/tts-engine.js +1 -1
- package/src/tts-models.js +1 -1
- package/src/vad-engine.js +1 -1
- package/src/version.js +1 -1
package/src/model-hashes.json
CHANGED
|
@@ -1,3 +1,107 @@
|
|
|
1
1
|
{
|
|
2
|
-
"_README": "SHA-256
|
|
2
|
+
"_README": "SHA-256 of the curated models' weight files, keyed by model id then by path relative to the model's cache dir (~/.chatpanel/models/<org>/<name>/). GENERATED by tools/model-copies/to-module.mjs from the copies in huggingface.co/ChatPanel (copy_models.py hashed each file it downloaded from the pinned upstream commit) — do NOT hand-edit. model-integrity.js checks a freshly downloaded model against these and refuses a mismatch; a model or file not listed is warn-and-allow.",
|
|
3
|
+
"ChatPanel/indic-transcribe-core-int8": {
|
|
4
|
+
"cross_kv.onnx": "0aed59ffef5e77e2b957d42f742ea2645fed3ac49954b6a91dc8e629d7196c26",
|
|
5
|
+
"cross_kv.onnx.data": "022d88763437e56ac1156b3953c68a01c205b52627094a086d243b822f6e810b",
|
|
6
|
+
"decoder.onnx": "f858a610f1d3498a993d5eb0424ef888d96edc853be3b7aa32846b237d2c4a97",
|
|
7
|
+
"decoder.onnx.data": "c557a469b426ad424b0ed04c7422df44fc12131df2ae300b3f4bc92bdf50d05b",
|
|
8
|
+
"encoder.onnx": "fa49d702bf83d52327105736ded11aea2e6afcfcb1667182e6db36e5cc27f097",
|
|
9
|
+
"encoder.onnx.data": "66c3442b950a3ff5e18fc33db1d15069b7888235776bdc86824d6f99d728f9a5"
|
|
10
|
+
},
|
|
11
|
+
"ChatPanel/indictrans2-indic-en-int8": {
|
|
12
|
+
"cross_kv.onnx": "eb10975a209e5cb0abb01e0e272e236ae2455973e7702e82c0f9aa7193ee9db8",
|
|
13
|
+
"cross_kv.onnx.data": "dc560bf3c174c203df69d3d2bc323ba16e0d1901bfc49db853406f6fa5b8c918",
|
|
14
|
+
"decoder.onnx": "b848027adbd61f3d06dc3019d96f509ef19608d701cb32874b004ad7055927bd",
|
|
15
|
+
"decoder.onnx.data": "f64be74f42e7d2bc642881430df7d9fe28d9f7b3ccec46ad36e9d1a791a6747c",
|
|
16
|
+
"encoder.onnx": "b08c9150c013ebdc39fc91eb374e4b5acbbea609b7b86065d917be237fab7259",
|
|
17
|
+
"encoder.onnx.data": "523545913dfd3a76e8ca58d0b7d4fd74353a571e6e2525cf10d73006ed02b526"
|
|
18
|
+
},
|
|
19
|
+
"MoritzLaurer/ModernBERT-base-zeroshot-v2.0": {
|
|
20
|
+
"onnx/model_quantized.onnx": "d49899e1fa3b04701a3e38b8040119d5b089ca9c0774736a23d1f5c9d9e6571f"
|
|
21
|
+
},
|
|
22
|
+
"Xenova/all-MiniLM-L6-v2": {
|
|
23
|
+
"onnx/model_quantized.onnx": "afdb6f1a0e45b715d0bb9b11772f032c399babd23bfc31fed1c170afc848bdb1"
|
|
24
|
+
},
|
|
25
|
+
"Xenova/bert-base-NER": {
|
|
26
|
+
"onnx/model_quantized.onnx": "caaee70a5518ec7f9e46e5308fcc9263a8c227703a9ce46cf61c69a552349648"
|
|
27
|
+
},
|
|
28
|
+
"Xenova/bert-base-multilingual-cased-ner-hrl": {
|
|
29
|
+
"onnx/model_quantized.onnx": "5b65139844be260b624a2a13782b01d122e613d64ce16ed0ba4d82e0b816f1a9"
|
|
30
|
+
},
|
|
31
|
+
"Xenova/bge-reranker-base": {
|
|
32
|
+
"onnx/model_quantized.onnx": "dd98f3e67837d23210a6b7550c08cced4f61845b940ac45be3565840a10f3244"
|
|
33
|
+
},
|
|
34
|
+
"Xenova/distilbert-base-multilingual-cased-ner-hrl": {
|
|
35
|
+
"onnx/model_quantized.onnx": "24a0b98f4dd4cd92842f5a541272f86f760225a64a29928eddef14bdb2edb986"
|
|
36
|
+
},
|
|
37
|
+
"Xenova/ms-marco-TinyBERT-L-2-v2": {
|
|
38
|
+
"onnx/model_quantized.onnx": "026c2ec3257cd351696e45bbd6040bb83cf818ba89059b4344bd6350138b62ce"
|
|
39
|
+
},
|
|
40
|
+
"Xenova/multilingual-e5-small": {
|
|
41
|
+
"onnx/model_quantized.onnx": "f80102d3f2a1229f387d3c81909990d8945513e347b0eab049f7de3c6f98c193"
|
|
42
|
+
},
|
|
43
|
+
"Xenova/opus-mt-mul-en": {
|
|
44
|
+
"onnx/decoder_model_merged_quantized.onnx": "6add167a0cd3f78aa298b8f927d2e8645e33cb17df11e92967f0c5b5703c8c4d",
|
|
45
|
+
"onnx/encoder_model_quantized.onnx": "5ce609a524375dbdd9c66b62b82b41abc667799022667ce424f20c245bd56925"
|
|
46
|
+
},
|
|
47
|
+
"Xenova/speecht5_hifigan": {
|
|
48
|
+
"onnx/model_quantized.onnx": "d092ea63bbc7839f7317657b5f531ebb68377ee05ec866ec096dba25911f9feb"
|
|
49
|
+
},
|
|
50
|
+
"Xenova/speecht5_tts": {
|
|
51
|
+
"onnx/decoder_model_merged_quantized.onnx": "6afe602f82ecdb34a2db003f45ccc1419c77aaf0032c263b4f6a0f8bf5835798",
|
|
52
|
+
"onnx/decoder_postnet_and_vocoder_quantized.onnx": "d092ea63bbc7839f7317657b5f531ebb68377ee05ec866ec096dba25911f9feb",
|
|
53
|
+
"onnx/encoder_model_quantized.onnx": "407375255d220d8ddf81e9a06d4100f80f870f8446e77d4f20951d2a4c08a156"
|
|
54
|
+
},
|
|
55
|
+
"fastrepl/dtln-aec-128": {
|
|
56
|
+
"model_128_1.onnx": "a060e46a6bebed03d6360262d814851dc6c2806cec7c1b6a388e617cae7c082c",
|
|
57
|
+
"model_128_2.onnx": "6b6e312f701a3fad2aac2981ca1ed978d25dffa0bc8da9f33235a2e91f56705a"
|
|
58
|
+
},
|
|
59
|
+
"istupakov/parakeet-tdt-0.6b-v3-onnx": {
|
|
60
|
+
"decoder_joint-model.int8.onnx": "eea7483ee3d1a30375daedc8ed83e3960c91b098812127a0d99d1c8977667a70",
|
|
61
|
+
"encoder-model.int8.onnx": "6139d2fa7e1b086097b277c7149725edbab89cc7c7ae64b23c741be4055aff09",
|
|
62
|
+
"nemo128.onnx": "a9fde1486ebfcc08f328d75ad4610c67835fea58c73ba57e3209a6f6cf019e9f"
|
|
63
|
+
},
|
|
64
|
+
"jinaai/jina-reranker-v1-tiny-en": {
|
|
65
|
+
"onnx/model_quantized.onnx": "5fa8508528828b4ad9bc97c97b6e020984e3b745fbcb53f0a907e68704f8a18a"
|
|
66
|
+
},
|
|
67
|
+
"onnx-community/Kokoro-82M-v1.0-ONNX": {
|
|
68
|
+
"onnx/model.onnx": "8fbea51ea711f2af382e88c833d9e288c6dc82ce5e98421ea61c058ce21a34cb",
|
|
69
|
+
"onnx/model_quantized.onnx": "fbae9257e1e05ffc727e951ef9b9c98418e6d79f1c9b6b13bd59f5c9028a1478"
|
|
70
|
+
},
|
|
71
|
+
"onnx-community/Kokoro-82M-v1.1-zh-ONNX": {
|
|
72
|
+
"onnx/model.onnx": "94b973941b1852754f979be5d5e20be666d5c81d9bb886b88ae1dc85c9b895ca",
|
|
73
|
+
"onnx/model_quantized.onnx": "a39469be791eeaa3089c1ed5e58b8731d1f2462ea0e7dae2bc44388e58f973d8"
|
|
74
|
+
},
|
|
75
|
+
"onnx-community/multilang-pii-ner-ONNX": {
|
|
76
|
+
"onnx/model_quantized.onnx": "1d02f3829ad90d95dea5e64d35f5528f96d7b223c1e056a96075c6229a484356"
|
|
77
|
+
},
|
|
78
|
+
"onnx-community/pyannote-segmentation-3.0": {
|
|
79
|
+
"onnx/model_quantized.onnx": "93a3eb106923c9b76a7d8af07ac337dd24c2d0dcd20f1b6c55f21133e944d658"
|
|
80
|
+
},
|
|
81
|
+
"onnx-community/silero-vad": {
|
|
82
|
+
"onnx/model.onnx": "a4a068cd6cf1ea8355b84327595838ca748ec29a25bc91fc82e6c299ccdc5808"
|
|
83
|
+
},
|
|
84
|
+
"onnx-community/wespeaker-voxceleb-resnet34-LM": {
|
|
85
|
+
"onnx/model_quantized.onnx": "f73f647730ae440ae411c2241290f42ff5b2106dd3176c897fe6fbb1950d5393"
|
|
86
|
+
},
|
|
87
|
+
"onnx-community/whisper-base": {
|
|
88
|
+
"onnx/decoder_model_merged_quantized.onnx": "fa3ef9902734ce5ae6f9ef2bdb2ba9a6c4b5785b09f4f420ce036573dc9d090b",
|
|
89
|
+
"onnx/encoder_model_quantized.onnx": "5862993336bf33acd23736071aae2b32261d3b1b2f37780194460d4ef974dd46"
|
|
90
|
+
},
|
|
91
|
+
"onnx-community/whisper-large-v3-turbo": {
|
|
92
|
+
"onnx/decoder_model_merged_quantized.onnx": "61481bd3be3a445d5a4b9070e8f8b2c6cc4fbbbbdc9f0e7ed048a132b8b84e0d",
|
|
93
|
+
"onnx/encoder_model_quantized.onnx": "d2f853dc3254fdc0079f55dd4433ea716ac98ec5574d3b475f288f2a77cebba9"
|
|
94
|
+
},
|
|
95
|
+
"onnx-community/whisper-small": {
|
|
96
|
+
"onnx/decoder_model_merged_quantized.onnx": "ec07c3cbb64172c39791e26ee870a65ac22b458c36722bfe2776b3dbf741e0c9",
|
|
97
|
+
"onnx/encoder_model_quantized.onnx": "a43a83f3c5361cd591cfa7c36f14b43cf7cb22f47a415cc14a8d557be800fa92"
|
|
98
|
+
},
|
|
99
|
+
"onnx-community/whisper-tiny.en": {
|
|
100
|
+
"onnx/decoder_model_merged_quantized.onnx": "c0592d0749413c960569e1c7fb806b060d5d18f3ebad4a95cbf9a77dc6e9be52",
|
|
101
|
+
"onnx/encoder_model_quantized.onnx": "e93ec822f16a8fd264e7de972ad17d615ea7334b75a52d54c50c2e18dd503a25"
|
|
102
|
+
},
|
|
103
|
+
"openai/privacy-filter": {
|
|
104
|
+
"onnx/model_quantized.onnx": "a325fb5341567a73c94e91ec5e49060d38d9b16111f518ad34773039a0c9c098",
|
|
105
|
+
"onnx/model_quantized.onnx_data": "50f4c8c7f3c27fbc1fe16d4f74f6f7c3b74ba8f18a262e8b6911854c64c33a6d"
|
|
106
|
+
}
|
|
3
107
|
}
|
package/src/model-integrity.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as
|
|
1
|
+
import{createHash as y}from"node:crypto";import{readFileSync as u,existsSync as m,rmSync as g}from"node:fs";import{join as d}from"node:path";import{fileURLToPath as $}from"node:url";const f=$(new URL("./model-hashes.json",import.meta.url));let h=null;function k(e=f){if(h&&e===f)return h;let r={};try{const i=JSON.parse(u(e,"utf8"));for(const[n,t]of Object.entries(i))!n.startsWith("_")&&t&&typeof t=="object"&&(r[n]=t)}catch{r={}}return e===f&&(h=r),r}function w(e){return y("sha256").update(u(e)).digest("hex")}function x(e,{modelsDir:r,log:i=()=>{},manifest:n=k()}={}){const t=n[e];if(!t||Object.keys(t).length===0)return i(`[integrity] no recorded hashes for ${e} — skipping verification (run tools/gen-model-hashes.mjs on a trusted host to enable)`),{verified:!1,reason:"unlisted",checked:0};const s=d(r,...e.split("/"));let o=0;for(const[c,l]of Object.entries(t)){const a=d(s,...c.split("/"));if(!m(a)){i(`[integrity] ${e}: listed file ${c} not on disk — skipping`);continue}const p=w(a);if(p!==l){try{g(a)}catch{}throw new Error(`[integrity] ${e}/${c} SHA-256 mismatch (expected ${l.slice(0,12)}…, got ${p.slice(0,12)}…) — deleted the file and refusing to load a tampered model`)}o++}return o&&i(`[integrity] ${e}: ${o} weight file(s) verified ✓`),{verified:o>0,reason:o?"ok":"no-files-present",checked:o}}async function F(e,r,{modelsDir:i,log:n=()=>{},dispose:t=null}={}){if(!e)return null;try{return x(r,{modelsDir:i,log:n})}catch(s){try{await t?.()}catch{}throw s}}export{k as loadHashManifest,w as sha256File,F as verifyFresh,x as verifyModelWeights};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{MODEL_COPIES as p}from"./model-copies.js";const h="https://huggingface.co/",m="https://dl.chatpanel.net/models/",y=/^https:\/\/(?:huggingface\.co|dl\.chatpanel\.net\/models)\/([^/]+\/[^/]+)\/resolve\/([^/]+)\/(.+)$/;function $(e){const n=y.exec(String(e||"").split("?")[0]);if(!n)return null;let t;try{t=decodeURIComponent(n[3])}catch{return null}return{id:n[1],rev:n[2],file:t}}const d=e=>e.split("/").map(encodeURIComponent).join("/");function R(e,{copies:n=p}={}){const t=$(e);if(!t)return[String(e)];const s=[],r=n[t.id],c=r&&(!r.files||r.files[t.file]);c&&s.push(`${h}${r.repo}/resolve/${r.revision}/${d(t.file)}`);const i=c&&t.rev==="main"&&r.upstreamRevision?r.upstreamRevision:t.rev;return s.push(`${h}${t.id}/resolve/${i}/${d(t.file)}`),s.push(`${m}${t.id}/resolve/${i}/${d(t.file)}`),[...new Set(s)]}function E(e=globalThis.fetch,{copies:n=p}={}){return async function(s,r){const c=typeof s=="string"?s:s?.url??String(s),i=R(c,{copies:n});if(i.length===1)return e(i[0],r);const g=$(c),v=i.find(l=>l.startsWith(`${h}${g.id}/`))||i[i.length-2],S=l=>l.status>=500||l.status===429;let u=null,a=null;for(const l of i){const f=l===v,x=l.startsWith(m);try{const o=await e(l,r);if(o.ok||o.status===304||f&&!S(o))return o;if((f||!u&&!x)&&(u=o,a=null),o!==u)try{await o.body?.cancel?.()}catch{}}catch(o){(f||!u&&!a)&&(a=o)}}if(u)return u;throw a||new Error(`model file unavailable: ${c}`)}}function M(e,{copies:n=p}={}){return n[e]||null}export{h as HF_HOST,m as MIRROR_HOST,M as modelCopy,E as modelFetch,$ as parseModelUrl,R 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
|
|
2
|
-
`)){if(!
|
|
1
|
+
import{verifyFresh as et}from"./model-integrity.js";import{modelFetch as nt}from"./model-sources.js";import{join as i}from"node:path";import{existsSync as D,mkdirSync as ot,readFileSync as rt,createWriteStream as st,renameSync as at,statSync as C}from"node:fs";import{Readable as ct}from"node:stream";import{modelRoot as Y}from"./ner-engine.js";import{getOrt as it,ortProviders as ft}from"./ort.js";const lt=new Set(["nemo-conformer-tdt","nemo-conformer-rnnt","parakeet_tdt","parakeet-tdt","parakeet_rnnt"]);function St(t){return lt.has(String(t||"").trim())}const $="int8";function V(t){return t==="fp32"?"fp32":$}function W(t){const e=V(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(Y(),...String(t).split("/"))}function ut(t,e=$){const n=E(t);if(!D(n))return!1;try{return W(e).every(r=>{const o=i(n,r);return D(o)&&C(o).size>0})}catch{return!1}}async function dt(t,e,n,{onProgress:r,log:o}={}){const a=`https://huggingface.co/${t}/resolve/main/${encodeURIComponent(e).replace(/%2F/g,"/")}`,s=await nt()(a,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`fetch ${e} → HTTP ${s.status}`);const f=Number(s.headers.get("content-length"))||0,l=i(n,`${e}.part`),u=st(l);let h=0,p=-1;const m=ct.fromWeb(s.body);m.on("data",g=>{if(h+=g.length,f){const c=Math.round(h/f*100);c!==p&&(p=c,r?.({file:e,pct:c}))}}),await new Promise((g,c)=>{m.pipe(u),u.on("finish",g),u.on("error",c),m.on("error",c)}),at(l,i(n,e)),o?.(`[parakeet] fetched ${e}`)}async function pt(t,e,{onProgress:n,log:r}={}){const o=E(t);ot(o,{recursive:!0});let a=!1;for(const s of W(e)){const f=i(o,s);D(f)&&C(f).size>0||(r?.(`[parakeet] downloading ${s}…`),await dt(t,s,o,{onProgress:n,log:r}),a=!0)}return await et(a,t,{modelsDir:Y(),log:r||(()=>{})}),o}function mt(t){const e=[];let n=-1;for(const r of rt(i(t,"vocab.txt"),"utf8").split(`
|
|
2
|
+
`)){if(!r)continue;const o=r.lastIndexOf(" ");if(o<0)continue;const a=parseInt(r.slice(o+1),10),s=r.slice(0,o);Number.isFinite(a)&&(e[a]=s.replace(/▁/g," "),s==="<blk>"&&(n=a))}return n<0&&(n=e.length-1),{vocab:e,blank:n}}function H(t,e,n){let r=e,o=t[e];for(let a=e+1;a<n;a++)t[a]>o&&(o=t[a],r=a);return r}const gt=5,K=10;async function vt({modelId:t,dtype:e=$,allowDownload:n=!0,onProgress:r,log:o=()=>{},sessionOptions:a=null}){const s=V(e),f=ut(t,s);if(!f&&!n)throw new Error("model not on disk and downloads disabled");const l=f?E(t):await pt(t,s,{onProgress:r,log:o}),u=await it(),h=s==="fp32"?"":".int8",p={executionProviders:ft(),graphOptimizationLevel:"all",logSeverityLevel:3,...a||{}},[m,g,c]=await Promise.all([u.InferenceSession.create(i(l,"nemo128.onnx"),p),u.InferenceSession.create(i(l,`encoder-model${h}.onnx`),p),u.InferenceSession.create(i(l,`decoder_joint-model${h}.onnx`),p)]),{vocab:X,blank:_}=mt(l),x=_+1,d=u.Tensor;async function q(w){if(!(w instanceof Float32Array)||w.length<400)return"";const P=w.length,I=await m.run({waveforms:new d("float32",w,[1,P]),waveforms_lens:new d("int64",BigInt64Array.from([BigInt(P)]),[1])}),O=await g.run({audio_signal:I.features,length:I.features_lens}),R=O.outputs,[,A,J]=R.dims,L=Number(O.encoded_lengths.data[0]),Q=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 Z=L*(K+1)+8;for(let S=0;b<L&&S<Z;S++){for(let v=0;v<A;v++)z[v]=Q[v*J+b];const tt=y.length?y[y.length-1]:_,F=await c.run({encoder_outputs:new d("float32",z,[1,A,1]),targets:new d("int32",Int32Array.from([tt]),[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=F.outputs.data,T=H(U,0,x),j=H(U,x,x+gt)-x;T!==_&&(M=F.output_states_1.data,N=F.output_states_2.data,y.push(T),k++),j>0?(b+=j,k=0):(T===_||k>=K)&&(b+=1,k=0)}let B="";for(const S of y)B+=X[S]??"";return B.replace(/^\s+/,"").replace(/\s+/g," ").trimEnd()}function G(){for(const w of[m,g,c])try{w.release?.()}catch{}}return{transcribe:q,dispose:G,dtype:s,dir:l}}export{$ as PARAKEET_DEFAULT_DTYPE,St as isTransducerModelType,vt as loadRecognizer,E as parakeetDir,V as parakeetDtype,ut as parakeetOnDisk};
|
package/src/segment-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as
|
|
1
|
+
import{verifyFresh as $}from"./model-integrity.js";import{existsSync as S,readdirSync as T}from"node:fs";import{join as P}from"node:path";import{ensureLib as R,modelRoot as A,withModelSource as v}from"./ner-engine.js";import{runtimeDtype as h}from"./model-runtime.js";import{makeWarmTimer as b}from"./warm-timer.js";const k="onnx-community/pyannote-segmentation-3.0",U=6,F=16e3;let n="off",g=k,f=null,c=null,s=null,m=null,a=null,o=null,_=0,p=0,w=null;function W(){return g}function X(){return n}function x(){return n==="ready"&&!!f&&!!c}function H(){return a}function J(){return{configured:n!=="off",ok:x(),state:n,model:g,loaded:!!f,error:s,warmMs:o?.warmMs??null}}function y(){return _>0||p>0||n==="loading"||n==="downloading"}function K(){p++,o?.disarm()}function Q(){p=Math.max(0,p-1),p===0&&_===0&&x()&&o?.arm()}async function E({log:e=()=>{}}={}){if(y())return!1;o?.disarm();const r=f;if(f=null,c=null,w=null,m=null,a=null,s=null,n="off",r){try{await r.dispose?.()}catch{}e("[segment] idle — model unloaded (reloads on the next diarizing session)")}return!0}function O(e=g,r=h()){const l=P(A(),...e.split("/"),"onnx");if(!S(l))return!1;const t=r==="fp32"?"":r==="q8"?"_quantized":`_${r}`;try{return T(l).some(i=>i===`model${t}.onnx`)}catch{return!1}}async function z({log:e=()=>{},allowDownload:r=!0}={}){let l;try{l=await R()}catch(u){return n="error",s=u.message,e(`[segment] engine unavailable (${u.message})`),!1}if(!l.AutoModelForAudioFrameClassification)return n="error",s="this transformers.js has no audio frame classification",e(`[segment] ${s}`),!1;const t=g,i=O(t);if(!i&&!r)return n="error",s="model not on disk and downloads disabled",!1;n=i?"loading":"downloading",i||(a={model:t,file:null,pct:0},e(`[segment] downloading ${t} (one-time)…`));try{const u=d=>{if(!d)return;const L=typeof d.progress=="number"?Math.round(d.progress):a?.pct??0;(d.status==="progress"||d.status==="download"||d.status==="initiate")&&(a={model:t,file:d.file||a?.file||null,pct:L})},{processor:D,model:M}=await v({host:i?null:"https://huggingface.co/",allowRemote:!i},async()=>({processor:await l.AutoProcessor.from_pretrained(t,{progress_callback:u}),model:await l.AutoModelForAudioFrameClassification.from_pretrained(t,{dtype:h(),progress_callback:u})}));return await $(!i,t,{modelsDir:A(),log:e,dispose:()=>M.dispose?.()}),c=D,f=M,n="ready",s=null,a=null,e(`[segment] ready — ${t} @ ${h()} (speaker turns inside a segment)`),!0}catch(u){return s=u.message,a=null,n="error",e(`[segment] load failed (${u.message}) — one speaker per segment, as before`),!1}}function j(e){return e.then(r=>(r&&!y()&&o?.arm(),r))}function V(e={}){if(m&&n!=="error")return m;n="loading";const r=typeof e.onLog=="function"?e.onLog:()=>{};return o=b({warmMs:e.warmMs,busy:y,log:r,unload:()=>E({log:r})}),m=j(z({log:r,allowDownload:e.allowDownload!==!1})),m}async function Y(e){if(!x()||!(e instanceof Float32Array)||e.length<F/2)return null;_++;try{if(w)return await w(e);const r=await c(e),{logits:l}=await f(r),t=c.post_process_speaker_diarization(l,e.length);return Array.isArray(t?.[0])?t[0]:null}catch{return null}finally{_--,y()||o?.arm()}}function Z(){o?.disarm(),o=null,p=0,_=0,n="off",g=k,f=null,c=null,s=null,m=null,a=null}function ee(e,{warmMs:r=null}={}){w=e||null,f=e?{dispose:async()=>{}}:null,c=e?{}:null,n=e?"ready":"off",r!==null&&(o=b({warmMs:r,busy:y,unload:()=>E()}),e&&o.arm())}export{k as DEFAULT_SEGMENT_MODEL,F as SAMPLE_RATE,U as SEGMENT_MODEL_APPROX_MB,Z as _reset,ee as _setForTest,W as activeModel,J as health,V as init,x as isReady,O as modelOnDisk,H as progress,Q as release,K as retain,Y as spans,X as state,E as unload};
|