auto-tts 0.4.0 → 0.5.1
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 +20 -3
- package/backend/app/cli.py +161 -15
- package/backend/app/jobs.py +100 -3
- package/backend/app/main.py +14 -1
- package/backend/app/schemas.py +13 -0
- package/bin/auto-tts.mjs +3 -1
- package/frontend/dist/assets/SoundSculpture-CRv0x1Wa.js +4231 -0
- package/frontend/dist/assets/index-BJWxXx2j.js +76 -0
- package/frontend/dist/assets/index-DgSTrTj2.js +44 -0
- package/frontend/dist/assets/index-Hzk28f07.css +1 -0
- package/frontend/dist/assets/react-vendor-C6kboJog.js +1 -0
- package/frontend/dist/assets/subtitle.worker-Do3AtmDO.js +4 -0
- package/frontend/dist/favicon.svg +4 -4
- package/frontend/dist/index.html +6 -9
- package/package.json +2 -2
- package/frontend/dist/assets/index-CuF7PWso.js +0 -80
- package/frontend/dist/assets/index-aBeehwg0.css +0 -1
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
|
|
13
13
|
| 依赖 | 版本 | 说明 |
|
|
14
14
|
| --- | --- | --- |
|
|
15
|
-
| Node.js |
|
|
15
|
+
| Node.js | 20.19 或更高 | 运行 `auto-tts` 命令 |
|
|
16
16
|
| Python | 3.9 或更高 | 后端运行时 |
|
|
17
17
|
|
|
18
18
|
然后全局安装:
|
|
@@ -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,19 +85,30 @@ 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 音色,可按语言区域或名称筛选
|
|
91
101
|
- **语气**:自然、温柔、愉悦、兴奋、严肃、悲伤、新闻播报、低语,另有自定义
|
|
92
102
|
- **长文本**:自动分块合成,长度不限
|
|
93
103
|
- **批量队列**:用空行分隔多段文本,每段成为一个独立任务
|
|
104
|
+
- **智能分字幕**:按标点、段落和字幕长度自动断句,长句会优先在逗号或空格处拆分
|
|
105
|
+
- **DOCX 拖拽导入**:把 Word `.docx` 文章直接拖入输入框,自动提取段落文本并进入字幕模式
|
|
106
|
+
- **字幕时间线**:像剪辑软件一样拖动字幕片段、精确输入开始时间并调整段前间隔,导出带静音间隔的 MP3 和同步 SRT
|
|
107
|
+
- **性能模式**:可一键关闭占用最高的 Three.js 特效,关闭后 3D 资源不会加载、页面切换为紧凑布局
|
|
108
|
+
- **高频交互优化**:字幕分段在 Web Worker 中执行,音色选择与任务队列使用虚拟列表,时间线只渲染可视片段
|
|
94
109
|
- **任务面板**:实时进度、失败原因、试听、下载 mp3
|
|
95
110
|
- **字幕导出**:任务完成后可下载与音频逐句对齐的 SRT 字幕
|
|
96
|
-
- **命令行**:`say` 直接合成 mp3,`voices`/`tones` 查询音色和语气,支持 `--json`,方便脚本和 Agent 调用
|
|
111
|
+
- **命令行**:`say` 直接合成 mp3,`--batch` 按空行分段批量生成 mp3 和 SRT,`voices`/`tones` 查询音色和语气,支持 `--json`,方便脚本和 Agent 调用
|
|
97
112
|
|
|
98
113
|
### 关于语气
|
|
99
114
|
|
|
@@ -135,6 +150,7 @@ cd auto-tts
|
|
|
135
150
|
| GET | `/api/voices` | 全部可用音色 |
|
|
136
151
|
| GET | `/api/tones` | 语气预设及其对应的语速/音调/音量 |
|
|
137
152
|
| POST | `/api/jobs` | 创建任务,`text` 单条或 `texts` 批量 |
|
|
153
|
+
| POST | `/api/timeline/export` | 按绝对开始时间合成时间线 MP3 与 SRT |
|
|
138
154
|
| GET | `/api/jobs` | 任务列表 |
|
|
139
155
|
| GET | `/api/jobs/{id}` | 单个任务 |
|
|
140
156
|
| DELETE | `/api/jobs/{id}` | 删除任务 |
|
|
@@ -144,7 +160,8 @@ cd auto-tts
|
|
|
144
160
|
## 技术栈
|
|
145
161
|
|
|
146
162
|
- 后端:FastAPI + edge-tts,任务队列为进程内异步队列
|
|
147
|
-
- 前端:React + TypeScript + Vite
|
|
163
|
+
- 前端:React 19 + React Compiler + TypeScript + Vite 7 + Less
|
|
164
|
+
- 交互:CSS-only motion、Web Worker 字幕分段、虚拟列表、时间线可视区渲染
|
|
148
165
|
|
|
149
166
|
## 许可
|
|
150
167
|
|
package/backend/app/cli.py
CHANGED
|
@@ -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
|
|
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
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
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
|
|
176
|
-
|
|
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("
|
|
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/backend/app/jobs.py
CHANGED
|
@@ -17,6 +17,12 @@ from . import config, tts
|
|
|
17
17
|
# six bytes. The same constant is used when merging subtitles onto the audio.
|
|
18
18
|
_BYTES_PER_MS = 6
|
|
19
19
|
|
|
20
|
+
# A valid, silent MPEG-2 Layer III frame for 24 kHz mono at 48 kbps. Every
|
|
21
|
+
# 144-byte frame is exactly 24 ms, so gaps can be inserted into a CBR timeline
|
|
22
|
+
# without re-encoding or requiring ffmpeg.
|
|
23
|
+
_SILENT_MP3_FRAME = bytes.fromhex("fff364c4") + bytes(140)
|
|
24
|
+
_FRAME_MS = 24
|
|
25
|
+
|
|
20
26
|
# Timestamps inside an SRT cue line: "HH:MM:SS,mmm".
|
|
21
27
|
_SRT_TIMESTAMP = re.compile(r"(\d{2}):(\d{2}):(\d{2}),(\d{3})")
|
|
22
28
|
|
|
@@ -103,6 +109,11 @@ class Job:
|
|
|
103
109
|
"created_at": self.created_at,
|
|
104
110
|
"finished_at": self.finished_at,
|
|
105
111
|
"size_bytes": self.size_bytes,
|
|
112
|
+
"duration_ms": (
|
|
113
|
+
round(self.size_bytes / _BYTES_PER_MS)
|
|
114
|
+
if self.status == "completed"
|
|
115
|
+
else 0
|
|
116
|
+
),
|
|
106
117
|
"chars": len(self.text),
|
|
107
118
|
"audio_url": f"/api/audio/{self.filename}" if self.status == "completed" else None,
|
|
108
119
|
"srt_url": (
|
|
@@ -235,6 +246,91 @@ class JobManager:
|
|
|
235
246
|
"srt_url": f"/api/subtitles/{srt_name}" if has_subtitles else None,
|
|
236
247
|
}
|
|
237
248
|
|
|
249
|
+
async def export_timeline(self, placements: list[dict[str, int | str]]) -> dict[str, Any]:
|
|
250
|
+
"""Render clips at their absolute timeline positions.
|
|
251
|
+
|
|
252
|
+
Each placement is ``{"id": job_id, "start_ms": absolute_start_ms}``. The
|
|
253
|
+
audio before each clip is filled with silent MP3 frames. SRT cues from
|
|
254
|
+
every source clip are shifted onto the same absolute timeline, so the
|
|
255
|
+
exported audio and subtitles stay in sync. Timeline positions are
|
|
256
|
+
snapped to 24 ms MP3-frame boundaries.
|
|
257
|
+
"""
|
|
258
|
+
if not placements:
|
|
259
|
+
raise ValueError("Add at least one clip to the timeline")
|
|
260
|
+
|
|
261
|
+
async with self._lock:
|
|
262
|
+
jobs = {job_id: self._jobs.get(job_id) for job_id in (str(p["id"]) for p in placements)}
|
|
263
|
+
|
|
264
|
+
ordered: list[tuple[Job, int]] = []
|
|
265
|
+
seen: set[str] = set()
|
|
266
|
+
for placement in sorted(placements, key=lambda item: int(item["start_ms"])):
|
|
267
|
+
job_id = str(placement["id"])
|
|
268
|
+
if job_id in seen:
|
|
269
|
+
raise ValueError("The same clip cannot appear twice on the timeline")
|
|
270
|
+
seen.add(job_id)
|
|
271
|
+
job = jobs.get(job_id)
|
|
272
|
+
if job is None:
|
|
273
|
+
raise ValueError(f"Timeline clip {job_id} was not found")
|
|
274
|
+
if job.status != "completed" or not (config.AUDIO_DIR / job.filename).is_file():
|
|
275
|
+
raise ValueError(f"Timeline clip {job_id} is not ready yet")
|
|
276
|
+
ordered.append((job, max(0, int(placement["start_ms"]))))
|
|
277
|
+
|
|
278
|
+
export_id = f"timeline-{uuid.uuid4().hex[:12]}"
|
|
279
|
+
audio_name = f"{export_id}.mp3"
|
|
280
|
+
srt_name = f"{export_id}.srt"
|
|
281
|
+
audio_path = config.AUDIO_DIR / audio_name
|
|
282
|
+
srt_path = config.AUDIO_DIR / srt_name
|
|
283
|
+
|
|
284
|
+
cues: list[tuple[int, int, str]] = []
|
|
285
|
+
total_bytes = 0
|
|
286
|
+
with audio_path.open("wb") as handle:
|
|
287
|
+
for job, requested_start_ms in ordered:
|
|
288
|
+
current_ms = total_bytes // _BYTES_PER_MS
|
|
289
|
+
gap_ms = max(0, requested_start_ms - current_ms)
|
|
290
|
+
frame_count = round(gap_ms / _FRAME_MS)
|
|
291
|
+
silence = _SILENT_MP3_FRAME * frame_count
|
|
292
|
+
handle.write(silence)
|
|
293
|
+
total_bytes += len(silence)
|
|
294
|
+
|
|
295
|
+
actual_start_ms = total_bytes // _BYTES_PER_MS
|
|
296
|
+
data = (config.AUDIO_DIR / job.filename).read_bytes()
|
|
297
|
+
source = config.AUDIO_DIR / job.srt_filename
|
|
298
|
+
source_cues = (
|
|
299
|
+
_parse_srt(source.read_text(encoding="utf-8"))
|
|
300
|
+
if source.is_file()
|
|
301
|
+
else []
|
|
302
|
+
)
|
|
303
|
+
if source_cues:
|
|
304
|
+
cues.extend(
|
|
305
|
+
(start + actual_start_ms, end + actual_start_ms, text)
|
|
306
|
+
for start, end, text in source_cues
|
|
307
|
+
)
|
|
308
|
+
else:
|
|
309
|
+
clip_duration_ms = round(len(data) / _BYTES_PER_MS)
|
|
310
|
+
cues.append(
|
|
311
|
+
(
|
|
312
|
+
actual_start_ms,
|
|
313
|
+
actual_start_ms + clip_duration_ms,
|
|
314
|
+
job.text,
|
|
315
|
+
)
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
handle.write(data)
|
|
319
|
+
total_bytes += len(data)
|
|
320
|
+
|
|
321
|
+
has_subtitles = bool(cues)
|
|
322
|
+
if has_subtitles:
|
|
323
|
+
srt_path.write_text(_render_srt(cues), encoding="utf-8")
|
|
324
|
+
|
|
325
|
+
return {
|
|
326
|
+
"id": export_id,
|
|
327
|
+
"count": len(ordered),
|
|
328
|
+
"size_bytes": total_bytes,
|
|
329
|
+
"duration": round(total_bytes / (_BYTES_PER_MS * 1000), 1),
|
|
330
|
+
"audio_url": f"/api/audio/{audio_name}",
|
|
331
|
+
"srt_url": f"/api/subtitles/{srt_name}" if has_subtitles else None,
|
|
332
|
+
}
|
|
333
|
+
|
|
238
334
|
def _remove_files(self, job: Job) -> None:
|
|
239
335
|
(config.AUDIO_DIR / job.filename).unlink(missing_ok=True)
|
|
240
336
|
(config.AUDIO_DIR / job.srt_filename).unlink(missing_ok=True)
|
|
@@ -288,9 +384,10 @@ class JobManager:
|
|
|
288
384
|
tmp_path.replace(path)
|
|
289
385
|
|
|
290
386
|
def _purge_merged_files(self) -> None:
|
|
291
|
-
"""Drop
|
|
292
|
-
for
|
|
293
|
-
path.
|
|
387
|
+
"""Drop derived exports from a previous run; they are cheap to rebuild."""
|
|
388
|
+
for pattern in ("merged-*", "timeline-*"):
|
|
389
|
+
for path in config.AUDIO_DIR.glob(pattern):
|
|
390
|
+
path.unlink(missing_ok=True)
|
|
294
391
|
|
|
295
392
|
# -------------------------------------------------------------------- workers
|
|
296
393
|
|
package/backend/app/main.py
CHANGED
|
@@ -9,10 +9,11 @@ from fastapi import FastAPI, HTTPException
|
|
|
9
9
|
from fastapi.middleware.cors import CORSMiddleware
|
|
10
10
|
from fastapi.responses import FileResponse
|
|
11
11
|
from fastapi.staticfiles import StaticFiles
|
|
12
|
+
from starlette.middleware.gzip import GZipMiddleware
|
|
12
13
|
|
|
13
14
|
from . import config, tts
|
|
14
15
|
from .jobs import JobManager
|
|
15
|
-
from .schemas import JobView, MergeRequest, SynthesisRequest
|
|
16
|
+
from .schemas import JobView, MergeRequest, SynthesisRequest, TimelineExportRequest
|
|
16
17
|
|
|
17
18
|
manager = JobManager(config.MAX_CONCURRENCY)
|
|
18
19
|
|
|
@@ -26,6 +27,7 @@ async def lifespan(_: FastAPI):
|
|
|
26
27
|
|
|
27
28
|
|
|
28
29
|
app = FastAPI(title="auto-tts", version="0.1.0", lifespan=lifespan)
|
|
30
|
+
app.add_middleware(GZipMiddleware, minimum_size=1024)
|
|
29
31
|
app.add_middleware(
|
|
30
32
|
CORSMiddleware,
|
|
31
33
|
allow_origins=config.CORS_ORIGINS,
|
|
@@ -103,6 +105,17 @@ async def merge_jobs(payload: MergeRequest) -> dict:
|
|
|
103
105
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
104
106
|
|
|
105
107
|
|
|
108
|
+
@app.post("/api/timeline/export")
|
|
109
|
+
async def export_timeline(payload: TimelineExportRequest) -> dict:
|
|
110
|
+
"""Render completed jobs at absolute timeline positions with silence gaps."""
|
|
111
|
+
try:
|
|
112
|
+
return await manager.export_timeline(
|
|
113
|
+
[{"id": clip.id, "start_ms": clip.start_ms} for clip in payload.clips]
|
|
114
|
+
)
|
|
115
|
+
except ValueError as exc:
|
|
116
|
+
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
117
|
+
|
|
118
|
+
|
|
106
119
|
@app.get("/api/jobs/{job_id}", response_model=JobView)
|
|
107
120
|
async def get_job(job_id: str) -> dict:
|
|
108
121
|
job = await manager.get(job_id)
|
package/backend/app/schemas.py
CHANGED
|
@@ -25,6 +25,18 @@ class MergeRequest(BaseModel):
|
|
|
25
25
|
|
|
26
26
|
ids: list[str] = Field(default_factory=list, description="Job ids to merge.")
|
|
27
27
|
|
|
28
|
+
class TimelinePlacement(BaseModel):
|
|
29
|
+
"""One completed job placed at an absolute position on the timeline."""
|
|
30
|
+
|
|
31
|
+
id: str = Field(..., description="Completed job id.")
|
|
32
|
+
start_ms: int = Field(default=0, ge=0, le=86_400_000, description="Start time in milliseconds.")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class TimelineExportRequest(BaseModel):
|
|
36
|
+
"""Ordered clips and their absolute start times on the timeline."""
|
|
37
|
+
|
|
38
|
+
clips: list[TimelinePlacement] = Field(default_factory=list, description="Timeline clips.")
|
|
39
|
+
|
|
28
40
|
|
|
29
41
|
class JobView(BaseModel):
|
|
30
42
|
"""Serialised view of a synthesis job."""
|
|
@@ -42,6 +54,7 @@ class JobView(BaseModel):
|
|
|
42
54
|
created_at: float
|
|
43
55
|
finished_at: float | None = None
|
|
44
56
|
size_bytes: int
|
|
57
|
+
duration_ms: int = 0
|
|
45
58
|
chars: int
|
|
46
59
|
audio_url: str | None = None
|
|
47
60
|
srt_url: str | None = None
|
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
|
|
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
|
}
|