auto-tts 0.2.0 → 0.2.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
@@ -59,6 +59,7 @@ auto-tts --version # 查看版本
59
59
  - **长文本**:自动分块合成,长度不限
60
60
  - **批量队列**:用空行分隔多段文本,每段成为一个独立任务
61
61
  - **任务面板**:实时进度、失败原因、试听、下载 mp3
62
+ - **字幕导出**:任务完成后可下载与音频逐句对齐的 SRT 字幕
62
63
 
63
64
  ### 关于语气
64
65
 
@@ -105,6 +106,7 @@ cd auto-tts
105
106
  | GET | `/api/jobs/{id}` | 单个任务 |
106
107
  | DELETE | `/api/jobs/{id}` | 删除任务 |
107
108
  | GET | `/api/audio/{filename}` | 获取音频文件 |
109
+ | GET | `/api/subtitles/{filename}` | 获取 SRT 字幕文件 |
108
110
 
109
111
  ## 技术栈
110
112
 
@@ -27,11 +27,16 @@ class Job:
27
27
  created_at: float = field(default_factory=time.time)
28
28
  finished_at: float | None = None
29
29
  size_bytes: int = 0
30
+ has_subtitles: bool = False
30
31
 
31
32
  @property
32
33
  def filename(self) -> str:
33
34
  return f"{self.id}.mp3"
34
35
 
36
+ @property
37
+ def srt_filename(self) -> str:
38
+ return f"{self.id}.srt"
39
+
35
40
  def to_dict(self) -> dict:
36
41
  return {
37
42
  "id": self.id,
@@ -49,6 +54,11 @@ class Job:
49
54
  "size_bytes": self.size_bytes,
50
55
  "chars": len(self.text),
51
56
  "audio_url": f"/api/audio/{self.filename}" if self.status == "completed" else None,
57
+ "srt_url": (
58
+ f"/api/subtitles/{self.srt_filename}"
59
+ if self.status == "completed" and self.has_subtitles
60
+ else None
61
+ ),
52
62
  }
53
63
 
54
64
 
@@ -101,6 +111,7 @@ class JobManager:
101
111
  if job is None:
102
112
  return False
103
113
  (config.AUDIO_DIR / job.filename).unlink(missing_ok=True)
114
+ (config.AUDIO_DIR / job.srt_filename).unlink(missing_ok=True)
104
115
  return True
105
116
 
106
117
  async def _worker(self) -> None:
@@ -120,6 +131,7 @@ class JobManager:
120
131
  async def on_progress(value: float) -> None:
121
132
  job.progress = value
122
133
 
134
+ srt_path = config.AUDIO_DIR / job.srt_filename
123
135
  try:
124
136
  size = await tts.synthesize(
125
137
  job.text,
@@ -128,9 +140,11 @@ class JobManager:
128
140
  tts.format_volume(job.volume),
129
141
  tts.format_pitch(job.pitch),
130
142
  config.AUDIO_DIR / job.filename,
131
- on_progress,
143
+ srt_path=srt_path,
144
+ on_progress=on_progress,
132
145
  )
133
146
  job.size_bytes = size
147
+ job.has_subtitles = srt_path.is_file()
134
148
  job.progress = 1.0
135
149
  job.status = "completed"
136
150
  except asyncio.CancelledError:
@@ -116,6 +116,16 @@ async def get_audio(filename: str) -> FileResponse:
116
116
  return FileResponse(path, media_type="audio/mpeg")
117
117
 
118
118
 
119
+ @app.get("/api/subtitles/{filename}")
120
+ async def get_subtitles(filename: str) -> FileResponse:
121
+ if Path(filename).name != filename:
122
+ raise HTTPException(status_code=404, detail="Subtitles not found")
123
+ path = config.AUDIO_DIR / filename
124
+ if not path.is_file():
125
+ raise HTTPException(status_code=404, detail="Subtitles not found")
126
+ return FileResponse(path, media_type="application/x-subrip")
127
+
128
+
119
129
  # Serve the built frontend from the same origin so a single command can run the
120
130
  # whole app on one port. Mounted last, so every /api route above takes priority.
121
131
  if config.FRONTEND_DIST.is_dir():
