From 304f87c8d83b27d26b69fd5d647e883617ef563c Mon Sep 17 00:00:00 2001 From: Karim Masmoudi <125830216+Kernel-Hunter@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:30:51 +0100 Subject: [PATCH] Add a pronunciation list Under More, Pronunciations, people can add a word and how to say it, spelled the way it sounds ("Siobhan" as "shiv awn"). A word selected in the document is filled in, and Listen plays the spelling with the current voice. The worker replaces each listed word (whole words, any case, phrases too) before the G2P and maps the tokens back to the original text, so word timings and the highlight stay on the word on the page. It applies to playback, previews and exports. Changing the list drops the cached audio and restarts from the current word. The list is kept in local storage. Version 0.2.0, with a changelog. --- CHANGELOG.md | 10 ++ README.md | 4 +- package.json | 2 +- src/audio/player.ts | 10 ++ src/engine/client.ts | 6 ++ src/engine/g2p/pronunciations.ts | 116 +++++++++++++++++++++++ src/engine/protocol.ts | 3 + src/engine/worker.ts | 14 ++- src/store/pronunciations.ts | 38 ++++++++ src/styles/app.css | 10 ++ src/ui/app.ts | 108 ++++++++++++++++++++++ src/ui/icons.ts | 1 + tests/pronunciations.test.ts | 153 +++++++++++++++++++++++++++++++ 13 files changed, 470 insertions(+), 5 deletions(-) create mode 100644 CHANGELOG.md create mode 100644 src/engine/g2p/pronunciations.ts create mode 100644 src/store/pronunciations.ts create mode 100644 tests/pronunciations.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..cf1c4a6 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,10 @@ +# Changelog + +## 0.2.0 (3 November 2026) + +- Pronunciations. Under More, Pronunciations, add a word and how to say it, spelled the way it sounds ("Siobhan" as "shiv awn", "nginx" as "engine x"). Select a word in the document first and it is filled in. Listen plays the spelling with the current voice. The list applies to every document and voice, to audio exports, and to the sentence being read as soon as you change it. Words match whole and ignore case, and a phrase of several words works too. The list is kept in the browser's local storage. The Chrome extension does not use it yet. + +## 0.1.0 (31 October 2026) + +- First release: the web app and the Chrome extension (as a zip to load unpacked). +- The web app tells open pages when a new version is deployed, and the extension popup says when a new release is out. diff --git a/README.md b/README.md index 0263597..8f85390 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ Then open http://localhost:5330. See [Development](#development) for the other c - **Word highlighting.** The word being read is highlighted and the page follows it. Click any word to start from there. - **PDFs, EPUBs and web pages.** PDFs (on the original page, or as reflowed text), EPUB books, saved web pages, Markdown and text files, or text you paste. - **Voices that run on your device.** 28 natural voices (American and British English) and 3 fast voices for older computers. +- **Pronunciations.** Teach it how to say a name or a term by writing it the way it sounds ("Siobhan" as "shiv awn"). The list applies to every document, voice and audio export in the web app. - **Speed from 0.5x to 3x.** The pitch stays natural. - **Reading settings.** Reading font, size and line spacing, including the OpenDyslexic font. Light and dark themes. - **Remembers your place.** Every document opens where you stopped. @@ -97,7 +98,7 @@ Most other Piper voices are fine-tuned from the "lessac" voice, whose recordings ## Privacy -Everything runs in your browser. The app downloads the voice you choose from Hugging Face the first time (and the other voice only if you pick it later). While it is open, it also checks the site it was loaded from for a newer version (a small `version.json` file), and offers to reload when there is one. Apart from that it makes no network requests of its own: no analytics, no server, no account. Your documents, reading positions and settings stay in the browser's storage (IndexedDB, local storage and the Origin Private File System) and are never uploaded. Clearing the site data in your browser, or **Remove voice data** under More, About and storage, deletes them. +Everything runs in your browser. The app downloads the voice you choose from Hugging Face the first time (and the other voice only if you pick it later). While it is open, it also checks the site it was loaded from for a newer version (a small `version.json` file), and offers to reload when there is one. Apart from that it makes no network requests of its own: no analytics, no server, no account. Your documents, reading positions, settings and pronunciation list stay in the browser's storage (IndexedDB, local storage and the Origin Private File System) and are never uploaded. Clearing the site data in your browser, or **Remove voice data** under More, About and storage, deletes them. ## Chrome extension @@ -194,6 +195,7 @@ What the player does on a slow computer: - **Voice.** Kokoro-82M runs through [ONNX Runtime Web](https://onnxruntime.ai/) in a Web Worker: on the graphics chip with WebGPU when its output passes a check, otherwise on the processor with multi-threaded WebAssembly and an 8-bit version of the model. Every generated chunk is checked (NaN samples, clipping, audio that stops early), and if the graphics chip produces bad audio Narrata moves to the processor for good. The Piper voices run the same way on the processor. - **Pronunciation.** Kokoro reads phonemes, not letters. Narrata converts English with a TypeScript port of [misaki](https://github.com/hexgrad/misaki), the converter Kokoro was trained with: its American and British dictionaries, its rules for endings and numbers, a small part-of-speech tagger for words spelled alike ("I read" and "I will read") and its neural network for unknown words. It also reads clock times, common abbreviations, units and web addresses. For Piper, the same phonemes are mapped to the symbols eSpeak would produce. - **Word highlighting.** The models predict how long each phoneme lasts, and the converter knows which word each phoneme came from, so the highlight follows the voice word by word. Piper does not output these durations, so Narrata adds the output to the model graph when it loads it. +- **Your pronunciations.** Before the text goes to the phonemizer, each word on your list is replaced by the spelling you gave. The phonemes of that spelling are then credited to the original word, so the highlight stays on the word as it is written on the page. - **Speed without chipmunks.** Audio is generated at normal speed and played through [Signalsmith Stretch](https://signalsmith-audio.co.uk/code/stretch/), which keeps the pitch. All chunks go into one continuous buffer, so there are no gaps between sentences. - **Storage.** Models are saved in the Origin Private File System, so later visits load them from disk in about a second. A service worker caches the app and adds the cross-origin isolation headers that multi-threaded WebAssembly needs, which is how it runs on static hosting such as GitHub Pages. - **Documents.** [pdf.js](https://mozilla.github.io/pdf.js/) for PDFs, [Readability](https://github.com/mozilla/readability) for web pages, and a small EPUB reader built on [fflate](https://github.com/101arrowz/fflate). diff --git a/package.json b/package.json index 9a1f9b4..436a2ea 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "narrata", - "version": "0.1.0", + "version": "0.2.0", "private": true, "description": "Reads anything aloud with a natural voice that runs on your device.", "license": "MIT", diff --git a/src/audio/player.ts b/src/audio/player.ts index 956649f..3c0f133 100644 --- a/src/audio/player.ts +++ b/src/audio/player.ts @@ -514,6 +514,16 @@ export class Player { else if (this.started) this.resetPlayback(); } + /** + * Generate everything again from the current word, for a change that alters the audio but not + * the text (the pronunciation list): drops the cached audio and, while reading, restarts there. + */ + regenerate(): void { + this.cache.clear(); + if (this.state === 'playing' || this.state === 'buffering' || this.state === 'loading') void this.playFrom(this.currentOffset()); + else if (this.started) this.resetPlayback(); + } + /** Offset of the word being read (or last read). */ currentOffset(): number { if (!this.pdoc) return 0; diff --git a/src/engine/client.ts b/src/engine/client.ts index e4e375a..1eec922 100644 --- a/src/engine/client.ts +++ b/src/engine/client.ts @@ -3,6 +3,7 @@ import type { ChunkEnd } from '../core/chunker'; import type { DeviceProbe } from '../core/device'; import type { Device, EngineStatus, FromWorker, GenResult, ModelChoice, ToWorker, Tuning } from './protocol'; +import type { Pronunciation } from './g2p/pronunciations'; import type { Variant } from './model-store'; export type EngineState = 'starting' | 'needs-download' | 'downloading' | 'loading' | 'ready' | 'error'; @@ -219,6 +220,11 @@ export class TtsClient { }; } + /** Use this pronunciation list for everything generated from now on. */ + setPronunciations(list: Pronunciation[]) { + this.send({ type: 'pronunciations', list }); + } + clearModels() { this.update({ state: 'starting', device: undefined, variant: undefined }); this.send({ type: 'clear' }); diff --git a/src/engine/g2p/pronunciations.ts b/src/engine/g2p/pronunciations.ts new file mode 100644 index 0000000..5281e2d --- /dev/null +++ b/src/engine/g2p/pronunciations.ts @@ -0,0 +1,116 @@ +// The pronunciation list: words the reader wants said differently, each with a spelling of how it +// sounds ("nginx" as "engine x"). Before the G2P runs, every listed word in the text is replaced +// by its spelling; the G2P tokens are then mapped back to the original text, so the word timings +// and the highlight still point at the word on the page. + +import type { G2P, G2PResult, VoiceLang } from './types'; + +export interface Pronunciation { + /** The word or phrase as written. Matched whole, ignoring case. */ + word: string; + /** How to say it, spelled as it sounds. */ + sayAs: string; +} + +export const MAX_PRONUNCIATIONS = 500; +export const MAX_WORD_LENGTH = 60; +export const MAX_SAY_AS_LENGTH = 120; + +const clean = (s: unknown, max: number) => (typeof s === 'string' ? s.replace(/\s+/g, ' ').trim().slice(0, max) : ''); + +/** + * Trims both fields, drops entries with an empty field or a word without a letter or digit, and + * keeps only the last entry for a word (ignoring case), at its first position. + */ +export function normalizePronunciations(list: unknown): Pronunciation[] { + if (!Array.isArray(list)) return []; + const byWord = new Map(); + for (const item of list) { + const p = item as Partial | null; + const word = clean(p?.word, MAX_WORD_LENGTH); + const sayAs = clean(p?.sayAs, MAX_SAY_AS_LENGTH); + if (!word || !sayAs || !/[\p{L}\p{N}]/u.test(word)) continue; + byWord.set(word.toLocaleLowerCase(), { word, sayAs }); + } + return [...byWord.values()].slice(0, MAX_PRONUNCIATIONS); +} + +export interface Rewrite { + /** The text with every listed word replaced by its spelling. */ + text: string; + /** Whether anything was replaced. */ + changed: boolean; + /** Offset in the original text where a token starting at `i` of the new text starts. */ + start(i: number): number; + /** Offset in the original text where a token ending at `i` of the new text ends. */ + end(i: number): number; +} + +const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + +/** A compiled pronunciation list. */ +export class Pronouncer { + private readonly re: RegExp | null; + private readonly sayAs = new Map(); + + constructor(list: Pronunciation[]) { + const rules = normalizePronunciations(list); + for (const r of rules) this.sayAs.set(r.word.toLocaleLowerCase(), r.sayAs); + // Longer words first, so "New York City" wins over "New York". A word only matches whole: + // not inside a longer word, but "nginx's" and "nginx," still match. + const words = rules.map((r) => r.word).sort((a, b) => b.length - a.length); + this.re = words.length ? new RegExp(`(? escape(w).replace(/ /g, '\\s+')).join('|')})(?![\\p{L}\\p{N}])`, 'giu') : null; + } + + get size(): number { + return this.sayAs.size; + } + + rewrite(text: string): Rewrite { + const n = text.length; + if (!this.re) return { text, changed: false, start: (i) => Math.min(i, n), end: (i) => Math.min(i, n) }; + let out = ''; + const starts: number[] = []; + const ends: number[] = [0]; + let last = 0; + let matched = false; + const copy = (from: number, to: number) => { + for (let o = from; o < to; o++) { + starts.push(o); + ends.push(o + 1); + } + out += text.slice(from, to); + }; + for (const m of text.matchAll(this.re)) { + const key = m[0].replace(/\s+/g, ' ').toLocaleLowerCase(); + const say = this.sayAs.get(key); + if (say === undefined) continue; + const s = m.index!; + const e = s + m[0].length; + copy(last, s); + for (let k = 0; k < say.length; k++) { + starts.push(s); + ends.push(e); + } + out += say; + last = e; + matched = true; + } + if (!matched) return { text, changed: false, start: (i) => Math.min(i, n), end: (i) => Math.min(i, n) }; + copy(last, n); + starts.push(n); + const clamp = (i: number) => Math.max(0, Math.min(i, out.length)); + return { text: out, changed: true, start: (i) => starts[clamp(i)], end: (i) => ends[clamp(i)] }; + } +} + +/** + * Phonemes for `text` with the pronunciation list applied. Token offsets point into `text`: a + * token that came from a spelling covers the whole listed word it replaced. + */ +export async function phonemizeWith(g2p: G2P, pronouncer: Pronouncer, text: string, lang: VoiceLang): Promise { + const r = pronouncer.rewrite(text); + if (!r.changed) return g2p.phonemize(text, lang); + const g = await g2p.phonemize(r.text, lang); + return { phonemes: g.phonemes, tokens: g.tokens.map((t) => ({ ...t, start: r.start(t.start), end: Math.max(r.start(t.start), r.end(t.end)) })) }; +} diff --git a/src/engine/protocol.ts b/src/engine/protocol.ts index 2851ece..009aba1 100644 --- a/src/engine/protocol.ts +++ b/src/engine/protocol.ts @@ -1,5 +1,6 @@ import type { ChunkEnd } from '../core/chunker'; import type { DeviceProbe } from '../core/device'; +import type { Pronunciation } from './g2p/pronunciations'; import type { Variant } from './model-store'; import type { SessionTuning } from './runtime'; @@ -71,6 +72,8 @@ export type ToWorker = | ExportRequest | { type: 'export-cancel'; id: number } | { type: 'clear' } + /** Replace the pronunciation list (applies to chunks generated from now on). */ + | { type: 'pronunciations'; list: Pronunciation[] } /** Run the device check again (on the first run it replaces the one made at start). */ | { type: 'probe' }; diff --git a/src/engine/worker.ts b/src/engine/worker.ts index eda1870..3515b7e 100644 --- a/src/engine/worker.ts +++ b/src/engine/worker.ts @@ -9,7 +9,8 @@ import { cpuVariant as pickCpuVariant, threadCount as pickThreads } from '../cor import { tokenizeWords } from '../core/text'; import { fetchData } from './g2p/assets'; import { EnglishG2P } from './g2p/english'; -import type { G2P, PhonemeToken } from './g2p/types'; +import { Pronouncer, phonemizeWith } from './g2p/pronunciations'; +import type { G2P, PhonemeToken, VoiceLang } from './g2p/types'; import { MODEL_FILES, ModelStore, PIPER_SOURCE, SUPPORT_FILES, VOICE_BYTES, downloadSize, voicePath, type Variant } from './model-store'; import { PiperModel, phonemeDurations, piperInput, resample, type PiperConfig } from './piper/piper'; import { createSession, loadRuntime, type OrtModule, type Session } from './runtime'; @@ -28,6 +29,9 @@ const TEST_SENTENCE = 'Hello! This is a short test of the voice, to check that e const store = new ModelStore(); const piperStore = new ModelStore(PIPER_SOURCE); const g2p: G2P = new EnglishG2P(fetchData); +/** The reader's pronunciation list, applied to every chunk before the G2P. */ +let pronouncer = new Pronouncer([]); +const phonemize = (text: string, lang: VoiceLang) => phonemizeWith(g2p, pronouncer, text, lang); let model: Session | null = null; /** The Kokoro model to load when a Kokoro voice is used (set by prepare). */ let kokoroPlan: { variant: Variant; device: Device } | null = null; @@ -301,7 +305,7 @@ function modelPhonemes(tokens: PhonemeToken[]): { phonemes: string[]; owner: num /** Generate one piece of text with a Piper voice (resampled to the app's sample rate). */ async function synthesizePiper(text: string, v: PiperVoice): Promise { const pm = await ensurePiper(v); - const g = await g2p.phonemize(text, v.lang); + const g = await phonemize(text, v.lang); const input = piperInput(g.tokens, v.lang === 'b', pm.config.phoneme_id_map); const textWords = tokenizeWords(text); if (!input.phonemes.length) return { audio: new Float32Array(Math.round(SAMPLE_RATE * 0.1)), timing: { starts: textWords.map(() => 0), ends: textWords.map(() => 0), speechEnd: 0, method: 'proportional' } }; @@ -327,7 +331,7 @@ async function synthesize(text: string, voiceId: string): Promise { async function synthesizeKokoro(text: string, voiceId: string): Promise { const v = voiceById(voiceId); const voice = await ensureVoice(v.id); - const g = await g2p.phonemize(text, v.lang); + const g = await phonemize(text, v.lang); const { phonemes, owner, dropped } = modelPhonemes(g.tokens); if (dropped) console.warn(`Narrata: ${dropped} phoneme symbols are not in the voice model's vocabulary`, g.phonemes); const textWords = tokenizeWords(text); @@ -517,6 +521,10 @@ self.onmessage = async (e: MessageEvent) => { post({ type: 'status', status: status(m.choice) }); break; } + case 'pronunciations': + // Chunks already queued keep the old list; the player asks for them again (Player.restart). + pronouncer = new Pronouncer(m.list); + break; case 'select': lastChoice = m.choice; selected = m.voice; diff --git a/src/store/pronunciations.ts b/src/store/pronunciations.ts new file mode 100644 index 0000000..8a83f74 --- /dev/null +++ b/src/store/pronunciations.ts @@ -0,0 +1,38 @@ +// The pronunciation list, kept in local storage next to the settings. It never leaves the browser. + +import { normalizePronunciations, type Pronunciation } from '../engine/g2p/pronunciations'; + +const KEY = 'narrata.pronunciations'; + +export function loadPronunciations(storage: Storage | null = safeStorage()): Pronunciation[] { + try { + const raw = storage?.getItem(KEY); + return raw ? normalizePronunciations(JSON.parse(raw)) : []; + } catch { + return []; + } +} + +export function savePronunciations(list: Pronunciation[], storage: Storage | null = safeStorage()): void { + try { + storage?.setItem(KEY, JSON.stringify(normalizePronunciations(list))); + } catch { + // Private mode or storage disabled: the list lasts for this session only. + } +} + +/** Adds or replaces the entry for a word (ignoring case); a replaced entry keeps its place. */ +export function upsertPronunciation(list: Pronunciation[], entry: Pronunciation): Pronunciation[] { + const key = entry.word.trim().toLocaleLowerCase(); + const i = list.findIndex((p) => p.word.toLocaleLowerCase() === key); + const next = i >= 0 ? list.map((p, j) => (j === i ? entry : p)) : [entry, ...list]; + return normalizePronunciations(next); +} + +function safeStorage(): Storage | null { + try { + return typeof localStorage === 'undefined' ? null : localStorage; + } catch { + return null; + } +} diff --git a/src/styles/app.css b/src/styles/app.css index 0093916..e2901f7 100644 --- a/src/styles/app.css +++ b/src/styles/app.css @@ -784,6 +784,14 @@ dialog.sheet[open] { animation: pop-in 0.2s var(--ease); } background: var(--paper); margin-bottom: 10px; } +.pron-form { margin: 0; } +.pron-fields { display: grid; grid-template-columns: 1fr 1fr; gap: 0 10px; } +.pron-actions { display: flex; gap: 8px; justify-content: flex-end; } +.pron-list { list-style: none; margin: 18px 0 0; padding: 6px 0 0; border-top: 1px solid var(--line); max-height: min(320px, 40dvh); overflow-y: auto; } +.pron-row { display: flex; align-items: center; gap: 6px; padding: 4px 0; } +.pron-word { flex: 0 1 38%; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; } +.sheet .pron-row input[type='text'] { flex: 1 1 auto; min-width: 0; width: auto; height: 38px; margin: 0; } +.pron-row .icon-btn { flex: none; } .kbd-list { display: grid; grid-template-columns: auto 1fr; gap: 10px 16px; margin: 0; } .kbd-list dt { text-align: right; } .kbd-list dd { margin: 0; color: var(--ink-2); } @@ -881,6 +889,8 @@ kbd { .pdf-view { gap: 10px; } .pdf-page { border-radius: 3px; } .doc-delete { opacity: 1; } + .pron-fields { grid-template-columns: 1fr; } + .pron-word { flex-basis: 34%; white-space: normal; overflow-wrap: anywhere; } } @media (prefers-reduced-motion: reduce) { diff --git a/src/ui/app.ts b/src/ui/app.ts index ff6aaa9..6756323 100644 --- a/src/ui/app.ts +++ b/src/ui/app.ts @@ -7,10 +7,12 @@ import { lastAtOrBefore, tokenizeWords, wordIndexAt } from '../core/text'; import { ACCEPT, loadFile, loadPastedText } from '../docs'; import type { LoadedDoc } from '../docs/types'; import { TtsClient, type EngineInfo } from '../engine/client'; +import { MAX_SAY_AS_LENGTH, MAX_WORD_LENGTH, type Pronunciation } from '../engine/g2p/pronunciations'; import { downloadSize, type Variant } from '../engine/model-store'; import type { Tuning } from '../engine/protocol'; import { DEFAULT_VOICE, PIPER_VOICES, VOICES, accentLabel, fastVoiceFor, isPiper, voiceById } from '../engine/voices'; import { Library, type DocMeta } from '../store/library'; +import { loadPronunciations, savePronunciations, upsertPronunciation } from '../store/pronunciations'; import { loadSettings, saveSettings, type Settings } from '../store/settings'; import { h, isTypingTarget, prefersReducedMotion } from './dom'; import { icons, logo } from './icons'; @@ -62,6 +64,7 @@ const RATE_PRESETS = [0.75, 1, 1.25, 1.5, 1.75, 2, 2.5, 3]; export class App { settings: Settings = loadSettings(); + pronunciations: Pronunciation[] = loadPronunciations(); readonly tts: TtsClient; readonly player: Player; readonly library = new Library(); @@ -91,6 +94,7 @@ export class App { constructor(root: HTMLElement) { this.applyAppearance(); this.tts = new TtsClient(this.settings.model, this.settings.voice, tuningFromUrl()); + if (this.pronunciations.length) this.tts.setPronunciations(this.pronunciations); this.player = new Player(this.tts, { onState: (s) => this.onPlayerState(s), onWord: (w) => this.onWord(w), @@ -1246,6 +1250,7 @@ export class App { h( 'div', { class: 'pop-section' }, + item(icons.pronounce, 'Pronunciations', this.pronunciations.length ? `${this.pronunciations.length} word${this.pronunciations.length === 1 ? '' : 's'}` : 'Teach Narrata how to say a word', () => this.pronunciationsDialog()), item(icons.download, 'Export audio', this.doc ? 'Save this document as an audio file' : 'Open a document first', () => void this.exportDialog(), !this.doc), item(icons.keyboard, 'Keyboard shortcuts', null, () => this.shortcutsDialog()), item(icons.info, 'About and storage', null, () => this.aboutDialog()), @@ -1278,6 +1283,109 @@ export class App { area.focus(); } + /** Replace the pronunciation list: save it, send it to the voice and redo the audio from here. */ + setPronunciations(list: Pronunciation[]) { + this.pronunciations = list; + savePronunciations(list); + this.tts.setPronunciations(list); + this.player.regenerate(); + } + + /** A short text selected in the document, to start a pronunciation with. */ + private selectedWord(): string { + const sel = window.getSelection(); + if (!sel || sel.isCollapsed || !this.doc || !sel.anchorNode || !this.doc.view.el.contains(sel.anchorNode)) return ''; + const text = sel.toString().replace(/\s+/g, ' ').trim().replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, ''); + return text.length <= MAX_WORD_LENGTH ? text : ''; + } + + /** Say a piece of text with the current voice (pauses reading, like the voice preview). */ + private async sayAloud(text: string, btn: HTMLButtonElement) { + if (!text.trim()) return; + if (!this.tts.ready) { + if (this.tts.info.state === 'needs-download' && !(await this.confirmDownload())) return; + await this.tts.prepare(this.settings.model, this.settings.voice).catch(() => {}); + if (!this.tts.ready) return; + } + btn.setAttribute('aria-busy', 'true'); + btn.innerHTML = icons.spinner; + try { + await this.tts.ensureVoice(this.settings.voice); + await this.player.preview(this.settings.voice, text, () => (btn.innerHTML = icons.speaker)); + } catch (e) { + toast(`Could not play it: ${(e as Error).message}`, { error: true }); + } finally { + btn.removeAttribute('aria-busy'); + btn.innerHTML = icons.play; + } + } + + private pronunciationsDialog() { + const word = h('input', { type: 'text', placeholder: 'Word, as written', 'aria-label': 'Word', maxlength: MAX_WORD_LENGTH, value: this.selectedWord(), autocomplete: 'off', spellcheck: 'false' }) as HTMLInputElement; + const sayAs = h('input', { type: 'text', placeholder: 'Say it as', 'aria-label': 'Say it as', maxlength: MAX_SAY_AS_LENGTH, autocomplete: 'off', spellcheck: 'false' }) as HTMLInputElement; + const listenBtn = h('button', { class: 'btn', type: 'button', 'aria-label': 'Listen', title: 'Listen', html: `${icons.play}Listen` }) as HTMLButtonElement; + const addBtn = h('button', { class: 'btn btn-primary', type: 'submit' }, 'Add') as HTMLButtonElement; + const list = h('ul', { class: 'pron-list', 'aria-label': 'Your pronunciations' }); + const icon = (html: string, label: string, onclick: (b: HTMLButtonElement) => void) => { + const b = h('button', { class: 'icon-btn', type: 'button', 'aria-label': label, title: label, html }) as HTMLButtonElement; + b.addEventListener('click', () => onclick(b)); + return b; + }; + const renderList = () => { + list.replaceChildren( + ...this.pronunciations.map((p) => { + const input = h('input', { type: 'text', value: p.sayAs, 'aria-label': `Say ${p.word} as`, maxlength: MAX_SAY_AS_LENGTH, autocomplete: 'off', spellcheck: 'false' }) as HTMLInputElement; + input.addEventListener('change', () => { + if (!input.value.trim()) { + input.value = p.sayAs; + return; + } + this.setPronunciations(upsertPronunciation(this.pronunciations, { word: p.word, sayAs: input.value })); + }); + return h( + 'li', + { class: 'pron-row' }, + h('span', { class: 'pron-word', title: p.word }, p.word), + input, + icon(icons.play, `Listen to ${p.word}`, (b) => void this.sayAloud(input.value, b)), + icon(icons.trash, `Remove ${p.word}`, () => { + this.setPronunciations(this.pronunciations.filter((x) => x.word.toLocaleLowerCase() !== p.word.toLocaleLowerCase())); + renderList(); + word.focus(); + }), + ); + }), + ); + list.hidden = this.pronunciations.length === 0; + }; + const sync = () => { + addBtn.disabled = !word.value.trim() || !sayAs.value.trim(); + listenBtn.disabled = !sayAs.value.trim(); + }; + word.addEventListener('input', sync); + sayAs.addEventListener('input', sync); + listenBtn.addEventListener('click', () => void this.sayAloud(sayAs.value, listenBtn)); + const form = h('form', { class: 'pron-form' }, h('div', { class: 'pron-fields' }, word, sayAs), h('div', { class: 'pron-actions' }, listenBtn, addBtn)); + form.addEventListener('submit', (e) => { + e.preventDefault(); + if (addBtn.disabled) return; + this.setPronunciations(upsertPronunciation(this.pronunciations, { word: word.value, sayAs: sayAs.value })); + word.value = ''; + sayAs.value = ''; + sync(); + renderList(); + word.focus(); + }); + sync(); + renderList(); + sheet('Pronunciations', [ + h('p', { class: 'sheet-text' }, 'Tell Narrata how to say a word: write it the way it sounds, such as “nginx” as “engine x”. It applies to every document and voice, and stays in this browser.'), + form, + list, + ]); + (word.value ? sayAs : word).focus(); + } + private shortcutsDialog() { const row = (keys: string[], text: string) => [h('dt', {}, ...keys.flatMap((k, i) => [i ? ' ' : '', h('kbd', {}, k)])), h('dd', {}, text)]; sheet('Keyboard shortcuts', [ diff --git a/src/ui/icons.ts b/src/ui/icons.ts index dd003c7..121d168 100644 --- a/src/ui/icons.ts +++ b/src/ui/icons.ts @@ -32,6 +32,7 @@ export const icons = { stop: ``, spinner: ``, keyboard: svg(''), + pronounce: svg(''), info: svg(''), }; diff --git a/tests/pronunciations.test.ts b/tests/pronunciations.test.ts new file mode 100644 index 0000000..e1592cc --- /dev/null +++ b/tests/pronunciations.test.ts @@ -0,0 +1,153 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { tokenTimings } from '../src/core/align'; +import { tokenizeWords } from '../src/core/text'; +import { EnglishG2P } from '../src/engine/g2p/english'; +import type { DataLoader } from '../src/engine/g2p/misaki/data'; +import { MAX_PRONUNCIATIONS, Pronouncer, normalizePronunciations, phonemizeWith } from '../src/engine/g2p/pronunciations'; +import { loadPronunciations, savePronunciations, upsertPronunciation } from '../src/store/pronunciations'; + +const dataDir = join(__dirname, '../src/engine/g2p/data'); +const load: DataLoader = async (name) => { + const b = readFileSync(join(dataDir, name)); + return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer; +}; +const g2p = new EnglishG2P(load); + +class MemoryStorage { + private m = new Map(); + getItem(k: string) { + return this.m.get(k) ?? null; + } + setItem(k: string, v: string) { + this.m.set(k, v); + } +} + +describe('normalizePronunciations', () => { + it('trims, drops empty entries and keeps the last entry for a word', () => { + expect( + normalizePronunciations([ + { word: ' nginx ', sayAs: ' engine x ' }, + { word: '', sayAs: 'x' }, + { word: 'GIF', sayAs: '' }, + { word: '!!', sayAs: 'bang bang' }, + { word: 'NGINX', sayAs: 'engine ex' }, + null, + 'nonsense', + ]), + ).toEqual([{ word: 'NGINX', sayAs: 'engine ex' }]); + expect(normalizePronunciations('not a list')).toEqual([]); + }); + + it('caps the list length', () => { + const many = Array.from({ length: MAX_PRONUNCIATIONS + 20 }, (_, i) => ({ word: `w${i}`, sayAs: 'x' })); + expect(normalizePronunciations(many)).toHaveLength(MAX_PRONUNCIATIONS); + }); +}); + +describe('Pronouncer.rewrite', () => { + const p = new Pronouncer([ + { word: 'nginx', sayAs: 'engine x' }, + { word: 'New York', sayAs: 'Noo Yawk' }, + { word: 'New York City', sayAs: 'the big apple' }, + { word: 'C++', sayAs: 'C plus plus' }, + ]); + + it('replaces whole words, ignoring case', () => { + expect(p.rewrite('Run NGINX, then nginx\'s config.').text).toBe("Run engine x, then engine x's config."); + expect(p.rewrite('nginxes and unginx stay').changed).toBe(false); + expect(p.rewrite('I wrote C++ today.').text).toBe('I wrote C plus plus today.'); + }); + + it('prefers the longest phrase and allows any spacing inside it', () => { + expect(p.rewrite('In New York City now.').text).toBe('In the big apple now.'); + expect(p.rewrite('In New\nYork today.').text).toBe('In Noo Yawk today.'); + }); + + it('maps offsets in the new text back to the original', () => { + const text = 'Use nginx here.'; + const r = p.rewrite(text); + expect(r.text).toBe('Use engine x here.'); + // "Use" is unchanged. + expect([r.start(0), r.end(3)]).toEqual([0, 3]); + // "engine" and "x" both cover "nginx". + const engine = r.text.indexOf('engine'); + expect([r.start(engine), r.end(engine + 6)]).toEqual([4, 9]); + const x = r.text.indexOf('x '); + expect([r.start(x), r.end(x + 1)]).toEqual([4, 9]); + // "here" and the full stop shift back. + const here = r.text.indexOf('here'); + expect(text.slice(r.start(here), r.end(here + 4))).toBe('here'); + expect([r.start(r.text.length), r.end(r.text.length)]).toEqual([text.length, text.length]); + }); + + it('leaves text alone when the list is empty', () => { + const r = new Pronouncer([]).rewrite('Nothing to do.'); + expect(r.changed).toBe(false); + expect(r.text).toBe('Nothing to do.'); + }); +}); + +describe('phonemizeWith', () => { + it('reads a listed word as its spelling and keeps the tokens on the original text', async () => { + const p = new Pronouncer([{ word: 'nginx', sayAs: 'engine x' }]); + const text = 'Restart nginx now.'; + const g = await phonemizeWith(g2p, p, text, 'a'); + const expected = await g2p.phonemize('Restart engine x now.', 'a'); + expect(g.phonemes).toBe(expected.phonemes); + const nginx = { start: text.indexOf('nginx'), end: text.indexOf('nginx') + 5 }; + const covering = g.tokens.filter((t) => t.start === nginx.start && t.end === nginx.end); + expect(covering.map((t) => t.phonemes).join(' ')).toBe(expected.tokens.filter((t) => /^(engine|x)$/.test('Restart engine x now.'.slice(t.start, t.end))).map((t) => t.phonemes).join(' ')); + for (const t of g.tokens) expect(t.end).toBeLessThanOrEqual(text.length); + }); + + it('gives every word of the original text a time, in order', async () => { + const p = new Pronouncer([{ word: 'nginx', sayAs: 'engine x' }]); + const text = 'Restart nginx now.'; + const g = await phonemizeWith(g2p, p, text, 'a'); + // One model token per phoneme character, as in the worker; every phoneme lasts 2 frames. + const phonemes: string[] = []; + const owner: number[] = []; + g.tokens.forEach((t, i) => { + for (const c of t.phonemes) { + phonemes.push(c); + owner.push(i); + } + if (t.whitespace) { + phonemes.push(' '); + owner.push(-1); + } + }); + const durations = [1, ...phonemes.map(() => 2), 1]; + const words = tokenizeWords(text); + const timing = tokenTimings({ words, tokens: g.tokens, phonemes, owner, durations, samples: 24000, sampleRate: 24000 }); + expect(timing).not.toBeNull(); + expect(timing!.starts).toHaveLength(3); + expect(timing!.starts[0]).toBeLessThan(timing!.starts[1]); + expect(timing!.starts[1]).toBeLessThan(timing!.starts[2]); + }); +}); + +describe('pronunciation storage', () => { + it('saves, loads and updates the list', () => { + const storage = new MemoryStorage() as unknown as Storage; + expect(loadPronunciations(storage)).toEqual([]); + let list = upsertPronunciation([], { word: 'nginx', sayAs: 'engine x' }); + list = upsertPronunciation(list, { word: 'Saoirse', sayAs: 'sur sha' }); + list = upsertPronunciation(list, { word: 'NGINX', sayAs: 'engine ex' }); + expect(list).toEqual([ + { word: 'Saoirse', sayAs: 'sur sha' }, + { word: 'NGINX', sayAs: 'engine ex' }, + ]); + savePronunciations(list, storage); + expect(loadPronunciations(storage)).toEqual(list); + }); + + it('ignores a broken stored value', () => { + const storage = new MemoryStorage() as unknown as Storage; + storage.setItem('narrata.pronunciations', '{oops'); + expect(loadPronunciations(storage)).toEqual([]); + }); +});