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/README.md CHANGED
@@ -48,10 +48,53 @@ auto-tts web --port 9000 # 换一个端口(默认 8000)
48
48
  auto-tts web --host 0.0.0.0 # 允许局域网内其它设备访问
49
49
  auto-tts web --no-open # 不自动打开浏览器
50
50
  auto-tts web --reset # 重建 Python 环境后启动
51
+ auto-tts say "你好" -o hello.mp3 # 直接合成 mp3,不启动服务
52
+ auto-tts voices # 查看可用音色
51
53
  auto-tts --help # 查看全部用法
52
54
  auto-tts --version # 查看版本
53
55
  ```
54
56
 
57
+ ### 直接合成(无需启动服务)
58
+
59
+ `auto-tts` 也可以当作普通命令行工具使用,直接调用 edge-tts,不启动 Web 服务:
60
+
61
+ ```bash
62
+ auto-tts say "你好,世界" -o hello.mp3 # 合成到文件
63
+ auto-tts say "你好" -o hello.mp3 --srt # 同时生成同名字幕
64
+ echo "很长的文章" | auto-tts say - -o article.mp3 # 文本从 stdin 读入
65
+ auto-tts say --file article.txt -v zh-CN-YunxiNeural -t newscast -o article.mp3
66
+ auto-tts say "stream" -o - > out.mp3 # 音频写到 stdout
67
+ auto-tts say --batch -f scenes.txt -o out/ --srt # 空行分段,每段生成独立 mp3+SRT
68
+ cat scenes.txt | auto-tts say - --batch -o out/ --srt --json
69
+ auto-tts voices --locale zh-CN --gender female
70
+ auto-tts tones # 查看语气预设
71
+ ```
72
+
73
+ 文本可以来自参数、`-`(stdin)或 `--file`;`-o` 省略时在当前目录生成 `auto-tts-<时间戳>.mp3`;音色默认 `zh-CN-XiaoxiaoNeural`(与网页版一致),`-t/--tone` 可用 `auto-tts tones` 查看,`--rate/--volume/--pitch` 会覆盖语气预设。完整参数见 `auto-tts say --help`。
74
+
75
+ `--batch` 把输入按空行分段(与网页版批量模式一致),每段生成一个独立的 mp3:`-o` 此时是输出目录(省略时新建 `auto-tts-<时间戳>/`),`--srt` 会为每段生成同名字幕,文件按 `001.mp3`、`002.mp3` 顺序编号(段数多时自动扩位)。单段失败不会中断其余分段,全部成功时退出码为 0,否则为 1。
76
+
77
+ ### 给脚本和 Agent 用的 --json
78
+
79
+ `say`、`voices`、`tones` 都支持 `--json`:成功时 stdout 只输出一个 JSON 对象,失败时输出 `{"ok": false, "error": "..."}` 并以非零退出码结束。进度和提示始终走 stderr,便于管道和自动解析。
80
+
81
+ ```bash
82
+ auto-tts voices --locale zh --json
83
+ # {"ok": true, "count": 14, "voices": [{"name": "zh-CN-XiaoxiaoNeural", ...}]}
84
+
85
+ auto-tts say "内容" -o out.mp3 --srt --json
86
+ # {"ok": true, "path": "/abs/out.mp3", "srt_path": "/abs/out.srt", "size_bytes": 27936, ...}
87
+
88
+ auto-tts say --batch -f scenes.txt -o out/ --srt --json
89
+ # {"ok": true, "dir": "out", "count": 2, "succeeded": 2, "failed": 0,
90
+ # "results": [{"index": 1, "path": "out/001.mp3", "srt_path": "out/001.srt", "ok": true, ...}, ...]}
91
+
92
+ auto-tts web --no-open --json
93
+ # 服务就绪后输出一行:{"url": "http://127.0.0.1:8000", "host": "127.0.0.1", "port": 8000}
94
+ ```
95
+
96
+ 批量模式下若部分分段失败,`ok` 为 false,`results` 中逐项给出 `error`,其余分段照常生成,退出码为 1。
97
+
55
98
  ## 功能
56
99
 
57
100
  - **音色**:322 个 edge-tts 音色,可按语言区域或名称筛选
@@ -60,6 +103,7 @@ auto-tts --version # 查看版本
60
103
  - **批量队列**:用空行分隔多段文本,每段成为一个独立任务
61
104
  - **任务面板**:实时进度、失败原因、试听、下载 mp3
62
105
  - **字幕导出**:任务完成后可下载与音频逐句对齐的 SRT 字幕
106
+ - **命令行**:`say` 直接合成 mp3,`--batch` 按空行分段批量生成 mp3 和 SRT,`voices`/`tones` 查询音色和语气,支持 `--json`,方便脚本和 Agent 调用
63
107
 
64
108
  ### 关于语气
65
109
 
@@ -71,12 +115,11 @@ edge-tts 本身**不支持**真正的情感风格(微软服务端会拒绝 `<m
71
115
 
