auto-tts 0.3.0 → 0.4.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/bin/auto-tts.mjs CHANGED
@@ -2,17 +2,18 @@
2
2
  /*
3
3
  * auto-tts command line entry point.
4
4
  *
5
- * `auto-tts web` is the one command a user needs: it prepares a private Python
6
- * environment on first run, installs the backend dependencies into it, then
7
- * serves the API and the bundled frontend from a single port.
5
+ * `auto-tts web` prepares a private Python environment on first run, then
6
+ * serves the API and the bundled frontend from a single port. `say`, `voices`
7
+ * and `tones` run edge-tts directly, without a server, so scripts and agent
8
+ * tools can synthesise audio and inspect voices on their own.
8
9
  */
9
10
 
10
11
  import { spawn, spawnSync } from 'node:child_process'
11
12
  import { createHash } from 'node:crypto'
12
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
13
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
13
14
  import net from 'node:net'
14
15
  import { homedir } from 'node:os'
15
- import { dirname, join, resolve } from 'node:path'
16
+ import { delimiter, dirname, join, resolve } from 'node:path'
16
17
  import { fileURLToPath } from 'node:url'
17
18
 
18
19
  const HERE = dirname(fileURLToPath(import.meta.url))
@@ -23,26 +24,40 @@ const REQUIREMENTS = join(BACKEND_DIR, 'requirements.txt')
23
24
 
24
25
  const STATE_HOME = process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share')
25
26
  const STATE_DIR = join(STATE_HOME, 'auto-tts')
26
- const VENV_DIR = join(STATE_DIR, 'venv')
27
- const VENV_PYTHON = join(VENV_DIR, 'bin', 'python')
27
+ const VENV_DIR = resolve(process.env.AUTO_TTS_VENV_DIR || join(STATE_DIR, 'venv'))
28
+ const VENV_PYTHON = process.platform === 'win32'
29
+ ? join(VENV_DIR, 'Scripts', 'python.exe')
30
+ : join(VENV_DIR, 'bin', 'python')
31
+ const STAMP_FILE = join(VENV_DIR, '.requirements.sha256')
28
32
  const DATA_DIR = join(STATE_DIR, 'data')
29
33
 
30
34
  const DEFAULT_HOST = '127.0.0.1'
31
35
  const DEFAULT_PORT = 8000
36
+ const MIN_PYTHON = [3, 9]
37
+ const LOCAL_COMMANDS = ['say', 'voices', 'tones']
38
+ const WEB_COMMANDS = ['web', 'serve', 'start']
32
39
 
33
40
  function usage() {
34
41
  process.stdout.write(`auto-tts — unlimited text to speech
35
42
 
36
43
  Usage
37
- auto-tts web [options] start the web UI and open it in your browser
38
- auto-tts --help show this message
39
- auto-tts --version show the version
44
+ auto-tts web [options] serve the web UI (default command)
45
+ auto-tts say <text> [options] synthesise text to an mp3, no server needed
46
+ auto-tts voices [options] list the available voices
47
+ auto-tts tones list the speaking-tone presets
48
+ auto-tts --help show this message
49
+ auto-tts --version show the version
40
50
 
41
51
  Options for "web"
42
- --port <number> port to listen on (default ${DEFAULT_PORT})
43
- --host <address> address to bind (default ${DEFAULT_HOST})
44
- --no-open do not open a browser window
45
- --reset rebuild the Python environment before starting
52
+ --port <number> port to listen on (default ${DEFAULT_PORT})
53
+ --host <address> address to bind (default ${DEFAULT_HOST})
54
+ --no-open do not open a browser window
55
+ --reset rebuild the Python environment before starting
56
+ --json print one JSON line with the URL once ready
57
+
58
+ The web command is also available as "serve" and "start". say, voices and
59
+ tones support --json for machine-readable output; run "auto-tts say --help",
60
+ "auto-tts voices --help" or "auto-tts tones --help" for their options.
46
61
  `)
47
62
  }
48
63
 
@@ -51,96 +66,147 @@ function fail(message) {
51
66
  process.exit(1)
52
67
  }
53
68
 
