auto-tts 0.2.1 → 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/README.md CHANGED
@@ -48,10 +48,43 @@ 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 voices --locale zh-CN --gender female
68
+ auto-tts tones # 查看语气预设
69
+ ```
70
+
71
+ 文本可以来自参数、`-`(stdin)或 `--file`;`-o` 省略时在当前目录生成 `auto-tts-<时间戳>.mp3`;音色默认 `zh-CN-XiaoxiaoNeural`(与网页版一致),`-t/--tone` 可用 `auto-tts tones` 查看,`--rate/--volume/--pitch` 会覆盖语气预设。完整参数见 `auto-tts say --help`。
72
+
73
+ ### 给脚本和 Agent 用的 --json
74
+
75
+ `say`、`voices`、`tones` 都支持 `--json`:成功时 stdout 只输出一个 JSON 对象,失败时输出 `{"ok": false, "error": "..."}` 并以非零退出码结束。进度和提示始终走 stderr,便于管道和自动解析。
76
+
77
+ ```bash
78
+ auto-tts voices --locale zh --json
79
+ # {"ok": true, "count": 14, "voices": [{"name": "zh-CN-XiaoxiaoNeural", ...}]}
80
+
81
+ auto-tts say "内容" -o out.mp3 --srt --json
82
+ # {"ok": true, "path": "/abs/out.mp3", "srt_path": "/abs/out.srt", "size_bytes": 27936, ...}
83
+
84
+ auto-tts web --no-open --json
85
+ # 服务就绪后输出一行:{"url": "http://127.0.0.1:8000", "host": "127.0.0.1", "port": 8000}
86
+ ```
87
+
55
88
  ## 功能
56
89
 
57
90
  - **音色**:322 个 edge-tts 音色,可按语言区域或名称筛选
@@ -60,6 +93,7 @@ auto-tts --version # 查看版本
60
93
  - **批量队列**:用空行分隔多段文本,每段成为一个独立任务
61
94
  - **任务面板**:实时进度、失败原因、试听、下载 mp3
62
95
  - **字幕导出**:任务完成后可下载与音频逐句对齐的 SRT 字幕
96
+ - **命令行**:`say` 直接合成 mp3,`voices`/`tones` 查询音色和语气,支持 `--json`,方便脚本和 Agent 调用
63
97
 
64
98
  ### 关于语气
65
99
 
@@ -71,12 +105,11 @@ edge-tts 本身**不支持**真正的情感风格(微软服务端会拒绝 `<m
71
105
 
72
106
  ```
73
107
  ~/.local/share/auto-tts/
74
- ├── venv/ # Python 虚拟环境
75
- ├── data/audio/ # 生成的 mp3
76
- └── requirements.sha256 # 依赖指纹,用于判断是否需要重装
108
+ ├── venv/ # Python 虚拟环境(依赖指纹 .requirements.sha256 存在此处)
109
+ └── data/audio/ # 生成的 mp3
77
110
  ```
78
111
 
79
- `requirements.txt` 改动后,下次启动会自动识别并重装依赖。
112
+ `requirements.txt` 改动后,下次启动会自动识别并重装依赖。设置环境变量 `AUTO_TTS_VENV_DIR` 可以把虚拟环境放到别处(例如复用源码目录下的 `.venv`)。
80
113
 
81
114
  ## 从源码运行
82
115
 
