From 99ccd54c6369cfd5aab43e83a1dfd441e5fdf791 Mon Sep 17 00:00:00 2001 From: James Russo Date: Tue, 24 Nov 2026 13:51:57 +0000 Subject: [PATCH] fix(cli): speak a narration line as written in local voice and tts (#8706) * fix(cli): speak a narration line as written in local voice and tts The local voice provider hands the line to tts in a file of its own, so a line that names a .txt file or starts with dashes is spoken, not read or taken as an option. tts and heygen-tts treat a word starting with two path separators as text without looking it up. Co-Authored-By: Claude Fable 5.2 * fix(skills): pass the audio skill's own text file to tts with --text-file Its temp folder can be on a network share, and tts no longer reads such a path when it is given as a plain word. Co-Authored-By: Claude Fable 5.2 * fix(cli): remove the local voice run folder when its text file cannot be written Co-Authored-By: Claude Fable 5.2 * fix(cli): refuse a .txt path on a network share instead of speaking it Co-Authored-By: Claude Fable 5.2 * test(cli): name the share paths outright so the tts cases hold on Windows Co-Authored-By: Claude Fable 5.2 --------- Co-authored-by: Claude Fable 5.2 --- docs/packages/cli.mdx | 6 ++ packages/cli/src/commands/tts.test.ts | 30 ++++++++ packages/cli/src/commands/tts.ts | 11 ++- .../src/media-use/lib/tts-local-provider.mjs | 15 +++- .../media-use/lib/tts-local-provider.test.mjs | 54 +++++++++++++- packages/cli/src/utils/textFile.test.ts | 72 +++++++++++++++++++ packages/cli/src/utils/textFile.ts | 13 +++- skills-manifest.json | 2 +- skills/media-use/audio/scripts/heygen-tts.mjs | 4 ++ .../audio/scripts/heygen-tts.test.mjs | 36 ++++++++++ .../audio/scripts/lib/tts.cleanup.test.mjs | 2 +- skills/media-use/audio/scripts/lib/tts.mjs | 11 ++- 12 files changed, 244 insertions(+), 12 deletions(-) create mode 100644 packages/cli/src/utils/textFile.test.ts diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index adf060caff..9f5dc847d4 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -617,8 +617,14 @@ npx hyperframes tts script.txt npx hyperframes tts --list ``` +A single argument that names an existing local `.txt` file is read; anything +else is spoken. A `.txt` path that starts with two slashes or backslashes +(`\\server\share\script.txt`) is refused: to read a file on a network share, +pass it with `--text-file`. + | Flag | Description | | -------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| `--text-file` | Read the text from this file, whatever its path looks like | | `--output, -o` | Output path (default `speech.wav` in the current directory) | | `--voice, -v` | Voice ID. Run `--list` to see them all. | | `--speed, -s` | Speed multiplier (default 1.0) | diff --git a/packages/cli/src/commands/tts.test.ts b/packages/cli/src/commands/tts.test.ts index 937e66f372..ff34c12e6f 100644 --- a/packages/cli/src/commands/tts.test.ts +++ b/packages/cli/src/commands/tts.test.ts @@ -67,6 +67,36 @@ describe("tts command", () => { ); }); + it("refuses a .txt path that starts with two separators, and reads it with --text-file", async () => { + writeFileSync(join(dir, "script.txt"), "From the file\n"); + const errors = vi.spyOn(console, "error").mockImplementation(() => {}); + const file = join(dir, "script.txt"); + + for (const input of ["//host/share/script.txt", "\\\\host\\share\\script.txt"]) { + await expect(runCommand(ttsCommand, { rawArgs: [input, "--json"] })).rejects.toThrow( + CliUsageError, + ); + } + expect(synthesizeMock).not.toHaveBeenCalled(); + expect(errors.mock.calls.flat().join(" ")).toContain("--text-file"); + + await runCommand(ttsCommand, { rawArgs: ["--text-file", file, "--json"] }); + expect(synthesizeMock).toHaveBeenCalledWith( + "From the file", + expect.any(String), + expect.anything(), + ); + }); + + it("speaks a word that starts with two separators and is not a .txt path", async () => { + await runCommand(ttsCommand, { rawArgs: ["// and then it happened", "--json"] }); + expect(synthesizeMock).toHaveBeenCalledWith( + "// and then it happened", + expect.any(String), + expect.anything(), + ); + }); + it.each(["0.05", "1x", "1.5junk", "1 2", "", " ", "NaN", "Infinity", "0", "-1", "3.01"])( "rejects invalid speed %j before synthesis", async (speed) => { diff --git a/packages/cli/src/commands/tts.ts b/packages/cli/src/commands/tts.ts index 33b6e6748c..fc9753a304 100644 --- a/packages/cli/src/commands/tts.ts +++ b/packages/cli/src/commands/tts.ts @@ -1,6 +1,6 @@ import { terminalLines, terminalText } from "@hyperframes/core"; import { failCommand, failUsage } from "../utils/commandResult.js"; -import { isTextFile } from "../utils/textFile.js"; +import { isShareTextFilePath, isTextFile } from "../utils/textFile.js"; // fallow-ignore-file code-duplication import { defineCommand } from "../utils/defineCommand.js"; import type { Example } from "./_examples.js"; @@ -47,12 +47,12 @@ export default defineCommand({ args: { input: { type: "positional", - description: "Text to speak, or path to a .txt file", + description: "Text to speak, or the path of a local .txt file to read", required: false, }, "text-file": { type: "string", - description: "Read text from a .txt file (compatibility alias)", + description: "Read the text from this file, whatever its path looks like", }, output: { type: "string", @@ -104,6 +104,11 @@ export default defineCommand({ failUsage(); } + if (args["text-file"] === undefined && isShareTextFilePath(input)) { + console.error(c.error("A .txt path on a network share is read only with --text-file.")); + failUsage(); + } + let text: string; if (args["text-file"] !== undefined || isTextFile(input)) { text = readFileSync(resolve(input), "utf-8").trim(); diff --git a/packages/cli/src/media-use/lib/tts-local-provider.mjs b/packages/cli/src/media-use/lib/tts-local-provider.mjs index dbc9372889..ac15d8e6b2 100644 --- a/packages/cli/src/media-use/lib/tts-local-provider.mjs +++ b/packages/cli/src/media-use/lib/tts-local-provider.mjs @@ -1,5 +1,6 @@ import { execFileSync } from "node:child_process"; -import { existsSync, statSync } from "node:fs"; +import { existsSync, statSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; import { ffprobeBinary } from "./ff-binaries.mjs"; import { discardPrivateOutput, privateOutputPath } from "./private-output.mjs"; import { terminalLines } from "./terminal-text.mjs"; @@ -42,7 +43,17 @@ export async function localTtsGenerate( ) { const ffprobe = ffprobeBinary(); const outPath = privateOutputPath("kokoro", ".wav"); - const argv = ["hyperframes", "tts", intent, "--output", outPath]; + // The line goes in a file this run made, never on the command line: `tts` reads a word that + // names a .txt file and takes a word starting with dashes as an option. To reproduce, voice the + // path of an existing .txt file: the path must be spoken, not the file's text. + const textPath = join(dirname(outPath), "line.txt"); + try { + writeFileSync(textPath, intent, { flag: "wx" }); + } catch (err) { + discardPrivateOutput(outPath); + throw err; + } + const argv = ["hyperframes", "tts", "--text-file", textPath, "--output", outPath]; if (ctx?.voice) argv.push("--voice", ctx.voice); if (ctx?.lang && ctx.lang !== "en") argv.push("--lang", ctx.lang); // resolveSpawnCommand runs the CLI that started this engine (HYPERFRAMES_CLI_ENTRY) with the diff --git a/packages/cli/src/media-use/lib/tts-local-provider.test.mjs b/packages/cli/src/media-use/lib/tts-local-provider.test.mjs index 7f99f6e3ad..87eeac6f5e 100644 --- a/packages/cli/src/media-use/lib/tts-local-provider.test.mjs +++ b/packages/cli/src/media-use/lib/tts-local-provider.test.mjs @@ -1,5 +1,8 @@ import { test } from "node:test"; import assert from "node:assert/strict"; +import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; import { localTtsGenerate } from "./tts-local-provider.mjs"; // Kokoro runs `hyperframes tts` through the CLI that started the engine (HYPERFRAMES_CLI_ENTRY), @@ -31,7 +34,7 @@ test("a launching CLI's entry file runs instead of npx, on every platform", asyn assert.equal(captured.length, 1); assert.equal(captured[0].cmd, process.execPath); - assert.deepEqual(captured[0].args.slice(0, 3), [entry, "tts", "hello & there"]); + assert.deepEqual(captured[0].args.slice(0, 3), [entry, "tts", "--text-file"]); assert.ok(captured[0].args.includes("--voice")); // execFileSync options survive (pipes are what let the caller read the // "kokoro-onnx not installed" hint back out). @@ -75,3 +78,52 @@ test("a failed tts run prints its output line by line with control characters es "media-use: local voice not enabled (kokoro). bad text \\x1b]0;title\\x07\nline two \\x0dhello", ]); }); + +test("the line reaches tts in a file of its own, whatever it looks like", async (t) => { + const dir = mkdtempSync(join(tmpdir(), "hf-local-voice-test-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const notes = join(dir, "notes.txt"); + writeFileSync(notes, "text of the notes file"); + const env = { ...envWithNpxCli, HYPERFRAMES_CLI_ENTRY: "/opt/hf/dist/cli.js" }; + + for (const line of [ + notes, + "\\\\host\\share\\a.txt", + "//host/share/a.txt", + "--output=/tmp/x.wav", + "-v", + ]) { + const runs = []; + const fakeExec = (cmd, args) => { + const textPath = args[args.indexOf("--text-file") + 1]; + const outPath = args[args.indexOf("--output") + 1]; + runs.push({ args, textPath, outPath, text: readFileSync(textPath, "utf8") }); + }; + + await localTtsGenerate(line, {}, "linux", fakeExec, env, pathExists); + + assert.equal(runs.length, 1); + const [{ args, textPath, outPath, text }] = runs; + assert.equal(text, line); + assert.ok(!args.includes(line), `the line is not an argument: ${line}`); + assert.equal(dirname(textPath), dirname(outPath)); + assert.ok(!existsSync(textPath), "the file goes with the run's folder"); + } +}); + +test("a line that cannot be written leaves no folder behind", async (t) => { + const temp = mkdtempSync(join(tmpdir(), "hf-local-voice-test-")); + const saved = { TMPDIR: process.env.TMPDIR, TEMP: process.env.TEMP, TMP: process.env.TMP }; + Object.assign(process.env, { TMPDIR: temp, TEMP: temp, TMP: temp }); + t.after(() => { + for (const [name, value] of Object.entries(saved)) + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + rmSync(temp, { recursive: true, force: true }); + }); + const env = { ...envWithNpxCli, HYPERFRAMES_CLI_ENTRY: "/opt/hf/dist/cli.js" }; + + await assert.rejects(localTtsGenerate(undefined, {}, "linux", () => {}, env, pathExists)); + + assert.deepEqual(readdirSync(temp), []); +}); diff --git a/packages/cli/src/utils/textFile.test.ts b/packages/cli/src/utils/textFile.test.ts new file mode 100644 index 0000000000..9d0da130b2 --- /dev/null +++ b/packages/cli/src/utils/textFile.test.ts @@ -0,0 +1,72 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const existsSyncMock = vi.hoisted(() => vi.fn()); +vi.mock("node:fs", async (importOriginal) => { + const actual = await importOriginal(); + existsSyncMock.mockImplementation(actual.existsSync); + return { ...actual, existsSync: existsSyncMock }; +}); + +import { isShareTextFilePath, isTextFile } from "./textFile.js"; + +describe("isTextFile", () => { + let dir: string; + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "hf-text-file-test-")); + writeFileSync(join(dir, "script.txt"), "hello"); + writeFileSync(join(dir, "notes.md"), "hello"); + existsSyncMock.mockClear(); + }); + + afterEach(() => rmSync(dir, { recursive: true, force: true })); + + it("is true for an existing .txt file, in any letter case", () => { + writeFileSync(join(dir, "LOUD.TXT"), "hello"); + expect(isTextFile(join(dir, "script.txt"))).toBe(true); + expect(isTextFile(join(dir, "LOUD.TXT"))).toBe(true); + }); + + it("is false for a missing .txt file", () => { + expect(isTextFile(join(dir, "missing.txt"))).toBe(false); + }); + + it.each([ + ["a sentence", "Welcome to the show"], + ["an existing file of another type", "notes.md"], + ["a share, backslashes", "\\\\host\\share\\script.txt"], + ["a share, forward slashes", "//host/share/script.txt"], + ["a share, mixed separators", "\\/host/share/script.txt"], + ["a device", "\\\\.\\pipe\\script.txt"], + ["a long-path prefix", "\\\\?\\C:\\script.txt"], + ])("is false for %s without looking on disk", (_name, input) => { + expect(isTextFile(input === "notes.md" ? join(dir, input) : input)).toBe(false); + expect(existsSyncMock).not.toHaveBeenCalled(); + }); + + it.skipIf(process.platform === "win32")( + "is false for an existing .txt file named with two leading separators", + () => { + expect(isTextFile(`/${join(dir, "script.txt")}`)).toBe(false); + expect(existsSyncMock).not.toHaveBeenCalled(); + }, + ); +}); + +describe("isShareTextFilePath", () => { + it.each(["\\\\host\\share\\a.txt", "//host/share/a.TXT", "\\\\?\\C:\\a.txt"])( + "is true for %s", + (input) => { + expect(isShareTextFilePath(input)).toBe(true); + expect(existsSyncMock).not.toHaveBeenCalled(); + }, + ); + + it.each(["/host/share/a.txt", "a.txt", "//host/share/a.md", "// a note"])( + "is false for %s", + (input) => expect(isShareTextFilePath(input)).toBe(false), + ); +}); diff --git a/packages/cli/src/utils/textFile.ts b/packages/cli/src/utils/textFile.ts index 9d50c823e3..e9a97eee76 100644 --- a/packages/cli/src/utils/textFile.ts +++ b/packages/cli/src/utils/textFile.ts @@ -1,8 +1,15 @@ import { existsSync } from "node:fs"; import { extname, resolve } from "node:path"; -/** True when `input` names an existing `.txt` file, which `tts` reads instead of speaking the path. */ +const WINDOWS_SHARE_OR_DEVICE_PREFIX = /^[\\/]{2}/; + +/** True when `input` names an existing `.txt` file for `tts` to read; a share or device path is never looked up, since that reaches its host. */ export function isTextFile(input: string): boolean { - const path = resolve(input); - return existsSync(path) && extname(path).toLowerCase() === ".txt"; + if (WINDOWS_SHARE_OR_DEVICE_PREFIX.test(input) || extname(input).toLowerCase() !== ".txt") + return false; + return existsSync(resolve(input)); +} + +export function isShareTextFilePath(input: string): boolean { + return WINDOWS_SHARE_OR_DEVICE_PREFIX.test(input) && extname(input).toLowerCase() === ".txt"; } diff --git a/skills-manifest.json b/skills-manifest.json index 0e0ce555d0..0fc18ef3cb 100644 --- a/skills-manifest.json +++ b/skills-manifest.json @@ -18,7 +18,7 @@ "files": 13 }, "media-use": { - "hash": "211ae67ed751ede5", + "hash": "e0be1d796f844931", "files": 134 }, "remotion-to-hyperframes": { diff --git a/skills/media-use/audio/scripts/heygen-tts.mjs b/skills/media-use/audio/scripts/heygen-tts.mjs index 294113ce5f..5cd7711187 100755 --- a/skills/media-use/audio/scripts/heygen-tts.mjs +++ b/skills/media-use/audio/scripts/heygen-tts.mjs @@ -85,7 +85,11 @@ if (listOnly) { } // ---------- resolve text + voice ---------- +// Two leading separators name a network share or a device on Windows; looking one up reaches out +// to that host, so a .txt path of that form is refused, not looked up and not spoken. if (!positional) die("no text given. Pass a string or a .txt path, or use --list."); +if (/^[\\/]{2}/.test(positional) && /\.txt$/i.test(positional)) + die("a .txt path on a network share is not read. Copy the file to a local folder."); const text = positional.endsWith(".txt") && existsSync(resolve(positional)) ? readFileSync(resolve(positional), "utf8").trim() diff --git a/skills/media-use/audio/scripts/heygen-tts.test.mjs b/skills/media-use/audio/scripts/heygen-tts.test.mjs index 89740ce4fe..c886b229dc 100644 --- a/skills/media-use/audio/scripts/heygen-tts.test.mjs +++ b/skills/media-use/audio/scripts/heygen-tts.test.mjs @@ -45,6 +45,42 @@ test("a refused speech prints HeyGen's own message, so a caller can act on it", ); }); +// Every speech request is refused with the text it asked for, so the test can read that text. +const echoing = `data:text/javascript,globalThis.fetch = async (url, init) => new Response( + JSON.stringify({ error: { code: "refused", message: "asked: " + JSON.parse(init.body).text } }), + { status: 400, headers: { "content-type": "application/json" } });`; + +test("a .txt path that starts with two separators is refused, and the file it names is not read", () => { + const dir = mkdtempSync(join(tmpdir(), "heygen-tts-")); + writeFileSync(join(dir, "script.txt"), "text of the file"); + const speak = (word) => + spawnSync( + process.execPath, + ["--import", echoing, script, word, "--voice", "v", "-o", join(dir, "out.mp3")], + { + cwd: dir, + encoding: "utf8", + env: { + ...process.env, + HEYGEN_API_KEY: "", + HYPERFRAMES_API_KEY: "", + HEYGEN_ACCESS_TOKEN: "t", + }, + }, + ).stderr; + try { + assert.match(speak(join(dir, "script.txt")), /asked: text of the file/); + for (const word of ["//host/share/script.txt", "\\\\host\\share\\script.txt"]) { + const said = speak(word); + assert.match(said, /not read\. Copy the file to a local folder/); + assert.doesNotMatch(said, /asked:/); + } + assert.match(speak("// and then"), /asked: \/\/ and then/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + // Speech with one timed word; the audio itself is the file named by $TTS_AUDIO. const speaking = `data:text/javascript,import { readFileSync } from "node:fs"; globalThis.fetch = async (url) => String(url).endsWith("/voices/speech") diff --git a/skills/media-use/audio/scripts/lib/tts.cleanup.test.mjs b/skills/media-use/audio/scripts/lib/tts.cleanup.test.mjs index 1dcb08a08c..1c87996660 100644 --- a/skills/media-use/audio/scripts/lib/tts.cleanup.test.mjs +++ b/skills/media-use/audio/scripts/lib/tts.cleanup.test.mjs @@ -14,7 +14,7 @@ if (args[0] === "--version") { console.log("Python 3.12.0"); process.exit(0); } -const input = args[2]; +const input = args[2] === "--text-file" ? args[3] : args[2]; const output = args[0] === "-c" ? args[4] : args[args.indexOf("--output") + 1]; const text = fs.readFileSync(input, "utf8"); // Side files go to the case root under the output's name: the output itself is in a private folder. diff --git a/skills/media-use/audio/scripts/lib/tts.mjs b/skills/media-use/audio/scripts/lib/tts.mjs index 3c2ca1354c..4f34329306 100644 --- a/skills/media-use/audio/scripts/lib/tts.mjs +++ b/skills/media-use/audio/scripts/lib/tts.mjs @@ -326,7 +326,16 @@ export async function synthesizeOne({ } // kokoro — via the published CLI, run in the project dir. return withStagedWav(text, wavAbs, "kokoro (npx hyperframes tts)", (textPath, staged) => { - const args = ["hyperframes", "tts", textPath, "--voice", voiceId, "--output", staged]; + const args = [ + "hyperframes", + "tts", + "--text-file", + textPath, + "--voice", + voiceId, + "--output", + staged, + ]; if (lang !== "en") args.push("--lang", lang); if (speed !== 1) args.push("--speed", String(speed)); return spawnP("npx", args, { cwd: hyperframesDir });