auto-tts 0.4.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
@@ -64,12 +64,16 @@ auto-tts say "你好" -o hello.mp3 --srt # 同时生成同名字幕
64
64
  echo "很长的文章" | auto-tts say - -o article.mp3 # 文本从 stdin 读入
65
65
  auto-tts say --file article.txt -v zh-CN-YunxiNeural -t newscast -o article.mp3
66
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
67
69
  auto-tts voices --locale zh-CN --gender female
68
70
  auto-tts tones # 查看语气预设
69
71
  ```
70
72
 
71
73
  文本可以来自参数、`-`(stdin)或 `--file`;`-o` 省略时在当前目录生成 `auto-tts-<时间戳>.mp3`;音色默认 `zh-CN-XiaoxiaoNeural`(与网页版一致),`-t/--tone` 可用 `auto-tts tones` 查看,`--rate/--volume/--pitch` 会覆盖语气预设。完整参数见 `auto-tts say --help`。
72
74
 
75
+ `--batch` 把输入按空行分段(与网页版批量模式一致),每段生成一个独立的 mp3:`-o` 此时是输出目录(省略时新建 `auto-tts-<时间戳>/`),`--srt` 会为每段生成同名字幕,文件按 `001.mp3`、`002.mp3` 顺序编号(段数多时自动扩位)。单段失败不会中断其余分段,全部成功时退出码为 0,否则为 1。
76
+
73
77
  ### 给脚本和 Agent 用的 --json
74
78
 
75
79
  `say`、`voices`、`tones` 都支持 `--json`:成功时 stdout 只输出一个 JSON 对象,失败时输出 `{"ok": false, "error": "..."}` 并以非零退出码结束。进度和提示始终走 stderr,便于管道和自动解析。
@@ -81,10 +85,16 @@ auto-tts voices --locale zh --json
81
85
  auto-tts say "内容" -o out.mp3 --srt --json
82
86
  # {"ok": true, "path": "/abs/out.mp3", "srt_path": "/abs/out.srt", "size_bytes": 27936, ...}
83
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
+
84
92
  auto-tts web --no-open --json
85
93
  # 服务就绪后输出一行:{"url": "http://127.0.0.1:8000", "host": "127.0.0.1", "port": 8000}
86
94
  ```
87
95
 
96
+ 批量模式下若部分分段失败,`ok` 为 false,`results` 中逐项给出 `error`,其余分段照常生成,退出码为 1。
97
+
88
98
  ## 功能
89
99
 
90
100
  - **音色**:322 个 edge-tts 音色,可按语言区域或名称筛选
@@ -93,7 +103,7 @@ auto-tts web --no-open --json
93
103
  - **批量队列**:用空行分隔多段文本,每段成为一个独立任务
94
104
  - **任务面板**:实时进度、失败原因、试听、下载 mp3
95
105
  - **字幕导出**:任务完成后可下载与音频逐句对齐的 SRT 字幕
96
- - **命令行**:`say` 直接合成 mp3,`voices`/`tones` 查询音色和语气,支持 `--json`,方便脚本和 Agent 调用
106
+ - **命令行**:`say` 直接合成 mp3,`--batch` 按空行分段批量生成 mp3 和 SRT,`voices`/`tones` 查询音色和语气,支持 `--json`,方便脚本和 Agent 调用
97
107
 
98
108
  ### 关于语气
99
109
 
@@ -3,7 +3,8 @@
3
3
  These commands drive edge-tts directly and never start the HTTP server, so
4
4
  scripts and agent tools can synthesise audio without a service running. Results
5
5
  go to stdout, progress and diagnostics to stderr, and `--json` turns the result
