mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 08:32:45 +00:00
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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * fix(cli): remove the local voice run folder when its text file cannot be written Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(cli): refuse a .txt path on a network share instead of speaking it Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * test(cli): name the share paths outright so the tts cases hold on Windows Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
07e03e8fed
commit
99ccd54c63
@@ -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) |
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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), []);
|
||||
});
|
||||
|
||||
@@ -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<typeof import("node:fs")>();
|
||||
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),
|
||||
);
|
||||
});
|
||||
@@ -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";
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
"files": 13
|
||||
},
|
||||
"media-use": {
|
||||
"hash": "211ae67ed751ede5",
|
||||
"hash": "e0be1d796f844931",
|
||||
"files": 134
|
||||
},
|
||||
"remotion-to-hyperframes": {
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 });
|
||||
|
||||
Reference in New Issue
Block a user