54
- function parseArgs(argv) {
69
+ function printVersion() {
70
+ const manifest = JSON.parse(readFileSync(join(PACKAGE_ROOT, 'package.json'), 'utf8'))
71
+ process.stdout.write(`${manifest.version}\n`)
72
+ }
73
+
74
+ /**
75
+ * Split argv into a command plus its remaining arguments. The command is the
76
+ * first bare word; when it is missing the implicit "web" command is used, and
77
+ * the value of a web option must not be mistaken for it.
78
+ */
79
+ function splitCommand(argv) {
80
+ const args = []
81
+ let command = null
82
+ for (let index = 0; index < argv.length; index += 1) {
83
+ const arg = argv[index]
84
+ if (command === null && !arg.startsWith('-')) {
85
+ command = arg
86
+ continue
87
+ }
88
+ args.push(arg)
89
+ if (command === null && (arg === '--port' || arg === '--host') && index + 1 < argv.length) {
90
+ args.push(argv[index + 1])
91
+ index += 1
92
+ }
93
+ }
94
+ return { command: command ?? 'web', args }
95
+ }
96
+
97
+ function parseWebArgs(args) {
55
98
  const options = {
56
- command: 'web',
57
99
  host: process.env.AUTO_TTS_HOST || DEFAULT_HOST,
58
100
  port: Number(process.env.AUTO_TTS_PORT || DEFAULT_PORT),
59
101
  open: true,
60
102
  reset: false,
103
+ json: false,
61
104
  }
62
105
 
63
- const rest = [...argv]
64
- if (rest.length > 0 && !rest[0].startsWith('-')) {
65
- options.command = rest.shift()
66
- }
106
+ for (let index = 0; index < args.length; index += 1) {
107
+ const arg = args[index]
108
+ if (arg === '-h' || arg === '--help') return { help: true }
109
+ if (arg === '-v' || arg === '--version') return { version: true }
110
+
111
+ const equals = arg.indexOf('=')
112
+ const name = equals === -1 ? arg : arg.slice(0, equals)
113
+ const inline = equals === -1 ? null : arg.slice(equals + 1)
114
+ const value = () => {
115
+ if (inline !== null) return inline
116
+ index += 1
117
+ if (index >= args.length) fail(`option ${name} requires a value`)
118
+ return args[index]
119
+ }
120
+ const flag = () => {
121
+ if (inline !== null) fail(`option ${name} does not take a value`)
122
+ }
67
123
 
68
- while (rest.length > 0) {
69
- const arg = rest.shift()
70
- switch (arg) {
71
- case '--port':
72
- options.port = Number(rest.shift())
124
+ switch (name) {
125
+ case '--port': {
126
+ const raw = value()
127
+ const port = Number(raw)
128
+ if (!Number.isInteger(port) || port < 1 || port > 65535) fail(`invalid port "${raw}"`)
129
+ options.port = port
73
130
  break
131
+ }
74
132
  case '--host':
75
- options.host = rest.shift()
133
+ options.host = value()
134
+ if (!options.host) fail('option --host requires a value')
76
135
  break
77
136
  case '--no-open':
137
+ flag()
78
138
  options.open = false
79
139
  break
80
140
  case '--reset':
141
+ flag()
81
142
  options.reset = true
82
143
  break
83
- case '-h':
84
- case '--help':
85
- options.command = 'help'
86
- break
87
- case '-v':
88
- case '--version':
89
- options.command = 'version'
144
+ case '--json':
145
+ flag()
146
+ options.json = true
90
147
  break
91
148
  default:
92
149
  fail(`unknown option "${arg}" (try "auto-tts --help")`)
93
150
  }
94
151
  }
95
152
 
96
- if (!Number.isInteger(options.port) || options.port < 1 || options.port > 65535) {
97
- fail(`invalid port "${options.port}"`)
98
- }
99
- return options
153
+ return { options }
154
+ }
155
+
156
+ function hashFile(path) {
157
+ return createHash('sha256').update(readFileSync(path)).digest('hex')
100
158
  }
101
159
 
102
- /** Find a usable Python 3 interpreter, newest naming first. */
160
+ /** Find a usable Python interpreter, newest naming first. */
103
161
  function findPython() {
104
- for (const candidate of ['python3', 'python']) {
105
- const probe = spawnSync(candidate, ['-c', 'import sys; print(sys.version_info[0])'], {
106
- encoding: 'utf8',
107
- })
108
- if (probe.status === 0 && probe.stdout.trim() === '3') {
109
- return candidate
162
+ const candidates = process.platform === 'win32'
163
+ ? [['python3', []], ['python', []], ['py', ['-3']]]
164
+ : [['python3', []], ['python', []]]
165
+
166
+ for (const [command, prefix] of candidates) {
167
+ const probe = spawnSync(
168
+ command,
169
+ [...prefix, '-c', 'import sys; print("%d.%d" % sys.version_info[:2])'],
170
+ { encoding: 'utf8' },
171
+ )
172
+ if (probe.status !== 0 || !probe.stdout) continue
173
+ const [major, minor] = probe.stdout.trim().split('.').map(Number)
174
+ if (major > MIN_PYTHON[0] || (major === MIN_PYTHON[0] && minor >= MIN_PYTHON[1])) {
175
+ return [command, prefix]
110
176
  }
111
177
  }
112
- fail('Python 3 is required but was not found on PATH. Install it, then run this command again.')
178
+ fail(
179
+ `Python ${MIN_PYTHON[0]}.${MIN_PYTHON[1]} or newer is required but was not found on PATH.\n` +
180
+ ' Install it, then run this command again.',
181
+ )
113
182
  }
114
183
 
115
- function run(command, args, options = {}) {
116
- const result = spawnSync(command, args, { stdio: 'inherit', ...options })
117
- return result.status === 0
184
+ function run(command, args) {
185
+ const result = spawnSync(command, args, { stdio: 'inherit' })
186
+ return !result.error && result.status === 0
118
187
  }
119
188
 
120
189
  /**
121
- * The dependency set is considered current when the recorded hash of
122
- * requirements.txt matches and every package still imports.
190
+ * The dependency set is current when the recorded hash of requirements.txt
191
+ * matches and every package still imports.
123
192
  */
124
193
  function pythonEnvIsReady() {
125
194
  if (!existsSync(VENV_PYTHON)) return false
195
+ if (!existsSync(STAMP_FILE)) return false
196
+ if (readFileSync(STAMP_FILE, 'utf8').trim() !== hashFile(REQUIREMENTS)) return false
126
197
 
127
- const stampPath = join(STATE_DIR, 'requirements.sha256')
128
- const expected = createHash('sha256').update(readFileSync(REQUIREMENTS)).digest('hex')
129
- if (!existsSync(stampPath) || readFileSync(stampPath, 'utf8').trim() !== expected) return false
130
-
131
- const probe = spawnSync(
132
- VENV_PYTHON,
133
- ['-c', 'import edge_tts, fastapi, uvicorn'],
134
- { stdio: 'ignore' },
135
- )
198
+ const probe = spawnSync(VENV_PYTHON, ['-c', 'import edge_tts, fastapi, uvicorn'], {
199
+ stdio: 'ignore',
200
+ })
136
201
  return probe.status === 0
137
202
  }
138
203
 
139
204
  function createPythonEnv() {
140
- mkdirSync(STATE_DIR, { recursive: true })
141
- process.stdout.write('==> Setting up the Python environment (first run only)\n')
205
+ mkdirSync(dirname(VENV_DIR), { recursive: true })
206
+ process.stderr.write('==> Setting up the Python environment (first run only)\n')
142
207
 
143
- if (!run(findPython(), ['-m', 'venv', VENV_DIR])) {
208
+ const [command, prefix] = findPython()
209
+ if (!run(command, [...prefix, '-m', 'venv', VENV_DIR])) {
144
210
  fail(
145
211
  'could not create a Python virtualenv. On Debian or Ubuntu install python3-venv, then retry.',
146
212
  )
@@ -148,13 +214,39 @@ function createPythonEnv() {
148
214
  }
149
215
 
150
216
  function installPythonDeps() {
151
- process.stdout.write('==> Installing Python dependencies\n')
217
+ process.stderr.write('==> Installing Python dependencies\n')
152
218
  run(VENV_PYTHON, ['-m', 'pip', 'install', '--quiet', '--upgrade', 'pip'])
153
219
  if (!run(VENV_PYTHON, ['-m', 'pip', 'install', '--quiet', '-r', REQUIREMENTS])) {
154
220
  fail('could not install the Python dependencies (check your network connection).')
155
221
  }
156
- const digest = createHash('sha256').update(readFileSync(REQUIREMENTS)).digest('hex')
157
- writeFileSync(join(STATE_DIR, 'requirements.sha256'), `${digest}\n`)
222
+ writeFileSync(STAMP_FILE, `${hashFile(REQUIREMENTS)}\n`)
223
+ }
224
+
225
+ function ensurePythonEnv(options = {}) {
226
+ if (options.reset && existsSync(VENV_DIR)) {
227
+ process.stderr.write('==> Resetting the Python environment\n')
228
+ rmSync(VENV_DIR, { recursive: true, force: true })
229
+ }
230
+ if (!existsSync(VENV_PYTHON)) createPythonEnv()
231
+ if (!pythonEnvIsReady()) installPythonDeps()
232
+ }
233
+
234
+ /** Run one of the local commands through the backend's Python environment. */
235
+ function runLocal(command, args) {
236
+ ensurePythonEnv()
237
+ const env = {
238
+ ...process.env,
239
+ AUTO_TTS_DATA_DIR: DATA_DIR,
240
+ PYTHONPATH: process.env.PYTHONPATH
241
+ ? `${BACKEND_DIR}${delimiter}${process.env.PYTHONPATH}`
242
+ : BACKEND_DIR,
243
+ }
244
+ const result = spawnSync(VENV_PYTHON, ['-m', 'app.cli', command, ...args], {
245
+ stdio: 'inherit',
246
+ env,
247
+ })
248
+ if (result.error) fail(`could not start the Python backend: ${result.error.message}`)
249
+ process.exit(result.status ?? 1)
158
250
  }
159
251
 
160
252
  function isPortFree(host, port) {
@@ -211,10 +303,12 @@ async function openBrowser(url) {
211
303
 
212
304
  /** Wait until something accepts TCP connections on the given address. */
213
305
  function waitForServer(host, port, timeoutMs = 30000) {
306
+ // A wildcard bind cannot be connected to directly on every platform.
307
+ const probeHost = host === '0.0.0.0' || host === '::' ? '127.0.0.1' : host
214
308
  const deadline = Date.now() + timeoutMs
215
309
  return new Promise((resolve) => {
216
310
  const attempt = () => {
217
- const socket = net.createConnection({ host, port })
311
+ const socket = net.createConnection({ host: probeHost, port })
218
312
  socket.once('connect', () => {
219
313
  socket.destroy()
220
314
  resolve(true)
@@ -234,13 +328,7 @@ async function startWeb(options) {
234
328
  fail('the bundled frontend is missing. Reinstall the package, or run npm run build in the repo.')
235
329
  }
236
330
 
237
- if (options.reset && existsSync(VENV_DIR)) {
238
- process.stdout.write('==> Resetting the Python environment\n')
239
- run('rm', ['-rf', VENV_DIR])
240
- }
241
-
242
- if (!existsSync(VENV_PYTHON)) createPythonEnv()
243
- if (!pythonEnvIsReady()) installPythonDeps()
331
+ ensurePythonEnv({ reset: options.reset })
244
332
 
245
333
  if (!isPortFree(options.host, options.port)) {
246
334
  process.stderr.write(
@@ -289,38 +377,55 @@ async function startWeb(options) {
289
377
  process.on('SIGTERM', () => shutdown('SIGTERM'))
290
378
  server.on('exit', (code) => process.exit(code ?? 0))
291
379
 
292
- // Open the page only once the port actually answers, so the browser never
293
- // races the server and lands on a connection error.
294
- if (options.open && (await waitForServer(options.host, options.port))) {
295
- if (!(await openBrowser(url))) {
296
- process.stderr.write(`auto-tts: could not open a browser — visit ${url}\n`)
297
- }
380
+ // The address is only announced once the port actually answers, so neither
381
+ // the browser nor a caller's next request races the server.
382
+ if (!(await waitForServer(options.host, options.port))) {
383
+ shutdown('SIGTERM')
384
+ fail(`the server did not start within 30 seconds. Check the output above, then retry.`)
385
+ }
386
+
387
+ if (options.open && !(await openBrowser(url))) {
388
+ process.stderr.write(`auto-tts: could not open a browser — visit ${url}\n`)
298
389
  }
299
390
 
300
- process.stdout.write(`${url}\n`)
391
+ process.stdout.write(
392
+ options.json
393
+ ? `${JSON.stringify({ url, host: options.host, port: options.port })}\n`
394
+ : `${url}\n`,
395
+ )
301
396
  }
302
397
 
303
398
  async function main() {
304
- const options = parseArgs(process.argv.slice(2))
305
-
306
- switch (options.command) {
307
- case 'web':
308
- case 'serve':
309
- case 'start':
310
- await startWeb(options)
311
- break
312
- case 'help':
399
+ const { command, args } = splitCommand(process.argv.slice(2))
400
+
401
+ if (command === 'help') {
402
+ usage()
403
+ return
404
+ }
405
+ if (command === 'version') {
406
+ printVersion()
407
+ return
408
+ }
409
+ if (WEB_COMMANDS.includes(command)) {
410
+ const parsed = parseWebArgs(args)
411
+ if (parsed.help) {
313
412
  usage()
314
- break
315
- case 'version': {
316
- const manifest = JSON.parse(readFileSync(join(PACKAGE_ROOT, 'package.json'), 'utf8'))
317
- process.stdout.write(`${manifest.version}\n`)
318
- break
413
+ return
319
414
  }
320
- default:
321
- usage()
322
- fail(`unknown command "${options.command}"`)
415
+ if (parsed.version) {
416
+ printVersion()
417
+ return
418
+ }
419
+ await startWeb(parsed.options)
420
+ return
421
+ }
422
+ if (LOCAL_COMMANDS.includes(command)) {
423
+ runLocal(command, args)
424
+ return
323
425
  }
426
+
427
+ usage()
428
+ fail(`unknown command "${command}" (try "auto-tts --help")`)
324
429
  }
325
430
 
326
- main().catch((error) => fail(error.message))
431
+ main().catch((error) => fail(error.message))