@@ -37,4 +37,5 @@ class JobView(BaseModel):
37
37
  finished_at: float | None = None
38
38
  size_bytes: int
39
39
  chars: int
40
- audio_url: str | None = None
40
+ audio_url: str | None = None
41
+ srt_url: str | None = None
@@ -13,6 +13,12 @@ from . import config
13
13
 
14
14
  ProgressCallback = Callable[[float], Awaitable[None]]
15
15
 
16
+ # edge-tts streams 48 kbps CBR mono mp3 and reports boundaries in 100-nanosecond
17
+ # ticks. Each Communicate counts from zero, so the bytes already written are used
18
+ # to shift later chunks onto a single timeline.
19
+ _TICKS_PER_SECOND = 10_000_000
20
+ _MP3_BITRATE_BPS = 48_000
21
+
16
22
  _voices_cache: list[dict] | None = None
17
23
  _voices_lock = asyncio.Lock()
18
24
 
@@ -99,6 +105,20 @@ def split_text(text: str, limit: int) -> list[str]:
99
105
  return chunks
100
106
 
101
107
 
108
+ def _audio_ticks(audio_bytes: int) -> int:
109
+ """Convert a count of 48 kbps mp3 bytes into edge-tts timing ticks."""
110
+ return audio_bytes * 8 * _TICKS_PER_SECOND // _MP3_BITRATE_BPS
111
+
112
+
113
+ def _write_subtitles(submaker: edge_tts.SubMaker, srt_path: Path) -> bool:
114
+ """Write an SRT file, returning False when no boundaries were reported."""
115
+ srt = submaker.get_srt()
116
+ if not srt.strip():
117
+ return False
118
+ srt_path.write_text(srt, encoding="utf-8")
119
+ return True
120
+
121
+
102
122
  async def synthesize(
103
123
  text: str,
104
124
  voice: str,
@@ -106,28 +126,48 @@ async def synthesize(
106
126
  volume: str,
107
127
  pitch: str,
108
128
  out_path: Path,
129
+ srt_path: Path | None = None,
109
130
  on_progress: ProgressCallback | None = None,
110
131
  ) -> int:
111
- """Synthesise *text* into an mp3 file and return the number of audio bytes written."""
132
+ """Synthesise *text* into an mp3 file and return the number of audio bytes written.
133
+
134
+ When *srt_path* is provided, sentence-level subtitles derived from the
135
+ service's boundary events are written alongside the audio.
136
+ """
112
137
  chunks = split_text(text, config.CHUNK_SIZE)
113
138
  if not chunks:
114
139
  raise ValueError("Text must not be empty")
115
140
 
116
141
  out_path.parent.mkdir(parents=True, exist_ok=True)
117
142
  tmp_path = out_path.with_name(f"{out_path.name}.part")
143
+ submaker = edge_tts.SubMaker()
118
144
  total = len(chunks)
119
145
  written = 0
120
146
  try:
121
147
  with tmp_path.open("wb") as handle:
122
148
  for index, chunk in enumerate(chunks):
123
- communicate = edge_tts.Communicate(chunk, voice, rate=rate, volume=volume, pitch=pitch)
149
+ # Boundary offsets from a fresh Communicate are relative to its own
150
+ # audio, so shift them by the duration of everything written so far.
151
+ base = _audio_ticks(written)
152
+ communicate = edge_tts.Communicate(
153
+ chunk,
154
+ voice,
155
+ rate=rate,
156
+ volume=volume,
157
+ pitch=pitch,
158
+ boundary="SentenceBoundary",
159
+ )
124
160
  async for message in communicate.stream():
125
161
  if message["type"] == "audio":
126
162
  handle.write(message["data"])
127
163
  written += len(message["data"])
164
+ elif message["type"] in ("WordBoundary", "SentenceBoundary"):
165
+ submaker.feed({**message, "offset": message["offset"] + base})
128
166
  if on_progress is not None:
129
167
  await on_progress((index + 1) / total)
130
168
  tmp_path.replace(out_path)
169
+ if srt_path is not None:
170
+ _write_subtitles(submaker, srt_path)
131
171
  except BaseException:
132
172
  tmp_path.unlink(missing_ok=True)
133
173
  raise