auto-tts 0.1.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.
@@ -0,0 +1,326 @@
1
+ #!/usr/bin/env node
2
+ /*
3
+ * auto-tts command line entry point.
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.
8
+ */
9
+
10
+ import { spawn, spawnSync } from 'node:child_process'
11
+ import { createHash } from 'node:crypto'
12
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
13
+ import net from 'node:net'
14
+ import { homedir } from 'node:os'
15
+ import { dirname, join, resolve } from 'node:path'
16
+ import { fileURLToPath } from 'node:url'
17
+
18
+ const HERE = dirname(fileURLToPath(import.meta.url))
19
+ const PACKAGE_ROOT = resolve(HERE, '..')
20
+ const BACKEND_DIR = join(PACKAGE_ROOT, 'backend')
21
+ const FRONTEND_DIST = join(PACKAGE_ROOT, 'frontend', 'dist')
22
+ const REQUIREMENTS = join(BACKEND_DIR, 'requirements.txt')
23
+
24
+ const STATE_HOME = process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share')
25
+ 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')
28
+ const DATA_DIR = join(STATE_DIR, 'data')
29
+
30
+ const DEFAULT_HOST = '127.0.0.1'
31
+ const DEFAULT_PORT = 8000
32
+
33
+ function usage() {
34
+ process.stdout.write(`auto-tts — unlimited text to speech
35
+
36
+ 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
40
+
41
+ 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
46
+ `)
47
+ }
48
+
49
+ function fail(message) {
50
+ process.stderr.write(`auto-tts: ${message}\n`)
51
+ process.exit(1)
52
+ }
53
+
54
+ function parseArgs(argv) {
55
+ const options = {
56
+ command: 'web',
57
+ host: process.env.AUTO_TTS_HOST || DEFAULT_HOST,
58
+ port: Number(process.env.AUTO_TTS_PORT || DEFAULT_PORT),
59
+ open: true,
60
+ reset: false,
61
+ }
62
+
63
+ const rest = [...argv]
64
+ if (rest.length > 0 && !rest[0].startsWith('-')) {
65
+ options.command = rest.shift()
66
+ }
67
+
68
+ while (rest.length > 0) {
69
+ const arg = rest.shift()
70
+ switch (arg) {
71
+ case '--port':
72
+ options.port = Number(rest.shift())
73
+ break
74
+ case '--host':
75
+ options.host = rest.shift()
76
+ break
77
+ case '--no-open':
78
+ options.open = false
79
+ break
80
+ case '--reset':
81
+ options.reset = true
82
+ break
83
+ case '-h':
84
+ case '--help':
85
+ options.command = 'help'
86
+ break
87
+ case '-v':
88
+ case '--version':
89
+ options.command = 'version'
90
+ break
91
+ default:
92
+ fail(`unknown option "${arg}" (try "auto-tts --help")`)
93
+ }
94
+ }
95
+
96
+ if (!Number.isInteger(options.port) || options.port < 1 || options.port > 65535) {
97
+ fail(`invalid port "${options.port}"`)
98
+ }
99
+ return options
100
+ }
101
+
102
+ /** Find a usable Python 3 interpreter, newest naming first. */
103
+ 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
110
+ }
111
+ }
112
+ fail('Python 3 is required but was not found on PATH. Install it, then run this command again.')
113
+ }
114
+
115
+ function run(command, args, options = {}) {
116
+ const result = spawnSync(command, args, { stdio: 'inherit', ...options })
117
+ return result.status === 0
118
+ }
119
+
120
+ /**
121
+ * The dependency set is considered current when the recorded hash of
122
+ * requirements.txt matches and every package still imports.
123
+ */
124
+ function pythonEnvIsReady() {
125
+ if (!existsSync(VENV_PYTHON)) return false
126
+
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
+ )
136
+ return probe.status === 0
137
+ }
138
+
139
+ function createPythonEnv() {
140
+ mkdirSync(STATE_DIR, { recursive: true })
141
+ process.stdout.write('==> Setting up the Python environment (first run only)\n')
142
+
143
+ if (!run(findPython(), ['-m', 'venv', VENV_DIR])) {
144
+ fail(
145
+ 'could not create a Python virtualenv. On Debian or Ubuntu install python3-venv, then retry.',
146
+ )
147
+ }
148
+ }
149
+
150
+ function installPythonDeps() {
151
+ process.stdout.write('==> Installing Python dependencies\n')
152
+ run(VENV_PYTHON, ['-m', 'pip', 'install', '--quiet', '--upgrade', 'pip'])
153
+ if (!run(VENV_PYTHON, ['-m', 'pip', 'install', '--quiet', '-r', REQUIREMENTS])) {
154
+ fail('could not install the Python dependencies (check your network connection).')
155
+ }
156
+ const digest = createHash('sha256').update(readFileSync(REQUIREMENTS)).digest('hex')
157
+ writeFileSync(join(STATE_DIR, 'requirements.sha256'), `${digest}\n`)
158
+ }
159
+
160
+ function isPortFree(host, port) {
161
+ const script = [
162
+ 'import socket, sys',
163
+ 'sock = socket.socket()',
164
+ 'sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)',
165
+ 'try:',
166
+ ' sock.bind((sys.argv[1], int(sys.argv[2])))',
167
+ 'except OSError:',
168
+ ' sys.exit(1)',
169
+ 'finally:',
170
+ ' sock.close()',
171
+ ].join('\n')
172
+ return spawnSync(VENV_PYTHON, ['-c', script, host, String(port)]).status === 0
173
+ }
174
+
175
+ /** Candidate opener commands for the current platform, most preferred first. */
176
+ function browserCandidates(url) {
177
+ if (process.platform === 'darwin') {
178
+ return [['open', [url]]]
179
+ }
180
+ if (process.platform === 'win32') {
181
+ return [['cmd', ['/c', 'start', '', url]]]
182
+ }
183
+ // Linux. Under WSL xdg-open usually is not installed, so prefer the helpers
184
+ // that bridge to the Windows host.
185
+ const candidates = []
186
+ if (process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP) {
187
+ candidates.push(['wslview', [url]], ['cmd.exe', ['/c', 'start', '', url]])
188
+ }
189
+ candidates.push(['xdg-open', [url]], ['gio', ['open', url]], ['sensible-browser', [url]])
190
+ return candidates
191
+ }
192
+
193
+ /** Resolve true when the command actually started, false when it is missing. */
194
+ function tryOpen(command, args) {
195
+ return new Promise((resolve) => {
196
+ const child = spawn(command, args, { stdio: 'ignore', detached: true })
197
+ child.once('error', () => resolve(false))
198
+ child.once('spawn', () => {
199
+ child.unref()
200
+ resolve(true)
201
+ })
202
+ })
203
+ }
204
+
205
+ async function openBrowser(url) {
206
+ for (const [command, args] of browserCandidates(url)) {
207
+ if (await tryOpen(command, args)) return true
208
+ }
209
+ return false
210
+ }
211
+
212
+ /** Wait until something accepts TCP connections on the given address. */
213
+ function waitForServer(host, port, timeoutMs = 30000) {
214
+ const deadline = Date.now() + timeoutMs
215
+ return new Promise((resolve) => {
216
+ const attempt = () => {
217
+ const socket = net.createConnection({ host, port })
218
+ socket.once('connect', () => {
219
+ socket.destroy()
220
+ resolve(true)
221
+ })
222
+ socket.once('error', () => {
223
+ socket.destroy()
224
+ if (Date.now() >= deadline) resolve(false)
225
+ else setTimeout(attempt, 120)
226
+ })
227
+ }
228
+ attempt()
229
+ })
230
+ }
231
+
232
+ async function startWeb(options) {
233
+ if (!existsSync(join(FRONTEND_DIST, 'index.html'))) {
234
+ fail('the bundled frontend is missing. Reinstall the package, or run npm run build in the repo.')
235
+ }
236
+
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()
244
+
245
+ if (!isPortFree(options.host, options.port)) {
246
+ process.stderr.write(
247
+ `auto-tts: port ${options.port} is already in use.\n` +
248
+ ` If auto-tts is already running, open http://${options.host}:${options.port}\n` +
249
+ ` Otherwise stop the process holding it, or pass --port <number>.\n`,
250
+ )
251
+ process.exit(1)
252
+ }
253
+
254
+ const url = `http://${options.host}:${options.port}`
255
+
256
+ // The package directory is treated as read-only, so both the generated audio
257
+ // and the frontend location are handed to the server explicitly. Warnings
258
+ // still surface, but uvicorn's startup banner and access log stay hidden so
259
+ // the only thing a user normally sees is the address below.
260
+ const server = spawn(
261
+ VENV_PYTHON,
262
+ [
263
+ '-m',
264
+ 'uvicorn',
265
+ 'app.main:app',
266
+ '--app-dir',
267
+ BACKEND_DIR,
268
+ '--host',
269
+ options.host,
270
+ '--port',
271
+ String(options.port),
272
+ '--log-level',
273
+ 'warning',
274
+ ],
275
+ {
276
+ stdio: 'inherit',
277
+ env: {
278
+ ...process.env,
279
+ AUTO_TTS_DATA_DIR: DATA_DIR,
280
+ AUTO_TTS_FRONTEND_DIST: FRONTEND_DIST,
281
+ },
282
+ },
283
+ )
284
+
285
+ const shutdown = (signal) => {
286
+ server.kill(signal)
287
+ }
288
+ process.on('SIGINT', () => shutdown('SIGINT'))
289
+ process.on('SIGTERM', () => shutdown('SIGTERM'))
290
+ server.on('exit', (code) => process.exit(code ?? 0))
291
+
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
+ }
298
+ }
299
+
300
+ process.stdout.write(`${url}\n`)
301
+ }
302
+
303
+ 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':
313
+ 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
319
+ }
320
+ default:
321
+ usage()
322
+ fail(`unknown command "${options.command}"`)
323
+ }
324
+ }
325
+
326
+ main().catch((error) => fail(error.message))