@@ -0,0 +1,383 @@
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.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import asyncio
13
+ import json
14
+ import shutil
15
+ import sys
16
+ import tempfile
17
+ import time
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from . import tts
22
+
23
+ # Matches the frontend's default voice so the CLI and the web UI sound alike.
24
+ DEFAULT_VOICE = "zh-CN-XiaoxiaoNeural"
25
+
26
+ # edge-tts streams 48 kbps CBR mono mp3: 6000 bytes per second.
27
+ _BYTES_PER_SECOND = 6 * 1000
28
+
29
+ # Set before parsing so usage errors can be emitted as JSON as well.
30
+ _JSON_ERRORS = False
31
+
32
+
33
+ class CLIError(Exception):
34
+ """A user-facing failure that is reported without a traceback."""
35
+
36
+
37
+ class _Parser(argparse.ArgumentParser):
38
+ """ArgumentParser that mirrors usage errors as JSON when --json is set."""
39
+
40
+ def error(self, message: str) -> None:
41
+ if _JSON_ERRORS:
42
+ _emit_json({"ok": False, "error": message})
43
+ super().error(message)
44
+
45
+
46
+ def _force_utf8() -> None:
47
+ """Use UTF-8 on stdio so text and voices survive any console codepage."""
48
+ try:
49
+ sys.stdin.reconfigure(encoding="utf-8", errors="replace")
50
+ sys.stdout.reconfigure(encoding="utf-8")
51
+ sys.stderr.reconfigure(encoding="utf-8")
52
+ except (AttributeError, OSError):
53
+ pass
54
+
55
+
56
+ def _emit_json(payload: dict[str, Any]) -> None:
57
+ json.dump(payload, sys.stdout, ensure_ascii=False)
58
+ sys.stdout.write("\n")
59
+ sys.stdout.flush()
60
+
61
+
62
+ def _bounded_int(low: int, high: int):
63
+ """An argparse type that accepts integers within [low, high] only."""
64
+
65
+ def parse(value: str) -> int:
66
+ try:
67
+ number = int(value)
68
+ except ValueError:
69
+ raise argparse.ArgumentTypeError(f"expected an integer, got {value!r}") from None
70
+ if not low <= number <= high:
71
+ raise argparse.ArgumentTypeError(f"must be between {low} and {high}")
72
+ return number
73
+
74
+ return parse
75
+
76
+
77
+ def _display_path(path: Path) -> str:
78
+ """Prefer a path relative to the working directory for human output."""
79
+ try:
80
+ return str(path.relative_to(Path.cwd()))
81
+ except ValueError:
82
+ return str(path)
83
+
84
+
85
+ def _human_size(size: int) -> str:
86
+ value = float(size)
87
+ for unit in ("B", "KB", "MB", "GB"):
88
+ if value < 1024 or unit == "GB":
89
+ return f"{int(value)} B" if unit == "B" else f"{value:.1f} {unit}"
90
+ value /= 1024
91
+ return f"{value:.1f} GB"
92
+
93
+
94
+ def _format_duration(seconds: float) -> str:
95
+ total = int(round(seconds))
96
+ hours, remainder = divmod(total, 3600)
97
+ minutes, secs = divmod(remainder, 60)
98
+ if hours:
99
+ return f"{hours}:{minutes:02d}:{secs:02d}"
100
+ if minutes:
101
+ return f"{minutes}:{secs:02d}"
102
+ return f"{seconds:.1f}s"
103
+
104
+
105
+ class _Progress:
106
+ """Render chunk progress on stderr; silent when stderr is not a TTY."""
107
+
108
+ def __init__(self, enabled: bool) -> None:
109
+ self._enabled = enabled
110
+ self._last = -1
111
+
112
+ async def __call__(self, value: float) -> None:
113
+ if not self._enabled:
114
+ return
115
+ percent = min(100, int(value * 100))
116
+ if percent == self._last:
117
+ return
118
+ self._last = percent
119
+ sys.stderr.write(f"\r {percent:3d}%")
120
+ sys.stderr.flush()
121
+
122
+ def done(self) -> None:
123
+ if self._enabled:
124
+ sys.stderr.write("\r \r")
125
+ sys.stderr.flush()
126
+
127
+
128
+ # ---------------------------------------------------------------------- say
129
+
130
+
131
+ def _read_text(args: argparse.Namespace) -> str:
132
+ """Resolve the input text from the argument, --file or standard input."""
133
+ if args.file and args.text is not None:
134
+ raise CLIError("give either TEXT or --file, not both")
135
+ if args.file:
136
+ try:
137
+ text = Path(args.file).read_text(encoding="utf-8")
138
+ except OSError as exc:
139
+ raise CLIError(f"cannot read {args.file}: {exc.strerror or exc}") from exc
140
+ elif args.text == "-":
141
+ text = sys.stdin.read()
142
+ elif args.text is not None:
143
+ text = args.text
144
+ elif not sys.stdin.isatty():
145
+ text = sys.stdin.read()
146
+ else:
147
+ raise CLIError("no text given (pass TEXT, '-', --file, or pipe stdin)")
148
+ if not text.strip():
149
+ raise CLIError("the text is empty")
150
+ return text
151
+
152
+
153
+ def _default_out_path() -> Path:
154
+ """A fresh `auto-tts-<timestamp>.mp3` path in the working directory."""
155
+ 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
162
+
163
+
164
+ def _resolve_srt(args: argparse.Namespace, out_path: Path | None) -> Path | None:
165
+ """Return the SRT destination; `--srt` alone means next to the audio."""
166
+ if args.srt is None:
167
+ return None
168
+ if args.srt:
169
+ return Path(args.srt)
170
+ if out_path is None:
171
+ raise CLIError("--srt needs a path when the audio goes to stdout")
172
+ return out_path.with_suffix(".srt")
173
+
174
+
175
+ def _cmd_say(args: argparse.Namespace) -> int:
176
+ text = _read_text(args)
177
+
178
+ preset = next(tone for tone in tts.TONE_PRESETS if tone["key"] == args.tone)
179
+ rate = preset["rate"] if args.rate is None else args.rate
180
+ volume = preset["volume"] if args.volume is None else args.volume
181
+ pitch = preset["pitch"] if args.pitch is None else args.pitch
182
+
183
+ to_stdout = args.out == "-"
184
+ if to_stdout and args.json:
185
+ raise CLIError("--json cannot be combined with -o -")
186
+ out_path = None if to_stdout else (Path(args.out) if args.out else _default_out_path())
187
+ srt_path = _resolve_srt(args, out_path)
188
+ if srt_path is not None:
189
+ srt_path.parent.mkdir(parents=True, exist_ok=True)
190
+ progress = _Progress(enabled=not args.quiet and sys.stderr.isatty())
191
+
192
+ async def synth(media_path: Path) -> int:
193
+ return await tts.synthesize(
194
+ text,
195
+ args.voice,
196
+ tts.format_rate(rate),
197
+ tts.format_volume(volume),
198
+ tts.format_pitch(pitch),
199
+ media_path,
200
+ srt_path=srt_path,
201
+ on_progress=progress,
202
+ )
203
+
204
+ if to_stdout:
205
+ with tempfile.TemporaryDirectory(prefix="auto-tts-") as tmp:
206
+ tmp_path = Path(tmp) / "say.mp3"
207
+ size = asyncio.run(synth(tmp_path))
208
+ progress.done()
209
+ with tmp_path.open("rb") as handle:
210
+ shutil.copyfileobj(handle, sys.stdout.buffer)
211
+ sys.stdout.buffer.flush()
212
+ if not args.quiet:
213
+ sys.stderr.write(f"auto-tts: wrote {size} bytes to stdout\n")
214
+ else:
215
+ size = asyncio.run(synth(out_path))
216
+ progress.done()
217
+
218
+ payload: dict[str, Any] = {
219
+ "ok": True,
220
+ "path": None if to_stdout else str(out_path),
221
+ "srt_path": (
222
+ str(srt_path) if srt_path is not None and srt_path.is_file() else None
223
+ ),
224
+ "size_bytes": size,
225
+ "duration_seconds": round(size / _BYTES_PER_SECOND, 1),
226
+ "voice": args.voice,
227
+ "tone": args.tone,
228
+ "rate": rate,
229
+ "volume": volume,
230
+ "pitch": pitch,
231
+ "chars": len(text),
232
+ }
233
+
234
+ if args.json:
235
+ _emit_json(payload)
236
+ elif not to_stdout:
237
+ sys.stdout.write(
238
+ f"{_display_path(out_path)} "
239
+ f"({_format_duration(payload['duration_seconds'])}, {_human_size(size)})\n"
240
+ )
241
+ if payload["srt_path"]:
242
+ sys.stdout.write(f"{_display_path(srt_path)}\n")
243
+ return 0
244
+
245
+
246
+ # ------------------------------------------------------------------- voices
247
+
248
+
249
+ def _cmd_voices(args: argparse.Namespace) -> int:
250
+ voices = asyncio.run(tts.list_voices())
251
+ items = []
252
+ for voice in voices:
253
+ item = {
254
+ "name": voice["ShortName"],
255
+ "locale": voice["Locale"],
256
+ "gender": voice["Gender"],
257
+ "friendly_name": voice.get("FriendlyName", voice["ShortName"]),
258
+ }
259
+ if args.locale and not item["locale"].lower().startswith(args.locale.lower()):
260
+ continue
261
+ if args.gender and item["gender"].lower() != args.gender:
262
+ continue
263
+ items.append(item)
264
+ items.sort(key=lambda item: (item["locale"], item["name"]))
265
+
266
+ if args.json:
267
+ _emit_json({"ok": True, "count": len(items), "voices": items})
268
+ return 0
269
+ if not items:
270
+ sys.stderr.write("auto-tts: no voices matched the filter\n")
271
+ return 0
272
+ width = max(len(item["name"]) for item in items)
273
+ for item in items:
274
+ sys.stdout.write(f"{item['name']:<{width}} {item['gender']:<6} {item['locale']}\n")
275
+ return 0
276
+
277
+
278
+ # -------------------------------------------------------------------- tones
279
+
280
+
281
+ def _cmd_tones(args: argparse.Namespace) -> int:
282
+ tones = tts.list_tones()
283
+ if args.json:
284
+ _emit_json({"ok": True, "count": len(tones), "tones": tones})
285
+ return 0
286
+ for tone in tones:
287
+ sys.stdout.write(
288
+ f"{tone['key']:<10} "
289
+ f"rate {tts.format_rate(tone['rate']):>5} "
290
+ f"volume {tts.format_volume(tone['volume']):>5} "
291
+ f"pitch {tts.format_pitch(tone['pitch']):>6}\n"
292
+ )
293
+ return 0
294
+
295
+
296
+ # ------------------------------------------------------------------ argparse
297
+
298
+
299
+ def _build_parser() -> _Parser:
300
+ parser = _Parser(
301
+ prog="auto-tts",
302
+ description="Local synthesis commands; the HTTP server is not required.",
303
+ )
304
+ subparsers = parser.add_subparsers(dest="command", required=True)
305
+
306
+ common = _Parser(add_help=False)
307
+ common.add_argument("--json", action="store_true", help="print one JSON object to stdout")
308
+ common.add_argument("-q", "--quiet", action="store_true", help="suppress progress output")
309
+
310
+ say = subparsers.add_parser(
311
+ "say",
312
+ parents=[common],
313
+ help="synthesise text to an mp3 file",
314
+ description="Synthesise text to an mp3 file without starting the server.",
315
+ epilog=(
316
+ "examples:\n"
317
+ " auto-tts say \"hello world\" -o hello.mp3\n"
318
+ ' auto-tts say "hello" -o hello.mp3 --srt # subtitles next to the audio\n'
319
+ " echo \"long article\" | auto-tts say - -o article.mp3\n"
320
+ " auto-tts say --file article.txt -v zh-CN-YunxiNeural -t newscast -o article.mp3\n"
321
+ " auto-tts say \"stream me\" -o - > out.mp3 # audio on stdout\n"
322
+ ),
323
+ formatter_class=argparse.RawDescriptionHelpFormatter,
324
+ )
325
+ say.add_argument("text", nargs="?", default=None, help="text to synthesise; '-' reads stdin")
326
+ 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)")
328
+ say.add_argument("-v", "--voice", default=DEFAULT_VOICE, metavar="NAME", help=f"edge-tts voice short name (default: {DEFAULT_VOICE})")
329
+ 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
+ say.add_argument("--rate", type=_bounded_int(-100, 200), default=None, help="speaking rate delta in percent; overrides the tone")
331
+ say.add_argument("--volume", type=_bounded_int(-100, 100), default=None, help="volume delta in percent; overrides the tone")
332
+ 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")
334
+
335
+ voices = subparsers.add_parser(
336
+ "voices",
337
+ parents=[common],
338
+ help="list the available voices",
339
+ description="List the edge-tts voice catalogue without starting the server.",
340
+ )
341
+ voices.add_argument("--locale", default=None, metavar="PREFIX", help="only voices whose locale starts with PREFIX (e.g. zh, zh-CN)")
342
+ voices.add_argument("--gender", type=str.lower, choices=["male", "female"], default=None, metavar="GENDER", help="only voices of this gender")
343
+
344
+ subparsers.add_parser(
345
+ "tones",
346
+ parents=[common],
347
+ help="list the speaking-tone presets",
348
+ description="List the speaking-tone presets (rate/volume/pitch triples).",
349
+ )
350
+ return parser
351
+
352
+
353
+ def _run(handler, args: argparse.Namespace) -> int:
354
+ try:
355
+ return handler(args)
356
+ except CLIError as exc:
357
+ message = str(exc)
358
+ except KeyboardInterrupt:
359
+ sys.stderr.write("\nauto-tts: interrupted\n")
360
+ return 130
361
+ except Exception as exc: # noqa: BLE001 - the message is surfaced to the user
362
+ message = str(exc) or exc.__class__.__name__
363
+ if args.json:
364
+ _emit_json({"ok": False, "error": message})
365
+ sys.stderr.write(f"auto-tts: {message}\n")
366
+ return 1
367
+
368
+
369
+ def main(argv: list[str] | None = None) -> int:
370
+ global _JSON_ERRORS
371
+ _force_utf8()
372
+ argv = list(sys.argv[1:] if argv is None else argv)
373
+ _JSON_ERRORS = "--json" in argv
374
+ parser = _build_parser()
375
+ args = parser.parse_args(argv)
376
+ _JSON_ERRORS = args.json
377
+
378
+ handlers = {"say": _cmd_say, "voices": _cmd_voices, "tones": _cmd_tones}
379
+ return _run(handlers[args.command], args)
380
+
381
+
382
+ if __name__ == "__main__":
383
+ raise SystemExit(main())
@@ -10,17 +10,27 @@ PROJECT_DIR = BASE_DIR.parent
10
10
  DATA_DIR = Path(os.getenv("AUTO_TTS_DATA_DIR", BASE_DIR / "data"))
