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