auto-tts 0.2.1 → 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/backend/app/config.py +12 -2
- package/backend/app/jobs.py +229 -4
- package/backend/app/main.py +16 -1
- package/backend/app/schemas.py +6 -0
- package/backend/app/tts.py +53 -22
- package/frontend/dist/assets/index-Cc-LIddj.js +80 -0
- package/frontend/dist/assets/{index-CHs4jSOA.css → index-uchW1pqg.css} +1 -1
- package/frontend/dist/index.html +2 -2
- package/package.json +1 -1
- package/frontend/dist/assets/index-C1twiIjC.js +0 -80
package/backend/app/config.py
CHANGED
|
@@ -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
|
-
|
|
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(
|
package/backend/app/jobs.py
CHANGED
|
@@ -1,14 +1,25 @@
|
|
|
1
|
-
"""
|
|
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:
|
|
@@ -37,7 +48,47 @@ class Job:
|
|
|
37
48
|
def srt_filename(self) -> str:
|
|
38
49
|
return f"{self.id}.srt"
|
|
39
50
|
|
|
40
|
-
def
|
|
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]:
|
|
41
92
|
return {
|
|
42
93
|
"id": self.id,
|
|
43
94
|
"text": self.text,
|
|
@@ -73,6 +124,9 @@ class JobManager:
|
|
|
73
124
|
self._lock = asyncio.Lock()
|
|
74
125
|
|
|
75
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()
|
|
76
130
|
self._workers = [asyncio.create_task(self._worker()) for _ in range(self._concurrency)]
|
|
77
131
|
|
|
78
132
|
async def stop(self) -> None:
|
|
@@ -81,6 +135,7 @@ class JobManager:
|
|
|
81
135
|
if self._workers:
|
|
82
136
|
await asyncio.gather(*self._workers, return_exceptions=True)
|
|
83
137
|
self._workers = []
|
|
138
|
+
self._persist()
|
|
84
139
|
|
|
85
140
|
async def submit(self, text: str, voice: str, tone: str, rate: int, volume: int, pitch: int) -> Job:
|
|
86
141
|
job = Job(
|
|
@@ -94,6 +149,7 @@ class JobManager:
|
|
|
94
149
|
)
|
|
95
150
|
async with self._lock:
|
|
96
151
|
self._jobs[job.id] = job
|
|
152
|
+
self._persist()
|
|
97
153
|
await self._queue.put(job.id)
|
|
98
154
|
return job
|
|
99
155
|
|
|
@@ -110,9 +166,133 @@ class JobManager:
|
|
|
110
166
|
job = self._jobs.pop(job_id, None)
|
|
111
167
|
if job is None:
|
|
112
168
|
return False
|
|
169
|
+
self._remove_files(job)
|
|
170
|
+
self._persist()
|
|
171
|
+
return True
|
|
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:
|
|
113
239
|
(config.AUDIO_DIR / job.filename).unlink(missing_ok=True)
|
|
114
240
|
(config.AUDIO_DIR / job.srt_filename).unlink(missing_ok=True)
|
|
115
|
-
|
|
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
|
|
116
296
|
|
|
117
297
|
async def _worker(self) -> None:
|
|
118
298
|
while True:
|
|
@@ -155,4 +335,49 @@ class JobManager:
|
|
|
155
335
|
job.status = "failed"
|
|
156
336
|
job.error = str(exc) or exc.__class__.__name__
|
|
157
337
|
finally:
|
|
158
|
-
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}"
|
package/backend/app/main.py
CHANGED
|
@@ -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)
|
package/backend/app/schemas.py
CHANGED
|
@@ -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
|
|
package/backend/app/tts.py
CHANGED
|
@@ -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
|
|
|
@@ -131,8 +132,11 @@ async def synthesize(
|
|
|
131
132
|
) -> int:
|
|
132
133
|
"""Synthesise *text* into an mp3 file and return the number of audio bytes written.
|
|
133
134
|
|
|
134
|
-
|
|
135
|
-
|
|
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.
|
|
136
140
|
"""
|
|
137
141
|
chunks = split_text(text, config.CHUNK_SIZE)
|
|
138
142
|
if not chunks:
|
|
@@ -140,31 +144,58 @@ async def synthesize(
|
|
|
140
144
|
|
|
141
145
|
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
142
146
|
tmp_path = out_path.with_name(f"{out_path.name}.part")
|
|
143
|
-
|
|
147
|
+
|
|
148
|
+
limit = asyncio.Semaphore(max(1, config.CHUNK_CONCURRENCY))
|
|
144
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()
|
|
145
188
|
written = 0
|
|
146
189
|
try:
|
|
147
190
|
with tmp_path.open("wb") as handle:
|
|
148
|
-
for
|
|
149
|
-
# Boundary offsets from a fresh Communicate are relative to its
|
|
150
|
-
# audio, so shift them by the duration of everything
|
|
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.
|
|
151
194
|
base = _audio_ticks(written)
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
volume=volume,
|
|
157
|
-
pitch=pitch,
|
|
158
|
-
boundary="SentenceBoundary",
|
|
159
|
-
)
|
|
160
|
-
async for message in communicate.stream():
|
|
161
|
-
if message["type"] == "audio":
|
|
162
|
-
handle.write(message["data"])
|
|
163
|
-
written += len(message["data"])
|
|
164
|
-
elif message["type"] in ("WordBoundary", "SentenceBoundary"):
|
|
165
|
-
submaker.feed({**message, "offset": message["offset"] + base})
|
|
166
|
-
if on_progress is not None:
|
|
167
|
-
await on_progress((index + 1) / total)
|
|
195
|
+
for event in events:
|
|
196
|
+
submaker.feed({**event, "offset": event["offset"] + base})
|
|
197
|
+
handle.write(buffer)
|
|
198
|
+
written += len(buffer)
|
|
168
199
|
tmp_path.replace(out_path)
|
|
169
200
|
if srt_path is not None:
|
|
170
201
|
_write_subtitles(submaker, srt_path)
|