// Gapiring Edge v2: the text front for the browser, a port of pocket_text in pocket_onnx.py and of the // tokenizer.json pipeline (HF tokenizers: added tokens first; Prepend "▁"; Metaspace replace + split; Unigram // Viterbi with byte fallback). tokenize_check.mjs verifies it id for id against the Python tokenizer. const EVENTS = { "[laugh]": "§", "[pause]": "¦", "[breath]": "¶", "[sigh]": "¤" }; // roles and manners by name (the symbols stay in the code): operator, the two assistants, emotional mode, narrator // assistant: a lively helper (with { hesitant: true } it hesitates a little, as people do); assistant_formal: the same // helper in an even, measured delivery; narrator: reads a longer text aloud, its manner is the genre export const ROLES = { operator: "\u2460", assistant: "\u2462", assistant_formal: "\u2463", emotional: "\u2461", narrator: "\u247a" }; export const MANNERS = { calm: "\u2464", neutral: "\u2472", warm: "\u2473", cheerful: "\u2474", empathetic: "\u2475", dictation: "\u2476", persuasive: "\u2477", brisk: "\u2478", soothing: "\u2479", angry: "\u246c", upset: "\u246e", irritated: "\u246b", worried: "\u246d", tired: "\u2470", sceptical: "\u246f", confused: "\u2469", hurried: "\u246a", joking: "\u2466", grateful: "\u2467", curious: "\u2468", friendly: "\u2465", elderly: "\u2471", serious: "\u247b", book: "\u247c", article: "\u247d", news: "\u247e", tale: "\u247f" }; export const ROLE_MANNERS = { operator: ["neutral", "warm", "cheerful", "empathetic", "calm", "dictation", "persuasive", "brisk", "serious"], assistant: ["neutral", "warm", "cheerful", "empathetic", "calm", "dictation", "soothing", "serious"], assistant_formal: ["neutral", "warm", "cheerful", "empathetic", "calm", "dictation", "soothing", "serious"], narrator: ["book", "article", "news", "tale"], emotional: ["angry", "upset", "irritated", "worried", "tired", "sceptical", "confused", "hurried", "joking", "grateful", "curious", "friendly", "calm", "elderly"] }; export const DEFAULT_MANNER = { narrator: "book" }; // every other role: neutral export const PACES = { slow: "\u2480", fast: "\u2481" }; // the manners a pace goes with, by role (the narrator: a slow article, fast news) const PACED = ["neutral", "warm", "cheerful", "calm"]; export const PACE_MANNERS = { operator: { slow: [...PACED, "persuasive"], fast: [...PACED, "persuasive"] }, assistant: { slow: PACED, fast: PACED }, assistant_formal: { slow: PACED, fast: PACED }, narrator: { slow: ["article"], fast: ["news"] } }; const SERIOUS = "\u247b", HESITANT = "\u2482", SERIOUS_GENRES = ["article", "news"]; const HESITANT_MANNERS = ["neutral", "warm", "cheerful", "empathetic", "calm", "dictation", "soothing"]; // a piece of a longer text, in characters [limit, hard] (splitText): a short paragraph for the narrator export const PIECE = { narrator: [280, 340] }; // The symbols the model reads before the text: role, manner (the narrator's genre), then one optional mark. // pace: "slow" | "fast"; serious: the narrator's article and news in a serious tone (the other roles have the manner // "serious"); hesitant: the lively assistant with small hesitations. export function tagsFor(role, manner, { pace, serious = false, hesitant = false } = {}) { manner = manner ?? DEFAULT_MANNER[role] ?? "neutral"; if (!ROLE_MANNERS[role] || !ROLE_MANNERS[role].includes(manner)) throw new Error(`role/manner ${role}/${manner}: see ROLE_MANNERS`); if ((pace != null) + !!serious + !!hesitant > 1) throw new Error("pace, serious and hesitant do not combine: give one of them"); let tags = ROLES[role] + MANNERS[manner]; if (pace != null) { if (!PACE_MANNERS[role]?.[pace]?.includes(manner)) throw new Error(`pace ${pace} with ${role}/${manner}: see PACE_MANNERS`); tags += PACES[pace]; } if (serious) { if (role !== "narrator" || !SERIOUS_GENRES.includes(manner)) throw new Error("serious: true is for the narrator's article and news; the other roles take manner 'serious'"); tags += SERIOUS; } if (hesitant) { if (role !== "assistant" || !HESITANT_MANNERS.includes(manner)) throw new Error("hesitant: true is for role 'assistant'"); tags += HESITANT; } return tags; } const MAP = { "…": "...", "«": "", "»": "", '"': "", "“": "", "”": "", "„": "", "(": "", ")": "", ":": ",", ";": "," }; // Uzbek o' and g' as phone keyboards and editors write them (U+02BB, U+02BC, curly quotes, a prime, a backtick) const APOSTROPHES = /[\u02bb\u02bc\u2018\u2019\u2032\u02b9`]/g; export function pocketText(text, tags = "") { let t = Array.from(text.replace(APOSTROPHES, "'")).map((c) => (c in MAP ? MAP[c] : c)).join(""); t = t.replace(/\s+[—–-]\s+|[—–]/g, ", "); t = t.replace(/,(\s*,)+/g, ",").replace(/\s+([,.!?])/g, "$1"); t = t.split(/\s+/).filter(Boolean).join(" "); t = t.replace(/\s*(\[(?:laugh|pause|breath|sigh)\])\s*/g, (_, m) => EVENTS[m]); return tags + t.trim(); } // The pieces a longer text is spoken in: the model speaks one sentence or a short paragraph well and loses the thread on // more. Sentences are packed into pieces of at most `limit` characters (code points); a text within the limit stays // whole; one sentence longer than `hard` is cut at its commas. The same rules, white space included, as the Python, // Kotlin and Swift runtimes. const WS = "[ \\t\\n\\x0b\\f\\r\\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]"; const SENTENCE = new RegExp(`([.!?\\u2026])["\\u201d\\u00bb)]*${WS}+|\\n+`, "g"); const CLAUSE = new RegExp(`([,;:])${WS}+|${WS}+[\\u2014\\u2013-]${WS}+`, "g"); const TRIM = new RegExp(`^${WS}+|${WS}+$`, "g"); const TAIL = /[,;:]+$/; const size = (s) => Array.from(s).length; function cut(pattern, text) { // the text between the matches; a closing mark stays with what it closes const out = []; let start = 0; for (const m of text.matchAll(pattern)) { out.push(text.slice(start, m.index + (m[1] ? 1 : 0))); start = m.index + m[0].length; } out.push(text.slice(start)); return out; } export function splitText(text, limit = 150, hard = 240) { text = text.replace(TRIM, ""); if (size(text) <= limit) return text ? [text] : []; const sentences = []; for (const raw of cut(SENTENCE, text)) { const s = raw.replace(TRIM, ""); if (!s) continue; if (size(s) <= hard) { sentences.push(s); continue; } const clauses = cut(CLAUSE, s).map((c) => c.replace(TRIM, "")).filter(Boolean); let part = ""; clauses.forEach((c, i) => { const clause = i < clauses.length - 1 ? c.replace(TAIL, "") : c; if (part && size(part) + 2 + size(clause) > limit) { sentences.push(part); part = clause; } else part = part ? `${part}, ${clause}` : clause; }); if (part) sentences.push(part); } const pieces = []; for (const s of sentences) { if (pieces.length && size(pieces[pieces.length - 1]) + 1 + size(s) <= limit) pieces[pieces.length - 1] += " " + s; else pieces.push(s); } return pieces; } export class UnigramTokenizer { constructor(json) { const m = json.model; this.pieces = new Map(); let min = Infinity, maxLen = 1; m.vocab.forEach(([p, s], i) => { this.pieces.set(p, [i, s]); if (s < min) min = s; maxLen = Math.max(maxLen, Array.from(p).length); }); this.unkScore = min - 10; this.maxLen = maxLen; this.unkId = m.unk_id; this.added = json.added_tokens.map((t) => [t.content, t.id]).sort((a, b) => b[0].length - a[0].length); this.bytes = new Map(); for (let b = 0; b < 256; b++) { const p = `<0x${b.toString(16).toUpperCase().padStart(2, "0")}>`; if (this.pieces.has(p)) this.bytes.set(b, this.pieces.get(p)[0]); } } viterbi(word) { const chars = Array.from(word), n = chars.length; const best = new Array(n + 1).fill(-Infinity), back = new Array(n + 1); best[0] = 0; for (let i = 0; i < n; i++) { if (best[i] === -Infinity) continue; let any = false, piece = ""; for (let j = i; j < Math.min(n, i + this.maxLen); j++) { piece += chars[j]; const hit = this.pieces.get(piece); if (hit) { any = any || j === i; const s = best[i] + hit[1]; if (s > best[j + 1]) { best[j + 1] = s; back[j + 1] = [i, hit[0]]; } } } if (!any) { // no piece starts with this character: unknown, later byte fallback const s = best[i] + this.unkScore; if (s > best[i + 1]) { best[i + 1] = s; back[i + 1] = [i, -1]; } } } const out = []; for (let k = n; k > 0; k = back[k][0]) { const [i, id] = back[k]; if (id === -1) { const enc = new TextEncoder().encode(chars.slice(i, k).join("")); const ids = Array.from(enc, (b) => this.bytes.get(b) ?? this.unkId); out.push(...ids.reverse()); } else out.push(id); } return out.reverse(); } encodeSegment(seg) { if (!seg) return []; let s = "▁" + seg; // Prepend normalizer s = s.replace(/ /g, "▁"); // Metaspace replacement (prepend_scheme always: already starts with ▁) const words = s.split(/(?=▁)/).filter(Boolean); // split=true: each ▁ starts a new pre-token return words.flatMap((w) => this.viterbi(w)); } encode(text) { const ids = []; let rest = text; while (rest.length) { let pos = -1, tok = null; for (const [content, id] of this.added) { const p = rest.indexOf(content); if (p !== -1 && (pos === -1 || p < pos || (p === pos && content.length > tok[0].length))) { pos = p; tok = [content, id]; } } if (pos === -1) { ids.push(...this.encodeSegment(rest)); break; } ids.push(...this.encodeSegment(rest.slice(0, pos)), tok[1]); rest = rest.slice(pos + tok[0].length); } return ids; } }