6
- into a single machine-readable object.
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.
7
8
  """
8
9
 
9
10
  from __future__ import annotations
@@ -11,6 +12,7 @@ from __future__ import annotations
11
12
  import argparse
12
13
  import asyncio
13
14
  import json
15
+ import re
14
16
  import shutil
15
17
  import sys
16
18
  import tempfile
@@ -26,6 +28,10 @@ DEFAULT_VOICE = "zh-CN-XiaoxiaoNeural"
26
28
  # edge-tts streams 48 kbps CBR mono mp3: 6000 bytes per second.
27
29
  _BYTES_PER_SECOND = 6 * 1000
28
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
+
29
35
  # Set before parsing so usage errors can be emitted as JSON as well.
30
36
  _JSON_ERRORS = False
31
37
 
@@ -105,8 +111,9 @@ def _format_duration(seconds: float) -> str:
105
111
  class _Progress:
106
112
  """Render chunk progress on stderr; silent when stderr is not a TTY."""
107
113
 
108
- def __init__(self, enabled: bool) -> None:
114
+ def __init__(self, enabled: bool, prefix: str = "") -> None:
109
115
  self._enabled = enabled
116
+ self._prefix = prefix
110
117
  self._last = -1
111
118
 
112
119
  async def __call__(self, value: float) -> None:
@@ -116,12 +123,12 @@ class _Progress:
116
123
  if percent == self._last:
117
124
  return
118
125
  self._last = percent
119
- sys.stderr.write(f"\r {percent:3d}%")
126
+ sys.stderr.write(f"\r {self._prefix}{percent:3d}%")
120
127
  sys.stderr.flush()
121
128
 
122
129
  def done(self) -> None:
123
130
  if self._enabled:
124
- sys.stderr.write("\r \r")
131
+ sys.stderr.write("\r" + " " * (6 + len(self._prefix)) + "\r")
125
132
  sys.stderr.flush()
126
133
 
127
134
 
@@ -150,15 +157,28 @@ def _read_text(args: argparse.Namespace) -> str:
150
157
  return text
151
158
 
152
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
+
153
172
  def _default_out_path() -> Path:
154
173
  """A fresh `auto-tts-<timestamp>.mp3` path in the working directory."""
155
174
  stamp = time.strftime("%Y%m%d-%H%M%S")
156
- out_path = Path.cwd() / f"auto-tts-{stamp}.mp3"
157
- index = 2
158
- while out_path.exists():
159
- out_path = Path.cwd() / f"auto-tts-{stamp}-{index}.mp3"
160
- index += 1
161
- return out_path
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}")
162
182
 
163
183
 
164
184
  def _resolve_srt(args: argparse.Namespace, out_path: Path | None) -> Path | None:
@@ -172,13 +192,126 @@ def _resolve_srt(args: argparse.Namespace, out_path: Path | None) -> Path | None
172
192
  return out_path.with_suffix(".srt")
173
193
 
174
194
 
175
- def _cmd_say(args: argparse.Namespace) -> int:
176
- text = _read_text(args)
177
-
195
+ def _resolve_prosody(args: argparse.Namespace) -> tuple[int, int, int]:
196
+ """Apply the tone preset, letting explicit rate/volume/pitch overrides win."""
178
197
  preset = next(tone for tone in tts.TONE_PRESETS if tone["key"] == args.tone)
179
198
  rate = preset["rate"] if args.rate is None else args.rate
180
199
  volume = preset["volume"] if args.volume is None else args.volume
181
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)
182
315
 
183
316
  to_stdout = args.out == "-"
184
317
  if to_stdout and args.json:
@@ -319,18 +452,31 @@ def _build_parser() -> _Parser:
319
452
  " echo \"long article\" | auto-tts say - -o article.mp3\n"
320
453
  " auto-tts say --file article.txt -v zh-CN-YunxiNeural -t newscast -o article.mp3\n"
321
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"
322
467
  ),
323
468
  formatter_class=argparse.RawDescriptionHelpFormatter,
324
469
  )
325
470
  say.add_argument("text", nargs="?", default=None, help="text to synthesise; '-' reads stdin")
326
471
  say.add_argument("-f", "--file", default=None, metavar="PATH", help="read the text from a UTF-8 file")
327
- say.add_argument("-o", "--out", default=None, metavar="PATH", help="output mp3 path (default: auto-named in the working directory; '-' streams to stdout)")
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")
328
474
  say.add_argument("-v", "--voice", default=DEFAULT_VOICE, metavar="NAME", help=f"edge-tts voice short name (default: {DEFAULT_VOICE})")
329
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})")
330
476
  say.add_argument("--rate", type=_bounded_int(-100, 200), default=None, help="speaking rate delta in percent; overrides the tone")
331
477
  say.add_argument("--volume", type=_bounded_int(-100, 100), default=None, help="volume delta in percent; overrides the tone")
332
478
  say.add_argument("--pitch", type=_bounded_int(-100, 100), default=None, help="pitch delta in Hz; overrides the tone")
333
- 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")
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)")
334
480
 
335
481
  voices = subparsers.add_parser(
336
482
  "voices",
package/bin/auto-tts.mjs CHANGED
@@ -43,6 +43,7 @@ function usage() {
43
43
  Usage
44
44
  auto-tts web [options] serve the web UI (default command)
45
45
  auto-tts say <text> [options] synthesise text to an mp3, no server needed
46
+ (--batch: one mp3 per blank-line block)
46
47
  auto-tts voices [options] list the available voices
47
48
  auto-tts tones list the speaking-tone presets
48
49
  auto-tts --help show this message
@@ -56,7 +57,8 @@ Options for "web"
56
57
  --json print one JSON line with the URL once ready
57
58
 
58
59
  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
+ 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",
60
62
  "auto-tts voices --help" or "auto-tts tones --help" for their options.
61
63
  `)
62
64
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "auto-tts",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Unlimited text to speech with selectable voices and speaking tones, powered by edge-tts.",
5
5
  "license": "AGPL-3.0-or-later",
6
6
  "author": "kms413",