pi-reply-reader 0.0.0-stage → 0.1.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/CHANGELOG.md +57 -0
- package/LICENSE +21 -0
- package/README.md +347 -2
- package/dist/bin/reply-reader.js +49 -0
- package/dist/src/cli.js +202 -0
- package/dist/src/outputs.js +61 -0
- package/dist/src/playback.js +245 -0
- package/dist/src/reading-lock.js +143 -0
- package/dist/src/settings.js +97 -0
- package/dist/src/speech-text.js +511 -0
- package/dist/src/voice.js +173 -0
- package/examples/reply-reader-desktop-audio.service +44 -0
- package/extensions/reply-reader.ts +464 -0
- package/package.json +70 -4
- package/src/cli.ts +225 -0
- package/src/outputs.ts +73 -0
- package/src/playback.ts +292 -0
- package/src/questions.ts +19 -0
- package/src/reader-events.ts +44 -0
- package/src/reading-lock.ts +167 -0
- package/src/replies.ts +64 -0
- package/src/sections.ts +47 -0
- package/src/settings.ts +94 -0
- package/src/sherpa-onnx-node.d.ts +29 -0
- package/src/speech-text.ts +579 -0
- package/src/voice.ts +195 -0
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { configFile } from "./outputs.js";
|
|
4
|
+
/** Supertonic's voice speed when none is saved (S3, L46). */
|
|
5
|
+
export const DEFAULT_SPEED = 1.1;
|
|
6
|
+
export const MIN_SPEED = 0.5;
|
|
7
|
+
export const MAX_SPEED = 2;
|
|
8
|
+
/** What `/read-speed` offers without a number. */
|
|
9
|
+
export const SPEED_CHOICES = ["0.8", "0.9", "1.0", "1.1", "1.2", "1.3", "1.5"];
|
|
10
|
+
export const SPEED_HINT = "Speed must be a number from 0.5 to 2.0.";
|
|
11
|
+
const SETTINGS = "settings.json";
|
|
12
|
+
/** Digits with an optional decimal part after a period or a comma, or only the decimal part (".9", ",9"). */
|
|
13
|
+
const NUMBER = /^(?:\d+(?:[.,]\d+)?|[.,]\d+)$/;
|
|
14
|
+
const inRange = (value) => typeof value === "number" && Number.isFinite(value) && value >= MIN_SPEED && value <= MAX_SPEED;
|
|
15
|
+
/** A speed typed by the user ("1.15", "1,15" or ".9"), or undefined when it is not one from 0.5 to 2.0. */
|
|
16
|
+
export function parseSpeed(text) {
|
|
17
|
+
const trimmed = text.trim();
|
|
18
|
+
if (!NUMBER.test(trimmed))
|
|
19
|
+
return undefined;
|
|
20
|
+
const value = Number(trimmed.replace(",", "."));
|
|
21
|
+
return inRange(value) ? value : undefined;
|
|
22
|
+
}
|
|
23
|
+
/** "1.15", and whole numbers with one decimal ("1.0", "2.0") as the selector shows them. */
|
|
24
|
+
export function formatSpeed(speed) {
|
|
25
|
+
return Number.isInteger(speed) ? speed.toFixed(1) : String(speed);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The saved speed from `$XDG_CONFIG_HOME/pi-reply-reader/settings.json`. A missing file, folder or key means
|
|
29
|
+
* the default with no problem; an unreadable or invalid file, or a speed out of range, means the default and
|
|
30
|
+
* a `problem` for the user. Nothing throws.
|
|
31
|
+
*/
|
|
32
|
+
export function loadSpeed(env) {
|
|
33
|
+
const path = configFile(env, SETTINGS);
|
|
34
|
+
if (!path)
|
|
35
|
+
return { speed: DEFAULT_SPEED };
|
|
36
|
+
const ignored = (reason) => ({ speed: DEFAULT_SPEED, problem: `Ignored ${path}: ${reason}. Readings use speed ${formatSpeed(DEFAULT_SPEED)}.` });
|
|
37
|
+
let raw;
|
|
38
|
+
try {
|
|
39
|
+
raw = readFileSync(path, "utf8");
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
if (error.code === "ENOENT")
|
|
43
|
+
return { speed: DEFAULT_SPEED };
|
|
44
|
+
return ignored(`cannot be read (${error.message})`);
|
|
45
|
+
}
|
|
46
|
+
let parsed;
|
|
47
|
+
try {
|
|
48
|
+
parsed = JSON.parse(raw);
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
return ignored(`not valid JSON (${error.message})`);
|
|
52
|
+
}
|
|
53
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
54
|
+
return ignored("expected an object");
|
|
55
|
+
if (!("speed" in parsed))
|
|
56
|
+
return { speed: DEFAULT_SPEED };
|
|
57
|
+
const { speed } = parsed;
|
|
58
|
+
return inRange(speed) ? { speed } : ignored("speed must be a number from 0.5 to 2.0");
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Saves `speed` in settings.json, keeping every other key. Throws an Error naming the file and why when it
|
|
62
|
+
* cannot; an existing file that is not a JSON object is left as it is rather than overwritten.
|
|
63
|
+
*/
|
|
64
|
+
export function saveSpeed(env, speed) {
|
|
65
|
+
const path = configFile(env, SETTINGS);
|
|
66
|
+
if (!path)
|
|
67
|
+
throw new Error(`it was not saved: no config folder (set XDG_CONFIG_HOME or HOME to an absolute path)`);
|
|
68
|
+
const fail = (reason) => new Error(`it was not saved to ${path}: ${reason}`);
|
|
69
|
+
let settings = {};
|
|
70
|
+
let raw;
|
|
71
|
+
try {
|
|
72
|
+
raw = readFileSync(path, "utf8");
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
if (error.code !== "ENOENT")
|
|
76
|
+
throw fail(error.message);
|
|
77
|
+
}
|
|
78
|
+
if (raw !== undefined) {
|
|
79
|
+
let parsed;
|
|
80
|
+
try {
|
|
81
|
+
parsed = JSON.parse(raw);
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
throw fail("it is not valid JSON");
|
|
85
|
+
}
|
|
86
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
87
|
+
throw fail("it is not a JSON object");
|
|
88
|
+
settings = parsed;
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
92
|
+
writeFileSync(path, `${JSON.stringify({ ...settings, speed }, null, 2)}\n`);
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
throw fail(error.message);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -0,0 +1,511 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turns a Markdown reply into text meant to be heard: the syntax a voice would read literally
|
|
3
|
+
* ("asterisco asterisco", "or col 1 or", "comilla simple") is removed and the words are kept.
|
|
4
|
+
* Deterministic and model-free, so the same reply always sounds the same.
|
|
5
|
+
*/
|
|
6
|
+
export function speechText(markdown, language) {
|
|
7
|
+
return speechReading(markdown, language).text;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* The cleaned text plus the language its added words are in (S7). Pass `language` when `markdown` is part
|
|
11
|
+
* of a larger text (a section, the closing questions), so the part follows the language of the whole.
|
|
12
|
+
*/
|
|
13
|
+
export function speechReading(markdown, language = detectLanguage(markdown)) {
|
|
14
|
+
const previous = words;
|
|
15
|
+
words = PHRASEBOOKS[language];
|
|
16
|
+
try {
|
|
17
|
+
return { text: cleaned(markdown, language), language };
|
|
18
|
+
}
|
|
19
|
+
finally {
|
|
20
|
+
words = previous;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* (S7) English or Spanish, from the text's own function words; code, URLs and paths do not count.
|
|
25
|
+
* Spanish wins ties, so a reply with no clear English majority reads as it always did.
|
|
26
|
+
*/
|
|
27
|
+
export function detectLanguage(markdown) {
|
|
28
|
+
const prose = markdown
|
|
29
|
+
.replace(/^\s{0,3}(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^\s{0,3}\1[^\n]*$|(?![\s\S]))/gm, " ")
|
|
30
|
+
// The closing heading every reply here uses is English even in a Spanish reply.
|
|
31
|
+
.replace(/^\s*(?:#{1,6}\s+|\*\*|__)?needs your decision:?(?:\*\*|__)?\s*$/gim, " ")
|
|
32
|
+
.replace(/(`+)[\s\S]+?\1/g, " ")
|
|
33
|
+
.replace(/\S*(?::\/\/|[/\\~])\S*/g, " ")
|
|
34
|
+
.toLowerCase();
|
|
35
|
+
let english = 0;
|
|
36
|
+
let spanish = 0;
|
|
37
|
+
for (const [word] of prose.matchAll(/\p{L}+/gu)) {
|
|
38
|
+
if (ENGLISH_WORDS.has(word))
|
|
39
|
+
english++;
|
|
40
|
+
else if (SPANISH_WORDS.has(word))
|
|
41
|
+
spanish++;
|
|
42
|
+
}
|
|
43
|
+
return english > spanish ? "en" : "es";
|
|
44
|
+
}
|
|
45
|
+
/** Common function words found in one language only ("a", "no" and "me" are in both and count for neither). */
|
|
46
|
+
const ENGLISH_WORDS = new Set("the and of to is are was were be been being it its this that these those with for from on at by an as or not but if then than when which what who how you your we our they their there here will would can could should does do did has have had into only also just about all any each more most such so".split(" "));
|
|
47
|
+
const SPANISH_WORDS = new Set("el la los las de del al que y en un una unos unas es son era fue ser está están estar por para con sin se lo le les su sus este esta esto estos estas ese esa eso como más pero si sí ya hay cuando también porque sobre muy entre hasta desde todo todos cada qué cómo donde dónde o ni".split(" "));
|
|
48
|
+
/** The phrasebook of the text being cleaned; `speechReading` sets it around one synchronous run. */
|
|
49
|
+
let words;
|
|
50
|
+
function cleaned(markdown, language) {
|
|
51
|
+
const out = [];
|
|
52
|
+
const lines = markdown.replace(/\r\n?/g, "\n").split("\n");
|
|
53
|
+
let fence;
|
|
54
|
+
for (let i = 0; i < lines.length; i++) {
|
|
55
|
+
const raw = lines[i];
|
|
56
|
+
if (fence) {
|
|
57
|
+
const close = /^\s*(`{3,}|~{3,})\s*$/.exec(raw);
|
|
58
|
+
if (close && close[1][0] === fence.char && close[1].length >= fence.length)
|
|
59
|
+
fence = undefined;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
const open = /^\s{0,3}(`{3,}|~{3,})/.exec(raw);
|
|
63
|
+
if (open) {
|
|
64
|
+
fence = { char: open[1][0], length: open[1].length };
|
|
65
|
+
out.push(words.codeBlock);
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (raw.includes("|") && TABLE_SEPARATOR.test(lines[i + 1] ?? "")) {
|
|
69
|
+
out.push(tableRow(raw));
|
|
70
|
+
i++;
|
|
71
|
+
while (i + 1 < lines.length && lines[i + 1].includes("|") && lines[i + 1].trim() !== "") {
|
|
72
|
+
out.push(tableRow(lines[++i]));
|
|
73
|
+
}
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
const { text, section } = blockLine(raw);
|
|
77
|
+
out.push(text);
|
|
78
|
+
// A heading or bold-only line ends its section, so playback pauses as at a blank line; trim drops a last one.
|
|
79
|
+
if (section)
|
|
80
|
+
out.push("");
|
|
81
|
+
}
|
|
82
|
+
const joined = out.join("\n").replace(/[ \t]{2,}|\t/g, " ");
|
|
83
|
+
return (language === "es" ? contracted(joined) : joined)
|
|
84
|
+
// A numbered heading or bold line ("## 1. Estado", "## 5.2. Título") starts with "1." too; "1:" keeps playback
|
|
85
|
+
// from cutting there.
|
|
86
|
+
.replace(new RegExp(`^(\\d+(?: ${words.point} \\d+)*)\\. `, "gm"), "$1: ")
|
|
87
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
88
|
+
.trim();
|
|
89
|
+
}
|
|
90
|
+
/** Spanish only: the readings add "el comando", "la rama", "un commit" next to "de" and "a". */
|
|
91
|
+
function contracted(text) {
|
|
92
|
+
return (text
|
|
93
|
+
// Spanish contracts "de el" and "a el" (but not "de él").
|
|
94
|
+
.replace(/(?<![\p{L}\p{N}])([dD]e|[aA]) el(?![\p{L}\p{N}])/gu, (_m, word) => (word.length === 1 ? `${word}l` : `${word[0]}el`))
|
|
95
|
+
// The reverse for a contraction already written before the token: "del el comando" → "del comando",
|
|
96
|
+
// "del la rama" → "de la rama", "al un commit" → "a un commit".
|
|
97
|
+
.replace(/(?<![\p{L}\p{N}])([dD]e|[aA])l (el|la|un) (comando|carpeta|rama|commit)(?![\p{L}\p{N}])/gu, (_m, word, article, noun) => (article === "el" ? `${word}l ${noun}` : `${word} ${article} ${noun}`)));
|
|
98
|
+
}
|
|
99
|
+
const SPANISH = {
|
|
100
|
+
codeBlock: "Bloque de código.",
|
|
101
|
+
command: "el comando",
|
|
102
|
+
folder: "la carpeta",
|
|
103
|
+
branch: "la rama",
|
|
104
|
+
aCommit: "un commit",
|
|
105
|
+
in: "en",
|
|
106
|
+
line: "línea",
|
|
107
|
+
dot: "punto",
|
|
108
|
+
point: "punto",
|
|
109
|
+
or: "o",
|
|
110
|
+
approximately: "aproximadamente",
|
|
111
|
+
times: "por",
|
|
112
|
+
units: {
|
|
113
|
+
s: "segundos",
|
|
114
|
+
ms: "milisegundos",
|
|
115
|
+
min: "minutos",
|
|
116
|
+
KB: "kilobytes",
|
|
117
|
+
MB: "megabytes",
|
|
118
|
+
GB: "gigabytes",
|
|
119
|
+
"%": "por ciento",
|
|
120
|
+
dB: "decibeles",
|
|
121
|
+
dBFS: "decibeles",
|
|
122
|
+
},
|
|
123
|
+
unit: {
|
|
124
|
+
s: "segundo",
|
|
125
|
+
ms: "milisegundo",
|
|
126
|
+
min: "minuto",
|
|
127
|
+
KB: "kilobyte",
|
|
128
|
+
MB: "megabyte",
|
|
129
|
+
GB: "gigabyte",
|
|
130
|
+
"%": "por ciento",
|
|
131
|
+
dB: "decibel",
|
|
132
|
+
dBFS: "decibel",
|
|
133
|
+
},
|
|
134
|
+
punctuation: {
|
|
135
|
+
".": "punto",
|
|
136
|
+
",": "coma",
|
|
137
|
+
";": "punto y coma",
|
|
138
|
+
":": "dos puntos",
|
|
139
|
+
"!": "signo de exclamación",
|
|
140
|
+
"?": "signo de pregunta",
|
|
141
|
+
"~": "virgulilla",
|
|
142
|
+
"/": "barra",
|
|
143
|
+
"-": "guion",
|
|
144
|
+
_: "guion bajo",
|
|
145
|
+
"*": "asterisco",
|
|
146
|
+
"#": "numeral",
|
|
147
|
+
"|": "barra vertical",
|
|
148
|
+
},
|
|
149
|
+
symbols: [
|
|
150
|
+
[/[→⇒➜]/, "a"],
|
|
151
|
+
[/←/, "desde"],
|
|
152
|
+
[/≈/, "aproximadamente"],
|
|
153
|
+
[/≠/, "distinto de"],
|
|
154
|
+
[/≥/, "mayor o igual a"],
|
|
155
|
+
[/≤/, "menor o igual a"],
|
|
156
|
+
[/±/, "más o menos"],
|
|
157
|
+
[/&+/, "y"],
|
|
158
|
+
],
|
|
159
|
+
thousands: true,
|
|
160
|
+
};
|
|
161
|
+
const ENGLISH = {
|
|
162
|
+
codeBlock: "Code block.",
|
|
163
|
+
command: "the command",
|
|
164
|
+
folder: "the folder",
|
|
165
|
+
branch: "the branch",
|
|
166
|
+
aCommit: "a commit",
|
|
167
|
+
in: "in",
|
|
168
|
+
line: "line",
|
|
169
|
+
dot: "dot",
|
|
170
|
+
point: "point",
|
|
171
|
+
or: "or",
|
|
172
|
+
approximately: "approximately",
|
|
173
|
+
times: "times",
|
|
174
|
+
units: {
|
|
175
|
+
s: "seconds",
|
|
176
|
+
ms: "milliseconds",
|
|
177
|
+
min: "minutes",
|
|
178
|
+
KB: "kilobytes",
|
|
179
|
+
MB: "megabytes",
|
|
180
|
+
GB: "gigabytes",
|
|
181
|
+
"%": "percent",
|
|
182
|
+
dB: "decibels",
|
|
183
|
+
dBFS: "decibels",
|
|
184
|
+
},
|
|
185
|
+
unit: {
|
|
186
|
+
s: "second",
|
|
187
|
+
ms: "millisecond",
|
|
188
|
+
min: "minute",
|
|
189
|
+
KB: "kilobyte",
|
|
190
|
+
MB: "megabyte",
|
|
191
|
+
GB: "gigabyte",
|
|
192
|
+
"%": "percent",
|
|
193
|
+
dB: "decibel",
|
|
194
|
+
dBFS: "decibel",
|
|
195
|
+
},
|
|
196
|
+
punctuation: {
|
|
197
|
+
".": "period",
|
|
198
|
+
",": "comma",
|
|
199
|
+
";": "semicolon",
|
|
200
|
+
":": "colon",
|
|
201
|
+
"!": "exclamation mark",
|
|
202
|
+
"?": "question mark",
|
|
203
|
+
"~": "tilde",
|
|
204
|
+
"/": "slash",
|
|
205
|
+
"-": "hyphen",
|
|
206
|
+
_: "underscore",
|
|
207
|
+
"*": "asterisk",
|
|
208
|
+
"#": "hash",
|
|
209
|
+
"|": "pipe",
|
|
210
|
+
},
|
|
211
|
+
symbols: [
|
|
212
|
+
[/[→⇒➜]/, "to"],
|
|
213
|
+
[/←/, "from"],
|
|
214
|
+
[/≈/, "approximately"],
|
|
215
|
+
[/≠/, "not equal to"],
|
|
216
|
+
[/≥/, "greater than or equal to"],
|
|
217
|
+
[/≤/, "less than or equal to"],
|
|
218
|
+
[/±/, "plus or minus"],
|
|
219
|
+
[/&+/, "and"],
|
|
220
|
+
],
|
|
221
|
+
thousands: false,
|
|
222
|
+
};
|
|
223
|
+
const PHRASEBOOKS = { es: SPANISH, en: ENGLISH };
|
|
224
|
+
words = SPANISH;
|
|
225
|
+
const TABLE_SEPARATOR = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
|
|
226
|
+
const WORD = String.raw `\p{L}\p{N}_`;
|
|
227
|
+
/** A line wrapped whole in one emphasis (`**Qué cambió**`, `*Nota*`, `__X__`), read like a heading. */
|
|
228
|
+
const EMPHASIS_LINE = /^(?:\*\*(?=\S)(?:(?!\*\*).)+(?<=\S)\*\*|__(?=\S)(?:(?!__).)+(?<=\S)__|\*(?=\S)[^*]+(?<=\S)\*|_(?=\S)[^_]+(?<=\S)_)$/;
|
|
229
|
+
/** One line of text; `section` marks a heading or bold-only line, which a section break follows. */
|
|
230
|
+
function blockLine(raw) {
|
|
231
|
+
let line = raw.trim();
|
|
232
|
+
while (/^>\s?/.test(line))
|
|
233
|
+
line = line.replace(/^>\s?/, "").trim();
|
|
234
|
+
if (/^([-*_])(\s*\1){2,}$/.test(line))
|
|
235
|
+
return { text: "" };
|
|
236
|
+
if (/^\[[^\]]+\]:\s*\S+/.test(line))
|
|
237
|
+
return { text: "" };
|
|
238
|
+
const heading = /^#{1,6}\s+(.*?)(\s+#+)?$/.exec(line);
|
|
239
|
+
if (heading) {
|
|
240
|
+
const text = inline(heading[1]);
|
|
241
|
+
return { text: closeSentence(spokenHeading(text)), section: true };
|
|
242
|
+
}
|
|
243
|
+
if (EMPHASIS_LINE.test(line))
|
|
244
|
+
return { text: closeSentence(spokenHeading(inline(line))), section: true };
|
|
245
|
+
const bullet = /^[-*+]\s+(?:\[[ xX]\]\s+)?(.*)$/.exec(line);
|
|
246
|
+
if (bullet)
|
|
247
|
+
return { text: closeSentence(inline(bullet[1])) };
|
|
248
|
+
const numbered = /^(\d+)[.)]\s+(.*)$/.exec(line);
|
|
249
|
+
// "1:" rather than "1.", which playback would cut at, reading the number alone.
|
|
250
|
+
if (numbered)
|
|
251
|
+
return { text: closeSentence(`${numbered[1]}: ${inline(numbered[2])}`) };
|
|
252
|
+
return { text: inline(line) };
|
|
253
|
+
}
|
|
254
|
+
/** Every reply here closes with the English heading "Needs your decision"; a Spanish voice would mangle it. */
|
|
255
|
+
function spokenHeading(text) {
|
|
256
|
+
return words === SPANISH && /^needs your decision:?$/i.test(text) ? "Decisiones pendientes" : text;
|
|
257
|
+
}
|
|
258
|
+
function tableRow(raw) {
|
|
259
|
+
const cells = raw
|
|
260
|
+
.trim()
|
|
261
|
+
.replace(/^\|/, "")
|
|
262
|
+
.replace(/(?<!\\)\|$/, "")
|
|
263
|
+
.split(/(?<!\\)\|/)
|
|
264
|
+
.map((cell) => inline(cell.trim()))
|
|
265
|
+
.filter((cell) => cell !== "");
|
|
266
|
+
return closeSentence(cells.join(", "));
|
|
267
|
+
}
|
|
268
|
+
function closeSentence(text) {
|
|
269
|
+
return text === "" || /[.!?:;…,]$/.test(text) ? text : `${text}.`;
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Inline syntax: code spans are spoken verbatim (minus backticks), everything else is unwrapped.
|
|
273
|
+
* Code spans and escapes are parked behind private-use markers so emphasis around them still pairs up
|
|
274
|
+
* and their characters never count as Markdown.
|
|
275
|
+
*/
|
|
276
|
+
function inline(text) {
|
|
277
|
+
const spans = [];
|
|
278
|
+
const parked = text
|
|
279
|
+
.replace(/(`+)(.+?)(?<!`)\1(?!`)/g, (m, _ticks, code, offset) => `\uE002${spans.push(codeSpan(code, text.slice(0, offset), text.slice(offset + m.length))) - 1}\uE003`)
|
|
280
|
+
.replace(/\\([\\`*_{}[\]()#+\-.!|~<>])/g, (_m, ch) => `\uE000${ch.codePointAt(0)}\uE001`);
|
|
281
|
+
return prose(parked)
|
|
282
|
+
.replace(/\uE000(\d+)\uE001/g, (_m, code) => String.fromCodePoint(Number(code)))
|
|
283
|
+
.replace(/\uE002(\d+)\uE003/g, (_m, index) => spans[Number(index)])
|
|
284
|
+
.replace(/[ \t]*\uE008|[\uE006\uE007]/g, "");
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* `before` and `after` are the text around the span, so a branch or hash in it can tell what word precedes it,
|
|
288
|
+
* and in English what noun follows it ("the `/read` command").
|
|
289
|
+
*/
|
|
290
|
+
function codeSpan(code, before, after) {
|
|
291
|
+
// A code span holding one mark is spoken by name; a bare "." would also end a sentence in playback.
|
|
292
|
+
return Object.hasOwn(words.punctuation, code.trim()) ? words.punctuation[code.trim()] : speakable(code.trim(), before, after);
|
|
293
|
+
}
|
|
294
|
+
/** IDs, symbols, emoji and technical tokens a voice stumbles on, made speakable (prose and code spans alike). */
|
|
295
|
+
function speakable(text, before = "", after = "") {
|
|
296
|
+
const urls = [];
|
|
297
|
+
let out = text.replace(/\S*:\/\/\S*/g, (url) => `\uE004${urls.push(url) - 1}\uE005`);
|
|
298
|
+
out = identifierSpaces(out.replace(/\S+/g, (token, offset, whole) => tokenReading(token, previousWord(before + whole.slice(0, offset)), nextWord(whole.slice(offset + token.length) + after))));
|
|
299
|
+
out = out
|
|
300
|
+
// "aproximadamente" has no gender, unlike "unos" ("las unos 400 líneas").
|
|
301
|
+
.replace(/(?<![\p{L}\p{N}])~(?=\d)/gu, `${words.approximately} `)
|
|
302
|
+
.replace(UNIT, (_m, number, unit) => `${number} ${(number === "1" ? words.unit : words.units)[unit]}`)
|
|
303
|
+
// After the units, so "2.1 s" is "2 punto 1 segundos" and not "2 punto 1 segundo".
|
|
304
|
+
.replace(DOTTED_NUMBER, dottedNumber);
|
|
305
|
+
out = out.replace(/(?<![\p{L}\p{N}.])P(\d+)\.R(\d+)(?:\.Q(\d+))?(?![\p{L}\p{N}]|\.[\p{L}\p{N}])/gu, (_m, p, r, q) => `P ${p}, R ${r}${q ? `, Q ${q}` : ""}`);
|
|
306
|
+
out = out.replace(/(\d)[ \t]*×[ \t]*(?=\d)/g, `$1 ${words.times} `);
|
|
307
|
+
for (const [symbol, word] of words.symbols)
|
|
308
|
+
out = spokenAs(out, symbol, word);
|
|
309
|
+
return spokenAs(out, EMOJI, "")
|
|
310
|
+
.replace(/\uE004(\d+)\uE005/g, (_m, index) => identifierSpaces(urls[Number(index)]))
|
|
311
|
+
.replace(/\uE009/g, ".");
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* (h1) Digit groups joined by single dots, standing alone: not inside a word, a version tag (`v2.0.1`,
|
|
315
|
+
* `x@2.0.1`), a file name (`2.0.1.tgz`), a host (marked by `prose`) or an address after `tcp:`. A dot between
|
|
316
|
+
* digits in a technical token's own reading is parked as \uE009, so paths and file names keep theirs.
|
|
317
|
+
*/
|
|
318
|
+
const DOTTED_NUMBER = /\uE006[^\uE007]*\uE007|(?<![\p{L}\p{N}_.@/:\\\uE009])(?<![\p{L}\p{N}_]-)\d+(?:\.\d+)+(?![\p{L}\p{N}_@/\\\uE009]|\.[\p{L}\p{N}])/gu;
|
|
319
|
+
/** Spanish thousands: "2.750", "1.500.000". */
|
|
320
|
+
const THOUSANDS = /^[1-9]\d{0,2}(?:\.\d{3})+$/;
|
|
321
|
+
/** "1.1" reads as "1 punto 1"; Spanish thousands, IP addresses and hosts stay as they are. */
|
|
322
|
+
function dottedNumber(match) {
|
|
323
|
+
if (match.startsWith("\uE006") || (words.thousands && THOUSANDS.test(match)))
|
|
324
|
+
return match;
|
|
325
|
+
const groups = match.split(".");
|
|
326
|
+
if (groups.length === 4 && groups.every((group) => group.length <= 3 && Number(group) <= 255))
|
|
327
|
+
return match;
|
|
328
|
+
return groups.join(` ${words.point} `);
|
|
329
|
+
}
|
|
330
|
+
/** A unit right after a number that letters or a version dot do not precede: "2,5 s", "80%", "-16 dB". */
|
|
331
|
+
const UNIT = /(?<![\p{L}\p{N}_.,])(\d+(?:[.,]\d+)*)[ \t]?(dBFS|dB|ms|min|s|KB|MB|GB|%)(?![\p{L}\p{N}])/gu;
|
|
332
|
+
const EMOJI = /(?:\p{Extended_Pictographic}|\p{Regional_Indicator}|[\u{1F3FB}-\u{1F3FF}\uFE0F\u200D\u20E3])+/u;
|
|
333
|
+
/** Replaces `symbol` with `word`, spaced from neighbouring words but not from punctuation. */
|
|
334
|
+
function spokenAs(text, symbol, word) {
|
|
335
|
+
const pattern = new RegExp(`[ \\t]*(?:${symbol.source})[ \\t]*`, "gu");
|
|
336
|
+
return text.replace(pattern, (match, offset, whole) => {
|
|
337
|
+
const before = offset > 0 && !/[([{\s]/u.test(whole[offset - 1]);
|
|
338
|
+
const next = whole[offset + match.length];
|
|
339
|
+
const after = next !== undefined && !/[)\]}.,;:!?\s]/u.test(next);
|
|
340
|
+
if (word === "")
|
|
341
|
+
return before && after ? " " : "";
|
|
342
|
+
return `${before ? " " : ""}${word}${after ? " " : ""}`;
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* One technical token, read by its class in the order of S2 (e2)-(e8); URLs never get here (e1).
|
|
347
|
+
* Leading and trailing punctuation stays outside, so "`README.md`." reads "README punto md.".
|
|
348
|
+
* A dropped token leaves a \uE008 marker that takes the space before it along when removed.
|
|
349
|
+
*/
|
|
350
|
+
function tokenReading(token, previous, next) {
|
|
351
|
+
const [, lead, core, trail] = /^([("'“«[]*)(.*?)([)"'”»\].,;:!?]*)$/u.exec(token) ?? [];
|
|
352
|
+
if (!core || /[\uE000-\uE008]/u.test(token) || !/[\p{L}\p{N}]/u.test(core))
|
|
353
|
+
return token;
|
|
354
|
+
// English puts the noun after the token ("the `/read` command"); punctuation in between ends the phrase.
|
|
355
|
+
const noun = words === ENGLISH && trail === "" ? next.toLowerCase() : "";
|
|
356
|
+
const reading = classified(core, previous.toLowerCase(), noun);
|
|
357
|
+
if (reading === undefined)
|
|
358
|
+
return token;
|
|
359
|
+
if (reading === "")
|
|
360
|
+
return `\uE008${trail}`;
|
|
361
|
+
// A dot between digits in a reading ("a punto ts, en 1.2") is the token's own; (h1) leaves it.
|
|
362
|
+
return `${lead}${reading.replace(/(?<=\d)\.(?=\d)/g, "\uE009")}${trail}`;
|
|
363
|
+
}
|
|
364
|
+
/** `noun` is the English noun right after the token, which the reading then leaves out ("the read command"). */
|
|
365
|
+
function classified(core, previous, noun) {
|
|
366
|
+
if (previous === "rama" || previous === "branch")
|
|
367
|
+
return nameWords(core);
|
|
368
|
+
const line = /^(.+):(\d+)$/.exec(core);
|
|
369
|
+
const file = line && (pathReading(line[1], previous) ?? fileName(line[1]));
|
|
370
|
+
if (line && file)
|
|
371
|
+
return `${file}, ${words.line} ${line[2]}`;
|
|
372
|
+
if (BRANCH.test(core) && !/\.\p{L}+$/u.test(core))
|
|
373
|
+
return noun === "branch" ? nameWords(core) : `${words.branch} ${nameWords(core)}`;
|
|
374
|
+
if (noun === "folder") {
|
|
375
|
+
const folder = folderName(core);
|
|
376
|
+
if (folder !== undefined)
|
|
377
|
+
return folder;
|
|
378
|
+
}
|
|
379
|
+
return (alternatives(core) ??
|
|
380
|
+
pathReading(core, previous) ??
|
|
381
|
+
command(core, previous, noun) ??
|
|
382
|
+
fileName(core) ??
|
|
383
|
+
commitHash(core, previous) ??
|
|
384
|
+
slashWords(core));
|
|
385
|
+
}
|
|
386
|
+
const BRANCH = /^(?:feat|fix|docs|chore|refactor|test|release|origin|upstream)\/[\p{L}\p{N}][\p{L}\p{N}._/-]*$/u;
|
|
387
|
+
const PATH = /^[\p{L}\p{N}._~/+-]+$/u;
|
|
388
|
+
/** A bare `name.<tld>` is a host, not a file. */
|
|
389
|
+
const HOST_ENDINGS = new Set(["com", "org", "net", "io", "dev", "lan", "app", "ai", "co"]);
|
|
390
|
+
/** `feat/pending-central` reads as "feat pending central". */
|
|
391
|
+
function nameWords(core) {
|
|
392
|
+
return core.replace(/(?<=[\p{L}\p{N}])[-_/]+(?=[\p{L}\p{N}])/gu, " ");
|
|
393
|
+
}
|
|
394
|
+
/** `light/dark` reads as "light o dark"; short pairs such as `y/o` or `km/h` are kept. */
|
|
395
|
+
function alternatives(core) {
|
|
396
|
+
const pair = /^(\p{L}+)\/(\p{L}+)$/u.exec(core);
|
|
397
|
+
if (!pair)
|
|
398
|
+
return undefined;
|
|
399
|
+
return pair[1].length <= 3 && pair[2].length <= 3 ? core : `${pair[1]} ${words.or} ${pair[2]}`;
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* The last part plus its folder: `~/.gentle-shell/agent/AGENTS.md` reads as "AGENTS punto md, en agent"
|
|
403
|
+
* and `/tmp/x/wav/hs/` as "la carpeta hs, en wav" ("hs, en wav" right after "carpeta"). A single `/word` is
|
|
404
|
+
* left to `command`, `1/2` to the numbers.
|
|
405
|
+
*/
|
|
406
|
+
function pathReading(core, previous) {
|
|
407
|
+
if (!PATH.test(core))
|
|
408
|
+
return undefined;
|
|
409
|
+
const root = /^(?:~|\.{1,2})?\//.exec(core)?.[0] ?? "";
|
|
410
|
+
const parts = core.slice(root.length).split("/").filter((part) => part !== "");
|
|
411
|
+
const isFolder = core.endsWith("/");
|
|
412
|
+
if (root === "/" ? parts.length < 2 && !isFolder : root === "" && parts.length < 2)
|
|
413
|
+
return undefined;
|
|
414
|
+
if (root === "" && !/\p{L}\/[\p{L}\p{N}]|[\p{L}\p{N}]\/\p{L}/u.test(core))
|
|
415
|
+
return undefined;
|
|
416
|
+
const name = partName(parts.at(-1) ?? "");
|
|
417
|
+
if (name === "")
|
|
418
|
+
return undefined;
|
|
419
|
+
const said = previous === "carpeta" || previous === "folder";
|
|
420
|
+
const reading = (!isFolder && fileReading(parts.at(-1) ?? "")) || (said ? name : `${words.folder} ${name}`);
|
|
421
|
+
const folder = parts.length > 1 ? partName(parts[parts.length - 2]) : "";
|
|
422
|
+
return folder === "" ? reading : `${reading}, ${words.in} ${folder}`;
|
|
423
|
+
}
|
|
424
|
+
/** A leading `.` is dropped and `-`/`_` become spaces: `.gentle-shell` reads as "gentle shell". */
|
|
425
|
+
function partName(part) {
|
|
426
|
+
return part.replace(/^\.+/, "").replace(/[-_]+/g, " ").trim();
|
|
427
|
+
}
|
|
428
|
+
/** `speech-text.ts` reads as "speech text punto ts"; a part without a letter-only extension is not a file. */
|
|
429
|
+
function fileReading(part) {
|
|
430
|
+
const file = /^(.*\p{L}.*)\.(\p{L}+)$/u.exec(part);
|
|
431
|
+
if (!file)
|
|
432
|
+
return undefined;
|
|
433
|
+
const name = partName(file[1]).replace(/(?<=[\p{L}\p{N}])\.(?=[\p{L}\p{N}])/gu, ` ${words.dot} `);
|
|
434
|
+
return name === "" ? undefined : `${name} ${words.dot} ${file[2]}`;
|
|
435
|
+
}
|
|
436
|
+
/** Top-level folders of a Unix system: `/tmp` is a place, not a command. */
|
|
437
|
+
const SYSTEM_FOLDERS = new Set(["bin", "boot", "dev", "etc", "home", "lib", "media", "mnt", "opt", "proc", "root", "run", "srv", "sys", "tmp", "usr", "var"]);
|
|
438
|
+
/** `/reload` reads as "el comando reload", or just "reload" right after "comando"; `/tmp` reads as "la carpeta tmp". */
|
|
439
|
+
function command(core, previous, noun) {
|
|
440
|
+
const name = /^\/(\p{L}[\p{L}\p{N}_:-]*)$/u.exec(core)?.[1]?.replace(/[-_:]+/g, " ");
|
|
441
|
+
if (!name)
|
|
442
|
+
return undefined;
|
|
443
|
+
if (SYSTEM_FOLDERS.has(name))
|
|
444
|
+
return previous === "carpeta" || previous === "folder" ? name : `${words.folder} ${name}`;
|
|
445
|
+
return previous === "comando" || previous === "command" || noun === "command" ? name : `${words.command} ${name}`;
|
|
446
|
+
}
|
|
447
|
+
/** "the `/tmp/a/b/` folder" and "the `src/` folder" read as "the b folder" and "the src folder"; files are not folders. */
|
|
448
|
+
function folderName(core) {
|
|
449
|
+
if (!PATH.test(core) || !core.includes("/"))
|
|
450
|
+
return undefined;
|
|
451
|
+
const last = core.split("/").filter((part) => part !== "").at(-1) ?? "";
|
|
452
|
+
if (!core.endsWith("/") && fileReading(last))
|
|
453
|
+
return undefined;
|
|
454
|
+
const name = partName(last);
|
|
455
|
+
return /\p{L}/u.test(name) ? name : undefined;
|
|
456
|
+
}
|
|
457
|
+
/** A bare `README.md`; versions, numbers, hosts, `a..b` ranges and abbreviations such as `e.g` are not file names. */
|
|
458
|
+
function fileName(core) {
|
|
459
|
+
if (!/^[\p{L}\p{N}_.-]+$/u.test(core) || /^(?:\p{L}\.)+\p{L}$/u.test(core) || core.includes(".."))
|
|
460
|
+
return undefined;
|
|
461
|
+
const ext = /\.(\p{L}+)$/u.exec(core)?.[1];
|
|
462
|
+
return ext && !HOST_ENDINGS.has(ext.toLowerCase()) ? fileReading(core) : undefined;
|
|
463
|
+
}
|
|
464
|
+
/** A hash is dropped right after "commit" and spoken as "un commit" elsewhere. */
|
|
465
|
+
function commitHash(core, previous) {
|
|
466
|
+
if (!/^(?=.*\d)(?=.*[a-f])[0-9a-f]{7,40}$/.test(core))
|
|
467
|
+
return undefined;
|
|
468
|
+
return previous === "commit" || previous === "commits" ? "" : words.aCommit;
|
|
469
|
+
}
|
|
470
|
+
/** Other paths, such as `@scope/pkg`, `lab-*` globs or `/a/<id>/b`, keep (d)'s reading: their parts as words. */
|
|
471
|
+
function slashWords(core) {
|
|
472
|
+
if (!/^(?:~|\.{1,2})?\//.test(core) && !/\p{L}\/[\p{L}\p{N}]|[\p{L}\p{N}]\/\p{L}/u.test(core))
|
|
473
|
+
return undefined;
|
|
474
|
+
const parts = core.split("/").map((part) => part.replace(/^[~.]+/, "")).filter((part) => part !== "");
|
|
475
|
+
return parts.join(" ").replace(/(?<=[\p{L}\p{N}])[-_]+(?=[\p{L}\p{N}])/gu, " ");
|
|
476
|
+
}
|
|
477
|
+
/** The word right before a token, across spaces, opening quotes and emphasis markers. */
|
|
478
|
+
function previousWord(text) {
|
|
479
|
+
return /(?<![\p{L}\p{N}])(\p{L}+)[ \t*_`"'“«(]*$/u.exec(text)?.[1] ?? "";
|
|
480
|
+
}
|
|
481
|
+
/** The word right after a token, across closing emphasis or quotes and spaces, but not across punctuation. */
|
|
482
|
+
function nextWord(text) {
|
|
483
|
+
return /^[*_`"'”»]*[ \t]+[*_`"'“«]*(\p{L}+)(?![\p{L}\p{N}])/u.exec(text)?.[1] ?? "";
|
|
484
|
+
}
|
|
485
|
+
/** `auto_read` reads as "auto read", not "auto guion bajo read". */
|
|
486
|
+
function identifierSpaces(text) {
|
|
487
|
+
return text.replace(/(?<=[\p{L}\p{N}])_+(?=[\p{L}\p{N}])/gu, " ");
|
|
488
|
+
}
|
|
489
|
+
function prose(text) {
|
|
490
|
+
const unwrapped = text
|
|
491
|
+
.replace(/!?\[([^\]]*)\]\([^)\s]*(?:\s+"[^"]*")?\)/g, "$1")
|
|
492
|
+
.replace(/\[([^\]]+)\]\[[^\]]*\]/g, "$1")
|
|
493
|
+
// Hosts are marked so the file-name rule leaves `github.com` alone; `inline` drops the marks.
|
|
494
|
+
.replace(/<(https?:\/\/[^>\s]+)>/g, (_m, url) => `\uE006${host(url)}\uE007`)
|
|
495
|
+
.replace(/\bhttps?:\/\/[^\s<>()[\]*]+/g, (url) => {
|
|
496
|
+
const trailing = /[.,;:!?]+$/.exec(url)?.[0] ?? "";
|
|
497
|
+
return `\uE006${host(url.slice(0, url.length - trailing.length))}\uE007${trailing}`;
|
|
498
|
+
})
|
|
499
|
+
.replace(/\*\*(?=\S)(.+?)(?<=\S)\*\*/g, "$1")
|
|
500
|
+
.replace(new RegExp(`(?<![${WORD}])__(?=\\S)(.+?)(?<=\\S)__(?![${WORD}])`, "gu"), "$1")
|
|
501
|
+
.replace(/~~(?=\S)(.+?)(?<=\S)~~/g, "$1")
|
|
502
|
+
.replace(new RegExp(`(?<![${WORD}*])\\*(?=\\S)([^*\\n]*?)(?<=\\S)\\*(?![${WORD}*])`, "gu"), "$1")
|
|
503
|
+
.replace(new RegExp(`(?<![${WORD}])_(?=\\S)([^_\\n]*?)(?<=\\S)_(?![${WORD}])`, "gu"), "$1");
|
|
504
|
+
return speakable(unwrapped);
|
|
505
|
+
}
|
|
506
|
+
function host(url) {
|
|
507
|
+
return url
|
|
508
|
+
.replace(/^https?:\/\//, "")
|
|
509
|
+
.split(/[/?#]/)[0]
|
|
510
|
+
.replace(/^www\./, "");
|
|
511
|
+
}
|