Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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).
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
10 changes: 10 additions & 0 deletions src/audio/player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
6 changes: 6 additions & 0 deletions src/engine/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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' });
Expand Down
116 changes: 116 additions & 0 deletions src/engine/g2p/pronunciations.ts
Original file line number Diff line number Diff line change
@@ -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<string, Pronunciation>();
for (const item of list) {
const p = item as Partial<Pronunciation> | 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<string, string>();

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(`(?<![\\p{L}\\p{N}])(?:${words.map((w) => 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<G2PResult> {
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)) })) };
}
3 changes: 3 additions & 0 deletions src/engine/protocol.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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' };

Expand Down
14 changes: 11 additions & 3 deletions src/engine/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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;
Expand Down Expand Up @@ -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<Synth> {
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' } };
Expand All @@ -327,7 +331,7 @@ async function synthesize(text: string, voiceId: string): Promise<Synth> {
async function synthesizeKokoro(text: string, voiceId: string): Promise<Synth> {
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);
Expand Down Expand Up @@ -517,6 +521,10 @@ self.onmessage = async (e: MessageEvent<ToWorker>) => {
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;
Expand Down
38 changes: 38 additions & 0 deletions src/store/pronunciations.ts
Original file line number Diff line number Diff line change
@@ -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;
}
}
10 changes: 10 additions & 0 deletions src/styles/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -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); }
Expand Down Expand Up @@ -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) {
Expand Down
Loading
Loading