auto-tts 0.2.0 → 0.3.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
@@ -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
 
@@ -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(
@@ -1,14 +1,25 @@
1
- """In-memory job queue that drives edge-tts synthesis."""
1
+ """Job queue that drives edge-tts synthesis and survives process restarts."""
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
5
  import asyncio
6
+ import json
7
+ import re
6
8
  import time
7
9
  import uuid
8
10
  from dataclasses import dataclass, field
11
+ from typing import Any
9
12
 
10
13
  from . import config, tts
11
14
 
15
+ # edge-tts streams 48 kbps CBR mono mp3, so a merged timeline can be derived
16
+ # from byte offsets: one second of audio is 6000 bytes, i.e. one millisecond is
17
+ # six bytes. The same constant is used when merging subtitles onto the audio.
18
+ _BYTES_PER_MS = 6
19
+
20
+ # Timestamps inside an SRT cue line: "HH:MM:SS,mmm".
21
+ _SRT_TIMESTAMP = re.compile(r"(\d{2}):(\d{2}):(\d{2}),(\d{3})")
22
+
12
23
 
13
24
  @dataclass
14
25
  class Job:
@@ -27,12 +38,57 @@ class Job:
27
38
  created_at: float = field(default_factory=time.time)
28
39
  finished_at: float | None = None
29
40
  size_bytes: int = 0
41
+ has_subtitles: bool = False
30
42
 
31
43
  @property
32
44
  def filename(self) -> str:
33
45
  return f"{self.id}.mp3"
34
46
 
35
- def to_dict(self) -> dict:
47
+ @property
48
+ def srt_filename(self) -> str:
49
+ return f"{self.id}.srt"
50
+
51
+ def to_record(self) -> dict[str, Any]:
52
+ """Return the fields persisted to disk (no derived URLs)."""
53
+ return {
54
+ "id": self.id,
55
+ "text": self.text,
56
+ "voice": self.voice,
57
+ "tone": self.tone,
58
+ "rate": self.rate,
59
+ "volume": self.volume,
60
+ "pitch": self.pitch,
61
+ "status": self.status,
62
+ "progress": self.progress,
63
+ "error": self.error,
64
+ "created_at": self.created_at,
65
+ "finished_at": self.finished_at,
66
+ "size_bytes": self.size_bytes,
67
+ "has_subtitles": self.has_subtitles,
68
+ }
69
+
70
+ @classmethod
71
+ def from_record(cls, data: dict[str, Any]) -> "Job":
72
+ """Rebuild a job from a persisted record, tolerating missing fields."""
73
+ finished_at = data.get("finished_at")
74
+ return cls(
75
+ id=str(data.get("id", uuid.uuid4().hex)),
76
+ text=str(data.get("text", "")),
77
+ voice=str(data.get("voice", "")),
78
+ tone=str(data.get("tone", tts.DEFAULT_TONE)),
79
+ rate=int(data.get("rate", 0)),
80
+ volume=int(data.get("volume", 0)),
81
+ pitch=int(data.get("pitch", 0)),
82
+ status=str(data.get("status", "failed")),
83
+ progress=float(data.get("progress", 0.0)),
84
+ error=data.get("error"),
85
+ created_at=float(data.get("created_at", time.time())),
86
+ finished_at=float(finished_at) if finished_at is not None else None,
87
+ size_bytes=int(data.get("size_bytes", 0)),
88
+ has_subtitles=bool(data.get("has_subtitles", False)),
89
+ )
90
+
91
+ def to_dict(self) -> dict[str, Any]:
36
92
  return {
37
93
  "id": self.id,
38
94
  "text": self.text,
@@ -49,6 +105,11 @@ class Job:
49
105
  "size_bytes": self.size_bytes,
50
106
  "chars": len(self.text),
51
107
  "audio_url": f"/api/audio/{self.filename}" if self.status == "completed" else None,
108
+ "srt_url": (
109
+ f"/api/subtitles/{self.srt_filename}"
110
+ if self.status == "completed" and self.has_subtitles
111
+ else None
112
+ ),
52
113
  }
53
114
 
54
115
 
@@ -63,6 +124,9 @@ class JobManager:
63
124
  self._lock = asyncio.Lock()
64
125
 
65
126
  async def start(self) -> None:
127
+ # Restore the previous queue before any worker can pick up new work.
128
+ self._load()
129
+ self._purge_merged_files()
66
130
  self._workers = [asyncio.create_task(self._worker()) for _ in range(self._concurrency)]
67
131
 
68
132
  async def stop(self) -> None:
@@ -71,6 +135,7 @@ class JobManager:
71
135
  if self._workers:
72
136
  await asyncio.gather(*self._workers, return_exceptions=True)
73
137
  self._workers = []
138
+ self._persist()
74
139
 
75
140
  async def submit(self, text: str, voice: str, tone: str, rate: int, volume: int, pitch: int) -> Job:
76
141
  job = Job(
@@ -84,6 +149,7 @@ class JobManager:
84
149
  )
85
150
  async with self._lock:
86
151
  self._jobs[job.id] = job
152
+ self._persist()
87
153
  await self._queue.put(job.id)
88
154
  return job
89
155
 
@@ -100,9 +166,134 @@ class JobManager:
100
166
  job = self._jobs.pop(job_id, None)
101
167
  if job is None:
102
168
  return False
103
- (config.AUDIO_DIR / job.filename).unlink(missing_ok=True)
169
+ self._remove_files(job)
170
+ self._persist()
104
171
  return True
105
172
 
173
+ async def clear(self) -> int:
174
+ """Delete every job and its audio, returning how many were removed."""
175
+ async with self._lock:
176
+ jobs = list(self._jobs.values())
177
+ self._jobs.clear()
178
+ for job in jobs:
179
+ self._remove_files(job)
180
+ # Merged artifacts are derived from the jobs that just went away.
181
+ self._purge_merged_files()
182
+ self._persist()
183
+ return len(jobs)
184
+
185
+ async def merge(self, job_ids: list[str]) -> dict[str, Any]:
186
+ """Concatenate the selected completed jobs into one mp3 plus one srt.
187
+
188
+ Audio is merged by appending the raw mp3 streams (edge-tts emits 48 kbps
189
+ CBR, so this keeps a single continuous timeline). Subtitle cues from each
190
+ job are shifted by the duration of the audio that precedes them.
191
+ """
192
+ async with self._lock:
193
+ selected = [self._jobs[job_id] for job_id in job_ids if job_id in self._jobs]
194
+
195
+ selected = [
196
+ job
197
+ for job in selected
198
+ if job.status == "completed" and (config.AUDIO_DIR / job.filename).is_file()
199
+ ]
200
+ if not selected:
201
+ raise ValueError("Select at least one completed job")
202
+
203
+ merged_id = f"merged-{uuid.uuid4().hex[:12]}"
204
+ audio_name = f"{merged_id}.mp3"
205
+ srt_name = f"{merged_id}.srt"
206
+ audio_path = config.AUDIO_DIR / audio_name
207
+ srt_path = config.AUDIO_DIR / srt_name
208
+
209
+ cues: list[tuple[int, int, str]] = []
210
+ total_bytes = 0
211
+ with audio_path.open("wb") as handle:
212
+ for job in selected:
213
+ data = (config.AUDIO_DIR / job.filename).read_bytes()
214
+ handle.write(data)
215
+ # Offset the cues by the audio written so far, then grow it.
216
+ offset_ms = total_bytes // _BYTES_PER_MS
217
+ source = config.AUDIO_DIR / job.srt_filename
218
+ if source.is_file():
219
+ cues.extend(
220
+ (start + offset_ms, end + offset_ms, text)
221
+ for start, end, text in _parse_srt(source.read_text(encoding="utf-8"))
222
+ )
223
+ total_bytes += len(data)
224
+
225
+ has_subtitles = bool(cues)
226
+ if has_subtitles:
227
+ srt_path.write_text(_render_srt(cues), encoding="utf-8")
228
+
229
+ return {
230
+ "id": merged_id,
231
+ "count": len(selected),
232
+ "size_bytes": total_bytes,
233
+ "duration": round(total_bytes / (_BYTES_PER_MS * 1000), 1),
234
+ "audio_url": f"/api/audio/{audio_name}",
235
+ "srt_url": f"/api/subtitles/{srt_name}" if has_subtitles else None,
236
+ }
237
+
238
+ def _remove_files(self, job: Job) -> None:
239
+ (config.AUDIO_DIR / job.filename).unlink(missing_ok=True)
240
+ (config.AUDIO_DIR / job.srt_filename).unlink(missing_ok=True)
241
+
242
+ # --------------------------------------------------------------- persistence
243
+
244
+ def _load(self) -> None:
245
+ """Restore jobs written by a previous run, repairing unusable entries."""
246
+ path = config.JOBS_FILE
247
+ if not path.is_file():
248
+ return
249
+ try:
250
+ payload = json.loads(path.read_text(encoding="utf-8"))
251
+ except (OSError, ValueError):
252
+ return
253
+ if not isinstance(payload, list):
254
+ return
255
+
256
+ changed = False
257
+ for record in payload:
258
+ if not isinstance(record, dict):
259
+ continue
260
+ job = Job.from_record(record)
261
+ # The queue itself is not persisted, so anything still pending or
262
+ # running when the process stopped can never finish.
263
+ if job.status in ("pending", "processing"):
264
+ job.status = "failed"
265
+ job.error = "Interrupted by restart"
266
+ job.finished_at = job.finished_at or time.time()
267
+ changed = True
268
+ elif job.status == "completed" and not (config.AUDIO_DIR / job.filename).is_file():
269
+ job.status = "failed"
270
+ job.error = "Audio file is missing"
271
+ job.size_bytes = 0
272
+ job.has_subtitles = False
273
+ job.finished_at = job.finished_at or time.time()
274
+ changed = True
275
+ self._jobs[job.id] = job
276
+
277
+ if changed:
278
+ self._persist()
279
+
280
+ def _persist(self) -> None:
281
+ """Write the current queue to disk. Synchronous on purpose: no await
282
+ point means no other coroutine can mutate the queue mid-write."""
283
+ records = [job.to_record() for job in self._jobs.values()]
284
+ path = config.JOBS_FILE
285
+ path.parent.mkdir(parents=True, exist_ok=True)
286
+ tmp_path = path.with_name(f"{path.name}.part")
287
+ tmp_path.write_text(json.dumps(records, ensure_ascii=False, indent=2), encoding="utf-8")
288
+ tmp_path.replace(path)
289
+
290
+ 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)
294
+
295
+ # -------------------------------------------------------------------- workers
296
+
106
297
  async def _worker(self) -> None:
