Spaces:
Running
Running
Download lm.js from Reza2kn/Shenava-Rizeh-Live: direct link, hf CLI and curl.
- Browser
- Download file 2.27 kB
-
https://huggingface.co/spaces/Reza2kn/Shenava-Rizeh-Live/resolve/main/lm.js
- Command line
-
hf download hf://spaces/Reza2kn/Shenava-Rizeh-Live/lm.js
-
curl -L -o lm.js https://huggingface.co/spaces/Reza2kn/Shenava-Rizeh-Live/resolve/main/lm.js
2.27 kB
| // Compact trigram LM for the browser (format written by arpa2bin.py): sorted float64 n-gram keys + uint8-quantized log10 probs. | |
| export class NgramLM { | |
| constructor(buf) { | |
| const dv = new DataView(buf); | |
| if (String.fromCharCode(...new Uint8Array(buf, 0, 4)) !== 'RZLM') throw new Error('bad LM file'); | |
| const hl = dv.getUint32(4, true); | |
| const h = JSON.parse(new TextDecoder().decode(new Uint8Array(buf, 8, hl))); | |
| this.h = h; const o = h.offs, NV = h.n1; this.NV = NV; | |
| const words = new TextDecoder().decode(new Uint8Array(buf, o.vocab[0], o.vocab[1])).split('\n'); | |
| this.ids = new Map(words.map((w, i) => [w, i])); | |
| this.up = new Float32Array(buf, o.up[0], NV); this.ub = new Float32Array(buf, o.ub[0], NV); | |
| this.bk = new Float64Array(buf, o.bk[0], h.n2); this.bp = new Uint8Array(buf, o.bp[0], h.n2); this.bb = new Uint8Array(buf, o.bb[0], h.n2); | |
| this.tk = new Float64Array(buf, o.tk[0], h.n3); this.tp = new Uint8Array(buf, o.tp[0], h.n3); | |
| this.ps = (h.phi - h.plo) / 255; this.bs = (h.bhi - h.blo) / 255; | |
| } | |
| static find(a, k) { let lo = 0, hi = a.length - 1; while (lo <= hi) { const m = (lo + hi) >> 1, v = a[m]; if (v === k) return m; if (v < k) lo = m + 1; else hi = m - 1; } return -1; } | |
| id(w) { const i = this.ids.get(w); return i === undefined ? this.h.unk : i; } | |
| begin() { return [-1, this.h.bos]; } | |
| /** log10 P(w | state); returns [log10p, nextState] */ | |
| score(st, w) { | |
| const [u, v] = st, NV = this.NV, h = this.h; | |
| let lp; | |
| if (u >= 0) { const i = NgramLM.find(this.tk, (u * NV + v) * NV + w); if (i >= 0) return [h.plo + this.tp[i] * this.ps, [v, w]]; } | |
| let bo = 0; | |
| if (u >= 0) { const j = NgramLM.find(this.bk, u * NV + v); if (j >= 0) bo = h.blo + this.bb[j] * this.bs; } | |
| const i2 = NgramLM.find(this.bk, v * NV + w); | |
| if (i2 >= 0) lp = h.plo + this.bp[i2] * this.ps; else lp = this.ub[v] + this.up[w]; | |
| return [bo + lp, [v, w]]; | |
| } | |
| end(st) { return this.score(st, this.h.eos)[0]; } | |
| } | |
| // same word normalisation as the tinyasr LM fusion (tbench_fz norm_tokens) | |
| export function normTokens(s) { | |
| let t = ''; | |
| for (const c of s) t += c === '' ? ' ' : c === 'ي' ? 'ی' : c === 'ك' ? 'ک' : /[\p{L}\p{N}]/u.test(c) ? c : ' '; | |
| return t.split(/\s+/).filter(Boolean); | |
| } | |