fix(tts): sox combination order; refactor input logic flow

- Replace manual `process.stdin` listeners with `events.once()`
- Switch from `process.exit()` to `return` for cleaner async execution paths
- Update Node.js module imports to use default exports consistently
This commit is contained in:
mitchell 2026-06-12 19:39:19 -04:00
parent 0e07268bfb
commit 749559e19c
2 changed files with 33 additions and 34 deletions

View file

@ -1,5 +1,5 @@
#!/usr/bin/env node #!/usr/bin/env node
import { parseArgs } from "node:util"; import util from "node:util";
import { createOpenAICompatible } from "@ai-sdk/openai-compatible"; import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
import { streamText } from "ai"; import { streamText } from "ai";
@ -7,7 +7,7 @@ import { initConfig, loadConfig } from "./src/config";
import { Conversation } from "./src/conversation"; import { Conversation } from "./src/conversation";
import Renderer from "./src/render"; import Renderer from "./src/render";
const { values: args, positionals } = parseArgs({ const { values: args, positionals } = util.parseArgs({
args: process.argv.slice(2), args: process.argv.slice(2),
options: { options: {
model: { type: "string" }, model: { type: "string" },

63
tts.ts
View file

@ -1,10 +1,11 @@
#!/usr/bin/env node #!/usr/bin/env node
import events from "node:events";
import fs from "node:fs/promises"; import fs from "node:fs/promises";
import os from "node:os"; import os from "node:os";
import path from "node:path"; import path from "node:path";
import process from "node:process"; import process from "node:process";
import { createInterface } from "node:readline"; import readline from "node:readline";
import { parseArgs } from "node:util"; import util from "node:util";
import { Readability } from "@mozilla/readability"; import { Readability } from "@mozilla/readability";
import chalk from "chalk"; import chalk from "chalk";
import { execa } from "execa"; import { execa } from "execa";
@ -14,7 +15,7 @@ import wrapAnsi from "wrap-ansi";
async function main() { async function main() {
const start = Date.now(); const start = Date.now();
const { values: args } = parseArgs({ const { values: args } = util.parseArgs({
args: process.argv.slice(2), args: process.argv.slice(2),
options: { options: {
wait: { type: "boolean" }, wait: { type: "boolean" },
@ -32,41 +33,34 @@ async function main() {
const url = args.url ?? args.u; const url = args.url ?? args.u;
const edit = args.edit ?? args.e; const edit = args.edit ?? args.e;
let input = url let input = "";
? url
: await new Promise<string>((resolve) => {
let data = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => (data += chunk));
process.stdin.on("end", () => resolve(data));
});
input = input.trim();
if (url !== undefined) { if (url?.trim()) {
const result = await fetch(input); const result = await fetch(url.trim());
const window = new Window({ url: input }); const window = new Window({ url: url.trim() });
const doc = window.document; const doc = window.document;
doc.write(await result.text()); doc.write(await result.text());
await window.happyDOM.waitUntilComplete(); await window.happyDOM.waitUntilComplete();
const readable = new Readability(doc).parse(); const readable = new Readability(doc).parse();
if (readable?.textContent) input = readable.textContent.trim(); if (!readable?.textContent) {
if (input === result.url) { throw "Unable to read web page.";
console.error("Unable to read web page.");
process.exit(1);
} }
input = readable.textContent.trim();
} else {
process.stdin.setEncoding("utf8");
process.stdin.on("data", (data) => {
input += data;
});
await events.once(process.stdin, "end");
} }
if (!input) { if (!input) {
console.error("No input given."); throw "No input given.";
process.exit(1);
} }
const home = os.homedir(); const home = os.homedir();
const cwd = path.join(home, ".ttsc"); const cwd = path.join(home, ".ttsc");
const wavs = fs.glob(path.join(cwd, "*.wav"));
for await (const wav of wavs) await fs.rm(wav);
if (edit) { if (edit) {
const file = path.join(cwd, "input.txt"); const file = path.join(cwd, "input.txt");
await fs.writeFile(file, input); await fs.writeFile(file, input);
@ -75,7 +69,8 @@ async function main() {
cwd, cwd,
stdin: "inherit", stdin: "inherit",
stdout: "inherit", stdout: "inherit",
})`${editor} input.txt`; stderr: "inherit",
})`${editor} ${file}`;
input = await fs.readFile(file, "utf8"); input = await fs.readFile(file, "utf8");
} }
@ -86,6 +81,9 @@ async function main() {
), ),
); );
const wavs = fs.glob(path.join(cwd, "*.wav"));
for await (const wav of wavs) await fs.rm(wav);
const koko = execa({ const koko = execa({
cwd, cwd,
input, input,
@ -103,7 +101,8 @@ async function main() {
} }
let first = true; let first = true;
const rl = createInterface({ input: koko.stdout }); const files = [];
const rl = readline.createInterface({ input: koko.stdout });
for await (const line of rl) { for await (const line of rl) {
const trimmed = line.trim(); const trimmed = line.trim();
@ -124,13 +123,14 @@ async function main() {
console.log(chalk.green(`\nTime-to-audio: ${duration}s`)); console.log(chalk.green(`\nTime-to-audio: ${duration}s`));
} }
const [columns] = process.stdout.getWindowSize();
const text = wrapAnsi(info.text, columns);
const file = path.join(cwd, `${info.file}.wav`); const file = path.join(cwd, `${info.file}.wav`);
if (wait) { if (wait) {
files.push(file);
process.stdout.write("."); process.stdout.write(".");
} else { } else {
const [columns] = process.stdout.getWindowSize();
const text = wrapAnsi(info.text, columns);
console.log(`\n${chalk.blue(file)}\n${text}\n`); console.log(`\n${chalk.blue(file)}\n${text}\n`);
await execa({ await execa({
cwd, cwd,
@ -142,7 +142,7 @@ async function main() {
} }
await koko; await koko;
if (!wait) process.exit(); if (!wait) return;
const stop = Date.now(); const stop = Date.now();
const duration = ((stop - start) / 1000).toFixed(2); const duration = ((stop - start) / 1000).toFixed(2);
@ -150,8 +150,7 @@ async function main() {
console.log(chalk.yellow(`Combining audio with sox...\n`)); console.log(chalk.yellow(`Combining audio with sox...\n`));
try { try {
const wavs = await Array.fromAsync(fs.glob(path.join(cwd, "*.wav"))); await execa({ cwd, shell: true })`sox ${files} output.wav`;
await execa({ cwd, shell: true })`sox ${wavs} output.wav`;
} catch (err) { } catch (err) {
if (err instanceof Object && "code" in err && err.code === "ENOENT") { if (err instanceof Object && "code" in err && err.code === "ENOENT") {
console.error("Sox not found. Unable to combine outputs."); console.error("Sox not found. Unable to combine outputs.");
@ -159,7 +158,7 @@ async function main() {
throw err; throw err;
} }
console.log(chalk.yellow(`Audio available in ${cwd}`)); console.log(chalk.yellow(`Audio available in ${cwd}`));
process.exit(); return;
} }
const [columns] = process.stdout.getWindowSize(); const [columns] = process.stdout.getWindowSize();