11
11
  AUDIO_DIR = DATA_DIR / "audio"
12
12
 
13
+ # Job metadata is written here so the queue survives a restart. The audio files
14
+ # themselves live in AUDIO_DIR and are left in place.
15
+ JOBS_FILE = DATA_DIR / "jobs.json"
16
+
13
17
  # Built frontend served by the backend in single-port mode. When the directory
14
18
  # is missing the API still runs and the Vite dev server proxies to it instead.
15
19
  FRONTEND_DIST = Path(os.getenv("AUTO_TTS_FRONTEND_DIST", PROJECT_DIR / "frontend" / "dist"))
16
20
 
17
- # Number of synthesis jobs that may run in parallel.
18
- MAX_CONCURRENCY = int(os.getenv("AUTO_TTS_MAX_CONCURRENCY", "2"))
21
+ # Number of synthesis jobs that may run in parallel. edge-tts synthesis is
22
+ # network bound, so several jobs can stream from the service at once.
23
+ MAX_CONCURRENCY = int(os.getenv("AUTO_TTS_MAX_CONCURRENCY", "4"))
19
24
 
20
25
  # Long texts are split into chunks of at most this many characters before
21
26
  # being sent to edge-tts, then concatenated back into a single audio file.
22
27
  CHUNK_SIZE = int(os.getenv("AUTO_TTS_CHUNK_SIZE", "800"))
23
28
 
29
+ # Chunks of one text are independent streams, so they are synthesised in
30
+ # parallel and concatenated in order. This caps how many run at once per job,
31
+ # which keeps a single long text from monopolising the connection pool.
32
+ CHUNK_CONCURRENCY = int(os.getenv("AUTO_TTS_CHUNK_CONCURRENCY", "4"))
33
+
24
34
  CORS_ORIGINS = [
25
35
  origin.strip()
26
36
  for origin in os.getenv(