@segnavia/voice 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 modstudio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,43 @@
1
+ import { Word } from "@segnavia/format";
2
+ //#region src/index.d.ts
3
+ export interface Speech {
4
+ words: Word[];
5
+ durationMs: number;
6
+ audio: {
7
+ bytes: Uint8Array;
8
+ extension: string;
9
+ } | null;
10
+ }
11
+ export interface VoiceProvider {
12
+ id: string;
13
+ synthesize(text: string, voice?: string): Promise<Speech>;
14
+ }
15
+ export declare function splitWords(text: string): string[];
16
+ export declare function wordsFromCharacters(characters: string[], startsSec: number[], endsSec: number[]): Word[];
17
+ export declare function pacedProvider(options?: {
18
+ wordsPerMinute?: number;
19
+ }): VoiceProvider;
20
+ export declare function elevenLabsProvider(options: {
21
+ apiKey: () => string;
22
+ voice: string;
23
+ model?: string;
24
+ }): VoiceProvider;
25
+ export declare function alignedProvider(options: {
26
+ id: string;
27
+ speak: (text: string, voice?: string) => Promise<{
28
+ bytes: Uint8Array;
29
+ extension: string;
30
+ durationMs: number;
31
+ }>;
32
+ align: (audio: Uint8Array, text: string) => Promise<Word[]>;
33
+ }): VoiceProvider;
34
+ export interface Narrated {
35
+ words: Word[];
36
+ durationMs: number;
37
+ audio: string | null;
38
+ }
39
+ export declare function narrate(provider: VoiceProvider, text: string, options: {
40
+ cacheDirectory: string;
41
+ voice?: string;
42
+ }): Promise<Narrated>;
43
+ //#endregion
package/dist/index.js ADDED
@@ -0,0 +1,128 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ //#region src/index.ts
5
+ function splitWords(text) {
6
+ return text.split(/\s+/).filter(Boolean);
7
+ }
8
+ function wordsFromCharacters(characters, startsSec, endsSec) {
9
+ const words = [];
10
+ let current = null;
11
+ characters.forEach((character, index) => {
12
+ const start = Math.round((startsSec[index] ?? 0) * 1e3);
13
+ const end = Math.round((endsSec[index] ?? 0) * 1e3);
14
+ if (/\s/.test(character)) {
15
+ if (current) words.push(current);
16
+ current = null;
17
+ return;
18
+ }
19
+ if (current) {
20
+ current.text += character;
21
+ current.endMs = end;
22
+ } else current = {
23
+ text: character,
24
+ startMs: start,
25
+ endMs: end
26
+ };
27
+ });
28
+ if (current) words.push(current);
29
+ return words;
30
+ }
31
+ const SENTENCE_END = /[.!?\u05C3\u061F\u06D4\u0964]["'\u05F4\u201D)]*$/u;
32
+ const CLAUSE_END = /[,;:\u060C\u061B\u05C0]["'\u05F4\u201D)]*$/u;
33
+ function pacedProvider(options = {}) {
34
+ const msPerChar = 6e4 / ((options.wordsPerMinute ?? 160) * 5.5);
35
+ return {
36
+ id: `paced-${options.wordsPerMinute ?? 160}`,
37
+ async synthesize(text) {
38
+ let clock = 0;
39
+ return {
40
+ words: splitWords(text).map((word) => {
41
+ const startMs = clock;
42
+ const endMs = startMs + Math.max(140, word.length * msPerChar);
43
+ clock = endMs + (SENTENCE_END.test(word) ? 350 : CLAUSE_END.test(word) ? 150 : 60);
44
+ return {
45
+ text: word,
46
+ startMs: Math.round(startMs),
47
+ endMs: Math.round(endMs)
48
+ };
49
+ }),
50
+ durationMs: Math.round(clock + 400),
51
+ audio: null
52
+ };
53
+ }
54
+ };
55
+ }
56
+ function elevenLabsProvider(options) {
57
+ return {
58
+ id: `elevenlabs-${options.model ?? "eleven_multilingual_v2"}-${options.voice}`,
59
+ async synthesize(text, voice = options.voice) {
60
+ const response = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${voice}/with-timestamps`, {
61
+ method: "POST",
62
+ headers: {
63
+ "xi-api-key": options.apiKey(),
64
+ "content-type": "application/json"
65
+ },
66
+ body: JSON.stringify({
67
+ text,
68
+ model_id: options.model ?? "eleven_multilingual_v2"
69
+ })
70
+ });
71
+ if (!response.ok) throw new Error(`ElevenLabs refused the synthesis: ${response.status} ${await response.text()}`);
72
+ const body = await response.json();
73
+ const { characters, character_start_times_seconds: starts, character_end_times_seconds: ends } = body.alignment;
74
+ return {
75
+ words: wordsFromCharacters(characters, starts, ends),
76
+ durationMs: Math.round((ends.at(-1) ?? 0) * 1e3) + 300,
77
+ audio: {
78
+ bytes: Buffer.from(body.audio_base64, "base64"),
79
+ extension: "mp3"
80
+ }
81
+ };
82
+ }
83
+ };
84
+ }
85
+ function alignedProvider(options) {
86
+ return {
87
+ id: options.id,
88
+ async synthesize(text, voice) {
89
+ const audio = await options.speak(text, voice);
90
+ const words = await options.align(audio.bytes, text);
91
+ const expected = splitWords(text).length;
92
+ if (words.length !== expected) throw new Error(`The aligner placed ${words.length} words; the narration has ${expected}.`);
93
+ return {
94
+ words,
95
+ durationMs: audio.durationMs,
96
+ audio: {
97
+ bytes: audio.bytes,
98
+ extension: audio.extension
99
+ }
100
+ };
101
+ }
102
+ };
103
+ }
104
+ async function narrate(provider, text, options) {
105
+ const hash = createHash("sha256").update(JSON.stringify([
106
+ provider.id,
107
+ options.voice ?? null,
108
+ text
109
+ ])).digest("hex").slice(0, 16);
110
+ mkdirSync(options.cacheDirectory, { recursive: true });
111
+ const timings = path.join(options.cacheDirectory, `${hash}.json`);
112
+ if (existsSync(timings)) return JSON.parse(readFileSync(timings, "utf8"));
113
+ const speech = await provider.synthesize(text, options.voice);
114
+ let audio = null;
115
+ if (speech.audio) {
116
+ audio = `${hash}.${speech.audio.extension}`;
117
+ writeFileSync(path.join(options.cacheDirectory, audio), speech.audio.bytes);
118
+ }
119
+ const narrated = {
120
+ words: speech.words,
121
+ durationMs: speech.durationMs,
122
+ audio
123
+ };
124
+ writeFileSync(timings, JSON.stringify(narrated));
125
+ return narrated;
126
+ }
127
+ //#endregion
128
+ export { alignedProvider, elevenLabsProvider, narrate, pacedProvider, splitWords, wordsFromCharacters };
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@segnavia/voice",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/modstudio/segnavia.git",
9
+ "directory": "packages/voice"
10
+ },
11
+ "files": [
12
+ "dist"
13
+ ],
14
+ "sideEffects": false,
15
+ "engines": {
16
+ "node": ">=22"
17
+ },
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "exports": {
22
+ ".": {
23
+ "@segnavia/source": "./src/index.ts",
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ }
27
+ },
28
+ "dependencies": {
29
+ "@segnavia/format": "0.2.0"
30
+ }
31
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.