72
116
  ```
73
117
  ~/.local/share/auto-tts/
74
- ├── venv/ # Python 虚拟环境
75
- ├── data/audio/ # 生成的 mp3
76
- └── requirements.sha256 # 依赖指纹,用于判断是否需要重装
118
+ ├── venv/ # Python 虚拟环境(依赖指纹 .requirements.sha256 存在此处)
119
+ └── data/audio/ # 生成的 mp3
77
120
  ```
78
121
 
79
- `requirements.txt` 改动后,下次启动会自动识别并重装依赖。
122
+ `requirements.txt` 改动后,下次启动会自动识别并重装依赖。设置环境变量 `AUTO_TTS_VENV_DIR` 可以把虚拟环境放到别处(例如复用源码目录下的 `.venv`)。
80
123
 
81
124
  ## 从源码运行
82
125
 
@@ -0,0 +1,529 @@
1
+ """Local command line interface: `say`, `voices` and `tones`.
2
+
3
+ These commands drive edge-tts directly and never start the HTTP server, so
4
+ scripts and agent tools can synthesise audio without a service running. Results
5
+ go to stdout, progress and diagnostics to stderr, and `--json` turns the result
6
+ into a single machine-readable object. `say --batch` turns one input with
7
+ blank-line separated segments into one mp3 (and optional srt) per segment.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import asyncio
14
+ import json
15
+ import re
16
+ import shutil
17
+ import sys
18
+ import tempfile
19
+ import time
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from . import tts
24
+
25
+ # Matches the frontend's default voice so the CLI and the web UI sound alike.
26
+ DEFAULT_VOICE = "zh-CN-XiaoxiaoNeural"
27
+
28
+ # edge-tts streams 48 kbps CBR mono mp3: 6000 bytes per second.
29
+ _BYTES_PER_SECOND = 6 * 1000
30
+
31
+ # Batch segments are blank-line separated blocks, exactly like the web UI's
32
+ # batch mode, so the same input produces the same segmentation in both places.
33
+ _SEGMENT_BREAK = re.compile(r"\n\s*\n")
34
+
35
+ # Set before parsing so usage errors can be emitted as JSON as well.
36
+ _JSON_ERRORS = False
37
+
38
+
39
+ class CLIError(Exception):
40
+ """A user-facing failure that is reported without a traceback."""
41
+
42
+
43
+ class _Parser(argparse.ArgumentParser):
44
+ """ArgumentParser that mirrors usage errors as JSON when --json is set."""
45
+
46
+ def error(self, message: str) -> None:
47
+ if _JSON_ERRORS:
48
+ _emit_json({"ok": False, "error": message})
49
+ super().error(message)
50
+
51
+
52
+ def _force_utf8() -> None:
53
+ """Use UTF-8 on stdio so text and voices survive any console codepage."""
54
+ try:
55
+ sys.stdin.reconfigure(encoding="utf-8", errors="replace")
56
+ sys.stdout.reconfigure(encoding="utf-8")
57
+ sys.stderr.reconfigure(encoding="utf-8")
58
+ except (AttributeError, OSError):
59
+ pass
60
+
61
+
62
+ def _emit_json(payload: dict[str, Any]) -> None:
63
+ json.dump(payload, sys.stdout, ensure_ascii=False)
64
+ sys.stdout.write("\n")
65
+ sys.stdout.flush()
66
+
67
+
68
+ def _bounded_int(low: int, high: int):
69
+ """An argparse type that accepts integers within [low, high] only."""
70
+
71
+ def parse(value: str) -> int:
72
+ try:
73
+ number = int(value)
74
+ except ValueError:
75
+ raise argparse.ArgumentTypeError(f"expected an integer, got {value!r}") from None
76
+ if not low <= number <= high:
77
+ raise argparse.ArgumentTypeError(f"must be between {low} and {high}")
78
+ return number
79
+
80
+ return parse
81
+
82
+
83
+ def _display_path(path: Path) -> str:
84
+ """Prefer a path relative to the working directory for human output."""
85
+ try:
86
+ return str(path.relative_to(Path.cwd()))
87
+ except ValueError:
88
+ return str(path)
89
+
90
+
91
+ def _human_size(size: int) -> str:
92
+ value = float(size)
93
+ for unit in ("B", "KB", "MB", "GB"):
94
+ if value < 1024 or unit == "GB":
95
+ return f"{int(value)} B" if unit == "B" else f"{value:.1f} {unit}"
96
+ value /= 1024
97
+ return f"{value:.1f} GB"
98
+
99
+
100
+ def _format_duration(seconds: float) -> str:
101
+ total = int(round(seconds))
102
+ hours, remainder = divmod(total, 3600)
103
+ minutes, secs = divmod(remainder, 60)
104
+ if hours:
105
+ return f"{hours}:{minutes:02d}:{secs:02d}"
106
+ if minutes:
107
+ return f"{minutes}:{secs:02d}"
108
+ return f"{seconds:.1f}s"
109
+
110
+
111
+ class _Progress:
112
+ """Render chunk progress on stderr; silent when stderr is not a TTY."""
113
+
114
+ def __init__(self, enabled: bool, prefix: str = "") -> None:
115
+ self._enabled = enabled
116
+ self._prefix = prefix
117
+ self._last = -1
118
+
119
+ async def __call__(self, value: float) -> None:
120
+ if not self._enabled:
121
+ return
122
+ percent = min(100, int(value * 100))
123
+ if percent == self._last:
124
+ return
125
+ self._last = percent
126
+ sys.stderr.write(f"\r {self._prefix}{percent:3d}%")
127
+ sys.stderr.flush()
128
+
129
+ def done(self) -> None:
130
+ if self._enabled:
131
+ sys.stderr.write("\r" + " " * (6 + len(self._prefix)) + "\r")
132
+ sys.stderr.flush()
133
+
134
+
135
+ # ---------------------------------------------------------------------- say
136
+
137
+
138
+ def _read_text(args: argparse.Namespace) -> str:
139
+ """Resolve the input text from the argument, --file or standard input."""
140
+ if args.file and args.text is not None:
141
+ raise CLIError("give either TEXT or --file, not both")
142
+ if args.file:
143
+ try:
144
+ text = Path(args.file).read_text(encoding="utf-8")
145
+ except OSError as exc:
146
+ raise CLIError(f"cannot read {args.file}: {exc.strerror or exc}") from exc
147
+ elif args.text == "-":
148
+ text = sys.stdin.read()
149
+ elif args.text is not None:
150
+ text = args.text
151
+ elif not sys.stdin.isatty():
152
+ text = sys.stdin.read()
153
+ else:
154
+ raise CLIError("no text given (pass TEXT, '-', --file, or pipe stdin)")
155
+ if not text.strip():
156
+ raise CLIError("the text is empty")
157
+ return text
158
+
159
+
160
+ def _unique_path(path: Path) -> Path:
161
+ """Return *path*, or a numbered sibling when it is already taken."""
162
+ if not path.exists():
163
+ return path
164
+ index = 2
165
+ while True:
166
+ candidate = path.with_name(f"{path.stem}-{index}{path.suffix}")
167
+ if not candidate.exists():
168
+ return candidate
169
+ index += 1
170
+
171
+
172
+ def _default_out_path() -> Path:
173
+ """A fresh `auto-tts-<timestamp>.mp3` path in the working directory."""
174
+ stamp = time.strftime("%Y%m%d-%H%M%S")
175
+ return _unique_path(Path.cwd() / f"auto-tts-{stamp}.mp3")
176
+
177
+
178
+ def _default_batch_dir() -> Path:
179
+ """A fresh `auto-tts-<timestamp>` directory in the working directory."""
180
+ stamp = time.strftime("%Y%m%d-%H%M%S")
181
+ return _unique_path(Path.cwd() / f"auto-tts-{stamp}")
182
+
183
+
184
+ def _resolve_srt(args: argparse.Namespace, out_path: Path | None) -> Path | None:
185
+ """Return the SRT destination; `--srt` alone means next to the audio."""
186
+ if args.srt is None:
187
+ return None
188
+ if args.srt:
189
+ return Path(args.srt)
190
+ if out_path is None:
191
+ raise CLIError("--srt needs a path when the audio goes to stdout")
192
+ return out_path.with_suffix(".srt")
193
+
194
+
195
+ def _resolve_prosody(args: argparse.Namespace) -> tuple[int, int, int]:
196
+ """Apply the tone preset, letting explicit rate/volume/pitch overrides win."""
197
+ preset = next(tone for tone in tts.TONE_PRESETS if tone["key"] == args.tone)
198
+ rate = preset["rate"] if args.rate is None else args.rate
199
+ volume = preset["volume"] if args.volume is None else args.volume
200
+ pitch = preset["pitch"] if args.pitch is None else args.pitch
201
+ return rate, volume, pitch
202
+
203
+
204
+ def _batch_dir(args: argparse.Namespace) -> Path:
205
+ """Resolve the batch output directory, rejecting values that look like files."""
206
+ if not args.out:
207
+ return _default_batch_dir()
208
+ out_dir = Path(args.out)
209
+ if out_dir.is_file():
210
+ raise CLIError(f"--batch needs an output directory, but {args.out} is a file")
211
+ if out_dir.suffix.lower() in (".mp3", ".srt"):
212
+ raise CLIError(f"--batch needs an output directory, but {args.out} looks like a file")
213
+ return out_dir
214
+
215
+
216
+ def _cmd_say_batch(args: argparse.Namespace, text: str) -> int:
217
+ """Synthesise every blank-line separated segment into its own mp3 (+srt)."""
218
+ if args.out == "-":
219
+ raise CLIError("--batch writes one file per segment; -o must be an output directory")
220
+ if args.srt:
221
+ raise CLIError("give --srt without a path in --batch mode; every segment gets its own .srt")
222
+
223
+ segments = [part.strip() for part in _SEGMENT_BREAK.split(text) if part.strip()]
224
+ if not segments:
225
+ raise CLIError("the text is empty")
226
+
227
+ out_dir = _batch_dir(args)
228
+ created_dir = not out_dir.exists()
229
+ rate, volume, pitch = _resolve_prosody(args)
230
+ total = len(segments)
231
+ width = max(3, len(str(total)))
232
+ want_srt = args.srt is not None
233
+ progress_enabled = not args.quiet and sys.stderr.isatty()
234
+
235
+ async def run_all() -> list[dict[str, Any]]:
236
+ results: list[dict[str, Any]] = []
237
+ for index, segment in enumerate(segments, start=1):
238
+ audio_path = out_dir / f"{index:0{width}d}.mp3"
239
+ srt_path = audio_path.with_suffix(".srt") if want_srt else None
240
+ item: dict[str, Any] = {
241
+ "index": index,
242
+ "chars": len(segment),
243
+ "path": str(audio_path),
244
+ "ok": True,
245
+ }
246
+ progress = _Progress(enabled=progress_enabled, prefix=f"[{index}/{total}] ")
247
+ try:
248
+ size = await tts.synthesize(
249
+ segment,
250
+ args.voice,
251
+ tts.format_rate(rate),
252
+ tts.format_volume(volume),
253
+ tts.format_pitch(pitch),
254
+ audio_path,
255
+ srt_path=srt_path,
256
+ on_progress=progress,
257
+ )
258
+ except Exception as exc: # noqa: BLE001 - one bad segment must not stop the batch
259
+ item["ok"] = False
260
+ item["error"] = str(exc) or exc.__class__.__name__
261
+ else:
262
+ item["size_bytes"] = size
263
+ item["duration_seconds"] = round(size / _BYTES_PER_SECOND, 1)
264
+ item["srt_path"] = (
265
+ str(srt_path) if srt_path is not None and srt_path.is_file() else None
266
+ )
267
+ progress.done()
268
+ results.append(item)
269
+ return results
270
+
271
+ results = asyncio.run(run_all())
272
+ failed = sum(1 for item in results if not item["ok"])
273
+ if created_dir:
274
+ # A run that produced no files should not leave an empty directory behind.
275
+ try:
276
+ out_dir.rmdir()
277
+ except OSError:
278
+ pass
279
+ payload: dict[str, Any] = {
280
+ "ok": failed == 0,
281
+ "dir": str(out_dir),
282
+ "count": total,
283
+ "succeeded": total - failed,
284
+ "failed": failed,
285
+ "voice": args.voice,
286
+ "tone": args.tone,
287
+ "rate": rate,
288
+ "volume": volume,
289
+ "pitch": pitch,
290
+ "results": results,
291
+ }
292
+
293
+ if args.json:
294
+ _emit_json(payload)
295
+ else:
296
+ for item in results:
297
+ if not item["ok"]:
298
+ sys.stderr.write(f"auto-tts: segment {item['index']} failed: {item['error']}\n")
299
+ continue
300
+ sys.stdout.write(
301
+ f"{_display_path(Path(item['path']))} "
302
+ f"({_format_duration(item['duration_seconds'])}, {_human_size(item['size_bytes'])})\n"
303
+ )
304
+ if item["srt_path"]:
305
+ sys.stdout.write(f"{_display_path(Path(item['srt_path']))}\n")
306
+ return 1 if failed else 0
307
+
308
+
309
+ def _cmd_say(args: argparse.Namespace) -> int:
310
+ text = _read_text(args)
311
+ if args.batch:
312
+ return _cmd_say_batch(args, text)
313
+
314
+ rate, volume, pitch = _resolve_prosody(args)
315
+
316
+ to_stdout = args.out == "-"
317
+ if to_stdout and args.json:
318
+ raise CLIError("--json cannot be combined with -o -")
319
+ out_path = None if to_stdout else (Path(args.out) if args.out else _default_out_path())
320
+ srt_path = _resolve_srt(args, out_path)
321
+ if srt_path is not None:
322
+ srt_path.parent.mkdir(parents=True, exist_ok=True)
323
+ progress = _Progress(enabled=not args.quiet and sys.stderr.isatty())
324
+
325
+ async def synth(media_path: Path) -> int:
326
+ return await tts.synthesize(
327
+ text,
328
+ args.voice,
329
+ tts.format_rate(rate),
330
+ tts.format_volume(volume),
331
+ tts.format_pitch(pitch),
332
+ media_path,
333
+ srt_path=srt_path,
334
+ on_progress=progress,
335
+ )
336
+
337
+ if to_stdout:
338
+ with tempfile.TemporaryDirectory(prefix="auto-tts-") as tmp:
339
+ tmp_path = Path(tmp) / "say.mp3"
340
+ size = asyncio.run(synth(tmp_path))
341
+ progress.done()
342
+ with tmp_path.open("rb") as handle:
343
+ shutil.copyfileobj(handle, sys.stdout.buffer)
344
+ sys.stdout.buffer.flush()
345
+ if not args.quiet:
346
+ sys.stderr.write(f"auto-tts: wrote {size} bytes to stdout\n")
347
+ else:
348
+ size = asyncio.run(synth(out_path))
349
+ progress.done()
350
+
351
+ payload: dict[str, Any] = {
352
+ "ok": True,
353
+ "path": None if to_stdout else str(out_path),
354
+ "srt_path": (
355
+ str(srt_path) if srt_path is not None and srt_path.is_file() else None
356
+ ),
357
+ "size_bytes": size,
358
+ "duration_seconds": round(size / _BYTES_PER_SECOND, 1),
359
+ "voice": args.voice,
360
+ "tone": args.tone,
361
+ "rate": rate,
362
+ "volume": volume,
363
+ "pitch": pitch,
364
+ "chars": len(text),
365
+ }
366
+
367
+ if args.json:
368
+ _emit_json(payload)
369
+ elif not to_stdout:
370
+ sys.stdout.write(
371
+ f"{_display_path(out_path)} "
372
+ f"({_format_duration(payload['duration_seconds'])}, {_human_size(size)})\n"
373
+ )
374
+ if payload["srt_path"]:
375
+ sys.stdout.write(f"{_display_path(srt_path)}\n")
376
+ return 0
377
+
378
+
379
+ # ------------------------------------------------------------------- voices
380
+
381
+
382
+ def _cmd_voices(args: argparse.Namespace) -> int:
383
+ voices = asyncio.run(tts.list_voices())
384
+ items = []
385
+ for voice in voices:
386
+ item = {
387
+ "name": voice["ShortName"],
388
+ "locale": voice["Locale"],
389
+ "gender": voice["Gender"],
390
+ "friendly_name": voice.get("FriendlyName", voice["ShortName"]),
391
+ }
392
+ if args.locale and not item["locale"].lower().startswith(args.locale.lower()):
393
+ continue
394
+ if args.gender and item["gender"].lower() != args.gender:
395
+ continue
396
+ items.append(item)
397
+ items.sort(key=lambda item: (item["locale"], item["name"]))
398
+
399
+ if args.json:
400
+ _emit_json({"ok": True, "count": len(items), "voices": items})
401
+ return 0
402
+ if not items:
403
+ sys.stderr.write("auto-tts: no voices matched the filter\n")
404
+ return 0
405
+ width = max(len(item["name"]) for item in items)
406
+ for item in items:
407
+ sys.stdout.write(f"{item['name']:<{width}} {item['gender']:<6} {item['locale']}\n")
408
+ return 0
409
+
410
+
411
+ # -------------------------------------------------------------------- tones
412
+
413
+
414
+ def _cmd_tones(args: argparse.Namespace) -> int:
415
+ tones = tts.list_tones()
416
+ if args.json:
417
+ _emit_json({"ok": True, "count": len(tones), "tones": tones})
418
+ return 0
419
+ for tone in tones:
420
+ sys.stdout.write(
421
+ f"{tone['key']:<10} "
422
+ f"rate {tts.format_rate(tone['rate']):>5} "
423
+ f"volume {tts.format_volume(tone['volume']):>5} "
424
+ f"pitch {tts.format_pitch(tone['pitch']):>6}\n"
425
+ )
426
+ return 0
427
+
428
+
429
+ # ------------------------------------------------------------------ argparse
430
+
431
+
432
+ def _build_parser() -> _Parser:
433
+ parser = _Parser(
434
+ prog="auto-tts",
435
+ description="Local synthesis commands; the HTTP server is not required.",
436
+ )
437
+ subparsers = parser.add_subparsers(dest="command", required=True)
438
+
439
+ common = _Parser(add_help=False)
440
+ common.add_argument("--json", action="store_true", help="print one JSON object to stdout")
441
+ common.add_argument("-q", "--quiet", action="store_true", help="suppress progress output")
442
+
443
+ say = subparsers.add_parser(
444
+ "say",
445
+ parents=[common],
446
+ help="synthesise text to an mp3 file",
447
+ description="Synthesise text to an mp3 file without starting the server.",
448
+ epilog=(
449
+ "examples:\n"
450
+ " auto-tts say \"hello world\" -o hello.mp3\n"
451
+ ' auto-tts say "hello" -o hello.mp3 --srt # subtitles next to the audio\n'
452
+ " echo \"long article\" | auto-tts say - -o article.mp3\n"
453
+ " auto-tts say --file article.txt -v zh-CN-YunxiNeural -t newscast -o article.mp3\n"
454
+ " auto-tts say \"stream me\" -o - > out.mp3 # audio on stdout\n"
455
+ "\n"
456
+ "batch mode (--batch):\n"
457
+ " The input is split on blank lines, exactly like the web UI's batch mode,\n"
458
+ " and every segment becomes its own mp3. -o is then an output directory\n"
459
+ " (default: auto-tts-<timestamp>/ in the working directory) and the files\n"
460
+ " are numbered 001.mp3, 002.mp3, ...; wider numbers appear when needed.\n"
461
+ " --srt without a path writes 001.srt next to each mp3. A failing segment\n"
462
+ " does not stop the rest; the exit code is 1 when any segment failed.\n"
463
+ " With --json, stdout holds one object with count/succeeded/failed and a\n"
464
+ " results array carrying the path, srt_path and error of every segment.\n"
465
+ " auto-tts say --batch --file scenes.txt -o out/ --srt\n"
466
+ " cat scenes.txt | auto-tts say - --batch -o out/ --srt --json\n"
467
+ ),
468
+ formatter_class=argparse.RawDescriptionHelpFormatter,
469
+ )
470
+ say.add_argument("text", nargs="?", default=None, help="text to synthesise; '-' reads stdin")
471
+ say.add_argument("-f", "--file", default=None, metavar="PATH", help="read the text from a UTF-8 file")
472
+ say.add_argument("--batch", action="store_true", help="split the input on blank lines and write one mp3 per segment")
473
+ say.add_argument("-o", "--out", default=None, metavar="PATH", help="output mp3 path (default: auto-named in the working directory; '-' streams to stdout); with --batch an output directory")
474
+ say.add_argument("-v", "--voice", default=DEFAULT_VOICE, metavar="NAME", help=f"edge-tts voice short name (default: {DEFAULT_VOICE})")
475
+ say.add_argument("-t", "--tone", default=tts.DEFAULT_TONE, choices=[tone["key"] for tone in tts.TONE_PRESETS], help=f"tone preset (default: {tts.DEFAULT_TONE})")
476
+ say.add_argument("--rate", type=_bounded_int(-100, 200), default=None, help="speaking rate delta in percent; overrides the tone")
477
+ say.add_argument("--volume", type=_bounded_int(-100, 100), default=None, help="volume delta in percent; overrides the tone")
478
+ say.add_argument("--pitch", type=_bounded_int(-100, 100), default=None, help="pitch delta in Hz; overrides the tone")
479
+ say.add_argument("--srt", nargs="?", const="", default=None, metavar="PATH", help="also write an SRT file; without a path it sits next to the audio (one per segment with --batch)")
480
+
481
+ voices = subparsers.add_parser(
482
+ "voices",
483
+ parents=[common],
484
+ help="list the available voices",
485
+ description="List the edge-tts voice catalogue without starting the server.",
486
+ )
487
+ voices.add_argument("--locale", default=None, metavar="PREFIX", help="only voices whose locale starts with PREFIX (e.g. zh, zh-CN)")
488
+ voices.add_argument("--gender", type=str.lower, choices=["male", "female"], default=None, metavar="GENDER", help="only voices of this gender")
489
+
490
+ subparsers.add_parser(
491
+ "tones",
492
+ parents=[common],
493
+ help="list the speaking-tone presets",
494
+ description="List the speaking-tone presets (rate/volume/pitch triples).",
495
+ )
496
+ return parser
497
+
498
+
499
+ def _run(handler, args: argparse.Namespace) -> int:
500
+ try:
501
+ return handler(args)
502
+ except CLIError as exc:
503
+ message = str(exc)
504
+ except KeyboardInterrupt:
505
+ sys.stderr.write("\nauto-tts: interrupted\n")
506
+ return 130
507
+ except Exception as exc: # noqa: BLE001 - the message is surfaced to the user
508
+ message = str(exc) or exc.__class__.__name__
509
+ if args.json:
510
+ _emit_json({"ok": False, "error": message})
511
+ sys.stderr.write(f"auto-tts: {message}\n")
512
+ return 1
513
+
514
+
515
+ def main(argv: list[str] | None = None) -> int:
516
+ global _JSON_ERRORS
517
+ _force_utf8()
518
+ argv = list(sys.argv[1:] if argv is None else argv)
519
+ _JSON_ERRORS = "--json" in argv
520
+ parser = _build_parser()
521
+ args = parser.parse_args(argv)
522
+ _JSON_ERRORS = args.json
523
+
524
+ handlers = {"say": _cmd_say, "voices": _cmd_voices, "tones": _cmd_tones}
525
+ return _run(handlers[args.command], args)
526
+
527
+
528
+ if __name__ == "__main__":
529
+ raise SystemExit(main())
@@ -1,3 +1,6 @@
1
- edge-tts>=7.2.0
1
+ # 7.3.0 is the first release that emits the Sec-MS-GEC v2 token. Microsoft
2
+ # rejects the v1 token with a 403 WebSocket handshake error, so every older
3
+ # release can no longer synthesise anything.
4
+ edge-tts>=7.3.1
2
5
  fastapi>=0.115.0
3
6
  uvicorn[standard]>=0.30.0