auto-tts 0.5.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 CHANGED
@@ -12,7 +12,7 @@
12
12
 
13
13
  | 依赖 | 版本 | 说明 |
14
14
  | --- | --- | --- |
15
- | Node.js | 18 或更高 | 运行 `auto-tts` 命令 |
15
+ | Node.js | 20.19 或更高 | 运行 `auto-tts` 命令 |
16
16
  | Python | 3.9 或更高 | 后端运行时 |
17
17
 
18
18
  然后全局安装:
@@ -101,6 +101,11 @@ auto-tts web --no-open --json
101
101
  - **语气**:自然、温柔、愉悦、兴奋、严肃、悲伤、新闻播报、低语,另有自定义
102
102
  - **长文本**:自动分块合成,长度不限
103
103
  - **批量队列**:用空行分隔多段文本,每段成为一个独立任务
104
+ - **智能分字幕**:按标点、段落和字幕长度自动断句,长句会优先在逗号或空格处拆分
105
+ - **DOCX 拖拽导入**:把 Word `.docx` 文章直接拖入输入框,自动提取段落文本并进入字幕模式
106
+ - **字幕时间线**:像剪辑软件一样拖动字幕片段、精确输入开始时间并调整段前间隔,导出带静音间隔的 MP3 和同步 SRT
107
+ - **性能模式**:可一键关闭占用最高的 Three.js 特效,关闭后 3D 资源不会加载、页面切换为紧凑布局
108
+ - **高频交互优化**:字幕分段在 Web Worker 中执行,音色选择与任务队列使用虚拟列表,时间线只渲染可视片段
104
109
  - **任务面板**:实时进度、失败原因、试听、下载 mp3
105
110
  - **字幕导出**:任务完成后可下载与音频逐句对齐的 SRT 字幕
106
111
  - **命令行**:`say` 直接合成 mp3,`--batch` 按空行分段批量生成 mp3 和 SRT,`voices`/`tones` 查询音色和语气,支持 `--json`,方便脚本和 Agent 调用
@@ -145,6 +150,7 @@ cd auto-tts
145
150
  | GET | `/api/voices` | 全部可用音色 |
146
151
  | GET | `/api/tones` | 语气预设及其对应的语速/音调/音量 |
147
152
  | POST | `/api/jobs` | 创建任务,`text` 单条或 `texts` 批量 |
153
+ | POST | `/api/timeline/export` | 按绝对开始时间合成时间线 MP3 与 SRT |
148
154
  | GET | `/api/jobs` | 任务列表 |
149
155
  | GET | `/api/jobs/{id}` | 单个任务 |
150
156
  | DELETE | `/api/jobs/{id}` | 删除任务 |
@@ -154,7 +160,8 @@ cd auto-tts
154
160
  ## 技术栈
155
161
 
156
162
  - 后端:FastAPI + edge-tts,任务队列为进程内异步队列
157
- - 前端:React + TypeScript + Vite
163
+ - 前端:React 19 + React Compiler + TypeScript + Vite 7 + Less
164
+ - 交互:CSS-only motion、Web Worker 字幕分段、虚拟列表、时间线可视区渲染
158
165
 
159
166
  ## 许可
160
167
 
@@ -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 merged artifacts from a previous run; they are cheap to rebuild."""
292
- for path in config.AUDIO_DIR.glob("merged-*"):
293
- path.unlink(missing_ok=True)
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
 
@@ -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)
@@ -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