107
298
  while True:
108
299
  job_id = await self._queue.get()
@@ -120,6 +311,7 @@ class JobManager:
120
311
  async def on_progress(value: float) -> None:
121
312
  job.progress = value
122
313
 
314
+ srt_path = config.AUDIO_DIR / job.srt_filename
123
315
  try:
124
316
  size = await tts.synthesize(
125
317
  job.text,
@@ -128,9 +320,11 @@ class JobManager:
128
320
  tts.format_volume(job.volume),
129
321
  tts.format_pitch(job.pitch),
130
322
  config.AUDIO_DIR / job.filename,
131
- on_progress,
323
+ srt_path=srt_path,
324
+ on_progress=on_progress,
132
325
  )
133
326
  job.size_bytes = size
327
+ job.has_subtitles = srt_path.is_file()
134
328
  job.progress = 1.0
135
329
  job.status = "completed"
136
330
  except asyncio.CancelledError:
@@ -141,4 +335,49 @@ class JobManager:
141
335
  job.status = "failed"
142
336
  job.error = str(exc) or exc.__class__.__name__
143
337
  finally:
144
- job.finished_at = time.time()
338
+ job.finished_at = time.time()
339
+ self._persist()
340
+
341
+
342
+ # --------------------------------------------------------------------- subtitles
343
+
344
+
345
+ def _parse_srt(text: str) -> list[tuple[int, int, str]]:
346
+ """Parse SRT text into (start_ms, end_ms, payload) cues."""
347
+ cues: list[tuple[int, int, str]] = []
348
+ for block in re.split(r"\r?\n\s*\r?\n", text.strip()):
349
+ lines = [line for line in block.splitlines() if line.strip()]
350
+ timing_index = next((index for index, line in enumerate(lines) if "-->" in line), None)
351
+ if timing_index is None:
352
+ continue
353
+ stamps = _SRT_TIMESTAMP.findall(lines[timing_index])
354
+ if len(stamps) < 2:
355
+ continue
356
+ payload = "\n".join(lines[timing_index + 1 :]).strip()
357
+ if not payload:
358
+ continue
359
+ cues.append((_to_ms(stamps[0]), _to_ms(stamps[1]), payload))
360
+ return cues
361
+
362
+
363
+ def _render_srt(cues: list[tuple[int, int, str]]) -> str:
364
+ """Render cues back to SRT, renumbering from one."""
365
+ blocks = [
366
+ f"{index}\n{_format_ms(start)} --> {_format_ms(end)}\n{text}\n"
367
+ for index, (start, end, text) in enumerate(cues, start=1)
368
+ ]
369
+ return "\n".join(blocks)
370
+
371
+
372
+ def _to_ms(parts: tuple[str, str, str, str]) -> int:
373
+ hours, minutes, seconds, millis = (int(part) for part in parts)
374
+ return ((hours * 60 + minutes) * 60 + seconds) * 1000 + millis
375
+
376
+
377
+ def _format_ms(value: int) -> str:
378
+ millis = value % 1000
379
+ total_seconds = value // 1000
380
+ seconds = total_seconds % 60
381
+ minutes = (total_seconds // 60) % 60
382
+ hours = total_seconds // 3600
383
+ return f"{hours:02d}:{minutes:02d}:{seconds:02d},{millis:03d}"
@@ -12,7 +12,7 @@ from fastapi.staticfiles import StaticFiles
12
12
 
13
13
  from . import config, tts
14
14
  from .jobs import JobManager
15
- from .schemas import JobView, SynthesisRequest
15
+ from .schemas import JobView, MergeRequest, SynthesisRequest
16
16
 
17
17
  manager = JobManager(config.MAX_CONCURRENCY)
18
18
 
@@ -88,6 +88,21 @@ async def list_jobs() -> list[dict]:
88
88
  return [job.to_dict() for job in await manager.list()]
89
89
 
90
90
 
91
+ @app.delete("/api/jobs")
92
+ async def clear_jobs() -> dict:
93
+ """Delete every job together with its audio and subtitle files."""
94
+ return {"deleted": await manager.clear()}
95
+
96
+
97
+ @app.post("/api/jobs/merge")
98
+ async def merge_jobs(payload: MergeRequest) -> dict:
99
+ """Concatenate the selected jobs into one mp3 and one merged srt."""
100
+ try:
101
+ return await manager.merge(payload.ids)
102
+ except ValueError as exc:
103
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
104
+
105
+
91
106
  @app.get("/api/jobs/{job_id}", response_model=JobView)
92
107
  async def get_job(job_id: str) -> dict:
93
108
  job = await manager.get(job_id)
@@ -116,6 +131,16 @@ async def get_audio(filename: str) -> FileResponse:
116
131
  return FileResponse(path, media_type="audio/mpeg")
117
132
 
118
133
 
134
+ @app.get("/api/subtitles/{filename}")
135
+ async def get_subtitles(filename: str) -> FileResponse:
136
+ if Path(filename).name != filename:
137
+ raise HTTPException(status_code=404, detail="Subtitles not found")
138
+ path = config.AUDIO_DIR / filename
139
+ if not path.is_file():
140
+ raise HTTPException(status_code=404, detail="Subtitles not found")
141
+ return FileResponse(path, media_type="application/x-subrip")
142
+
143
+
119
144
  # Serve the built frontend from the same origin so a single command can run the
120
145
  # whole app on one port. Mounted last, so every /api route above takes priority.
121
146
  if config.FRONTEND_DIST.is_dir():
@@ -20,6 +20,12 @@ class SynthesisRequest(BaseModel):
20
20
  pitch: int = Field(default=0, ge=-100, le=100, description="Pitch delta, Hz.")
21
21
 
22
22
 
23
+ class MergeRequest(BaseModel):
24
+ """Identifiers of completed jobs to concatenate, in the requested order."""
25
+
26
+ ids: list[str] = Field(default_factory=list, description="Job ids to merge.")
27
+
28
+
23
29
  class JobView(BaseModel):
24
30
  """Serialised view of a synthesis job."""
25
31
 
@@ -37,4 +43,5 @@ class JobView(BaseModel):
37
43
  finished_at: float | None = None
38
44
  size_bytes: int
39
45
  chars: int
40
- audio_url: str | None = None
46
+ audio_url: str | None = None
47
+ srt_url: str | None = None
@@ -6,6 +6,7 @@ import asyncio
6
6
  import re
7
7
  from collections.abc import Awaitable, Callable
8
8
  from pathlib import Path
9
+ from typing import Any
9
10
 
10
11
  import edge_tts
11
12
 
@@ -13,6 +14,12 @@ from . import config
13
14
 
14
15
  ProgressCallback = Callable[[float], Awaitable[None]]
15
16
 
17
+ # edge-tts streams 48 kbps CBR mono mp3 and reports boundaries in 100-nanosecond
18
+ # ticks. Each Communicate counts from zero, so the bytes already written are used
19
+ # to shift later chunks onto a single timeline.
20
+ _TICKS_PER_SECOND = 10_000_000
21
+ _MP3_BITRATE_BPS = 48_000
22
+
16
23
  _voices_cache: list[dict] | None = None
17
24
  _voices_lock = asyncio.Lock()
18
25
 
@@ -99,6 +106,20 @@ def split_text(text: str, limit: int) -> list[str]:
99
106
  return chunks
100
107
 
101
108
 
109
+ def _audio_ticks(audio_bytes: int) -> int:
110
+ """Convert a count of 48 kbps mp3 bytes into edge-tts timing ticks."""
111
+ return audio_bytes * 8 * _TICKS_PER_SECOND // _MP3_BITRATE_BPS
112
+
113
+
114
+ def _write_subtitles(submaker: edge_tts.SubMaker, srt_path: Path) -> bool:
115
+ """Write an SRT file, returning False when no boundaries were reported."""
116
+ srt = submaker.get_srt()
117
+ if not srt.strip():
118
+ return False
119
+ srt_path.write_text(srt, encoding="utf-8")
120
+ return True
121
+
122
+
102
123
  async def synthesize(
103
124
  text: str,
104
125
  voice: str,
@@ -106,28 +127,78 @@ async def synthesize(
106
127
  volume: str,
107
128
  pitch: str,
108
129
  out_path: Path,
130
+ srt_path: Path | None = None,
109
131
  on_progress: ProgressCallback | None = None,
110
132
  ) -> int:
111
- """Synthesise *text* into an mp3 file and return the number of audio bytes written."""
133
+ """Synthesise *text* into an mp3 file and return the number of audio bytes written.
134
+
135
+ The text is split into chunks, which are independent edge-tts streams. They
136
+ are synthesised in parallel (bounded by ``CHUNK_CONCURRENCY``) and then
137
+ concatenated in order, which cuts the wall time of long texts roughly by the
138
+ degree of parallelism. When *srt_path* is provided, sentence-level subtitles
139
+ derived from the service's boundary events are written alongside the audio.
140
+ """
112
141
  chunks = split_text(text, config.CHUNK_SIZE)
113
142
  if not chunks:
114
143
  raise ValueError("Text must not be empty")
115
144
 
116
145
  out_path.parent.mkdir(parents=True, exist_ok=True)
117
146
  tmp_path = out_path.with_name(f"{out_path.name}.part")
147
+
148
+ limit = asyncio.Semaphore(max(1, config.CHUNK_CONCURRENCY))
118
149
  total = len(chunks)
150
+ finished = 0
151
+
152
+ async def render(chunk: str) -> tuple[bytes, list[dict[str, Any]]]:
153
+ """Synthesise one chunk, returning its audio bytes and boundary events."""
154
+ nonlocal finished
155
+ buffer = bytearray()
156
+ events: list[dict[str, Any]] = []
157
+ async with limit:
158
+ communicate = edge_tts.Communicate(
159
+ chunk,
160
+ voice,
161
+ rate=rate,
162
+ volume=volume,
163
+ pitch=pitch,
164
+ boundary="SentenceBoundary",
165
+ )
166
+ async for message in communicate.stream():
167
+ if message["type"] == "audio":
168
+ buffer.extend(message["data"])
169
+ elif message["type"] in ("WordBoundary", "SentenceBoundary"):
170
+ events.append(message)
171
+ finished += 1
172
+ if on_progress is not None:
173
+ await on_progress(finished / total)
174
+ return bytes(buffer), events
175
+
176
+ tasks = [asyncio.create_task(render(chunk)) for chunk in chunks]
177
+ try:
178
+ rendered = await asyncio.gather(*tasks)
179
+ except BaseException:
180
+ # A failed chunk must not leave its siblings streaming in the background.
181
+ for task in tasks:
182
+ task.cancel()
183
+ await asyncio.gather(*tasks, return_exceptions=True)
184
+ tmp_path.unlink(missing_ok=True)
185
+ raise
186
+
187
+ submaker = edge_tts.SubMaker()
119
188
  written = 0
120
189
  try:
121
190
  with tmp_path.open("wb") as handle:
122
- for index, chunk in enumerate(chunks):
123
- communicate = edge_tts.Communicate(chunk, voice, rate=rate, volume=volume, pitch=pitch)
124
- async for message in communicate.stream():
125
- if message["type"] == "audio":
126
- handle.write(message["data"])
127
- written += len(message["data"])
128
- if on_progress is not None:
129
- await on_progress((index + 1) / total)
191
+ for buffer, events in rendered:
192
+ # Boundary offsets from a fresh Communicate are relative to its
193
+ # own audio, so shift them by the duration of everything before.
194
+ base = _audio_ticks(written)
195
+ for event in events:
196
+ submaker.feed({**event, "offset": event["offset"] + base})
197
+ handle.write(buffer)
198
+ written += len(buffer)
130
199
  tmp_path.replace(out_path)
200
+ if srt_path is not None:
201
+ _write_subtitles(submaker, srt_path)
131
202
  except BaseException:
132
203
  tmp_path.unlink(missing_ok=True)
133
204
  raise