voxprep 0.1.0.dev0__py3-none-any.whl

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.

Potentially problematic release.


This version of voxprep might be problematic. Click here for more details.

voxprep/__init__.py ADDED
@@ -0,0 +1,42 @@
1
+ """voxprep: turn any audio/video into model-ready input for any AI, then stitch results back.
2
+
3
+ import voxprep as vp
4
+
5
+ vp.inspect("meeting.mp4") # what is it, which models take it
6
+ result = vp.prepare("meeting.mp4", target="openai") # compress, split at pauses if needed
7
+ texts = [my_model(c.to_bytes()) for c in result.chunks]
8
+ vp.stitch(result, texts).refine().to_srt("meeting.srt")
9
+
10
+ vp.transcribe("meeting.mp4", via="groq") # all of the above in one call
11
+ vp.extract_reference("podcast.mp4", "cosyvoice")[0].save("ref.wav")
12
+ """
13
+
14
+ from . import presets, vad
15
+ from .chunker import Chunk, PreparedResult, prepare
16
+ from .diagnose import Report, inspect
17
+ from .io import Audio, load, probe
18
+ from .reference import Candidate, extract_reference
19
+ from .stitch import stitch, transcribe
20
+ from .transcript import Segment, Transcript
21
+
22
+ __version__ = "0.1.0.dev0"
23
+
24
+ __all__ = [
25
+ "Audio",
26
+ "Candidate",
27
+ "Chunk",
28
+ "PreparedResult",
29
+ "Report",
30
+ "Segment",
31
+ "Transcript",
32
+ "__version__",
33
+ "extract_reference",
34
+ "inspect",
35
+ "load",
36
+ "prepare",
37
+ "presets",
38
+ "probe",
39
+ "stitch",
40
+ "transcribe",
41
+ "vad",
42
+ ]
@@ -0,0 +1,43 @@
1
+ """Built-in backends that call a speech model for each chunk.
2
+
3
+ A backend is any object with:
4
+
5
+ * ``name``: str
6
+ * ``preset``: name of the preset its chunks must follow
7
+ * ``transcribe(chunk, prompt=None)``: returns something :func:`voxprep.stitch` can read
8
+ (an API response, a dict, a :class:`~voxprep.transcript.Transcript`, SRT or plain text).
9
+
10
+ Model SDKs are optional extras, imported only when a backend is created.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from typing import Protocol
16
+
17
+ from ..chunker import Chunk
18
+
19
+
20
+ class Backend(Protocol):
21
+ name: str
22
+ preset: str
23
+
24
+ def transcribe(self, chunk: Chunk, prompt: str | None = None): ...
25
+
26
+
27
+ def get_backend(name: str, **options) -> Backend:
28
+ if name == "openai":
29
+ from .openai import OpenAIBackend
30
+
31
+ return OpenAIBackend(**options)
32
+ if name == "groq":
33
+ from .openai import GroqBackend
34
+
35
+ return GroqBackend(**options)
36
+ if name in ("funasr", "sensevoice"):
37
+ from .funasr import FunASRBackend
38
+
39
+ return FunASRBackend(**options)
40
+ raise KeyError(f"unknown backend {name!r}; choose openai, groq or funasr")
41
+
42
+
43
+ NAMES = ["openai", "groq", "funasr"]
@@ -0,0 +1,53 @@
1
+ """Local SenseVoice / FunASR models (free, offline, strong on Chinese).
2
+
3
+ Needs ``pip install "voxprep[funasr]"``, which brings PyTorch; the core package does not.
4
+ voxprep cuts the audio into <=28 s pieces at pauses, so the model's own VAD is not needed.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+
11
+ from ..chunker import Chunk
12
+
13
+ _TAGS = re.compile(r"<\|[^|]*\|>")
14
+
15
+
16
+ class FunASRBackend:
17
+ name = "funasr"
18
+ preset = "sensevoice"
19
+
20
+ def __init__(
21
+ self,
22
+ model: str = "iic/SenseVoiceSmall",
23
+ device: str = "cpu",
24
+ language: str = "auto",
25
+ model_obj=None,
26
+ **model_kwargs,
27
+ ):
28
+ self.language = language
29
+ if model_obj is None:
30
+ try:
31
+ from funasr import AutoModel
32
+ except ImportError as e: # pragma: no cover - depends on extras
33
+ raise ImportError(
34
+ 'the funasr backend needs FunASR: pip install "voxprep[funasr]"'
35
+ ) from e
36
+ model_obj = AutoModel(model=model, device=device, disable_update=True, **model_kwargs)
37
+ self.model = model_obj
38
+
39
+ def transcribe(self, chunk: Chunk, prompt: str | None = None) -> dict:
40
+ source = chunk.audio.resample(16000).samples if chunk.audio is not None else str(chunk.path)
41
+ results = self.model.generate(input=source, cache={}, language=self.language, use_itn=True)
42
+ text = "".join(clean(r.get("text", "")) for r in results)
43
+ return {"text": text}
44
+
45
+
46
+ def clean(text: str) -> str:
47
+ """Drop SenseVoice's language / emotion / event tags such as ``<|zh|><|NEUTRAL|>``."""
48
+ try:
49
+ from funasr.utils.postprocess_utils import rich_transcription_postprocess
50
+
51
+ return rich_transcription_postprocess(text)
52
+ except ImportError:
53
+ return _TAGS.sub("", text).strip()
@@ -0,0 +1,84 @@
1
+ """OpenAI transcription API, and Groq through its OpenAI-compatible endpoint.
2
+
3
+ Needs ``pip install "voxprep[openai]"`` (Groq uses the same package).
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+
10
+ from ..chunker import Chunk
11
+
12
+ PROMPT_CHARS = 200 # previous text passed as context; Whisper reads ~224 prompt tokens
13
+
14
+
15
+ class OpenAIBackend:
16
+ name = "openai"
17
+ preset = "openai"
18
+ default_model = "gpt-transcribe"
19
+ api_key_env = "OPENAI_API_KEY"
20
+ base_url: str | None = None
21
+
22
+ def __init__(
23
+ self,
24
+ model: str | None = None,
25
+ language: str | None = None,
26
+ context: bool = True,
27
+ client=None,
28
+ api_key: str | None = None,
29
+ base_url: str | None = None,
30
+ ):
31
+ self.model = model or self.default_model
32
+ self.language = language
33
+ self.context = context
34
+ self._verbose = True # ask for segment timestamps until the model says no
35
+ if client is None:
36
+ try:
37
+ from openai import OpenAI
38
+ except ImportError as e: # pragma: no cover - depends on extras
39
+ raise ImportError(
40
+ f"the {self.name} backend needs the openai package: "
41
+ 'pip install "voxprep[openai]"'
42
+ ) from e
43
+ client = OpenAI(
44
+ api_key=api_key or os.environ.get(self.api_key_env),
45
+ base_url=base_url or self.base_url,
46
+ )
47
+ self.client = client
48
+
49
+ def transcribe(self, chunk: Chunk, prompt: str | None = None):
50
+ kwargs = {
51
+ "model": self.model,
52
+ "file": (chunk.filename, chunk.to_bytes(), chunk.mime_type),
53
+ }
54
+ if self.language:
55
+ kwargs["language"] = self.language
56
+ if prompt and self.context:
57
+ kwargs["prompt"] = prompt[-PROMPT_CHARS:]
58
+ create = self.client.audio.transcriptions.create
59
+ if self._verbose:
60
+ try:
61
+ return create(
62
+ **kwargs, response_format="verbose_json", timestamp_granularities=["segment"]
63
+ )
64
+ except Exception as e:
65
+ if not _format_unsupported(e):
66
+ raise
67
+ # e.g. gpt-4o-*-transcribe only return json; times then come from VAD
68
+ self._verbose = False
69
+ return create(**kwargs, response_format="json")
70
+
71
+
72
+ class GroqBackend(OpenAIBackend):
73
+ name = "groq"
74
+ preset = "groq"
75
+ default_model = "whisper-large-v3-turbo"
76
+ api_key_env = "GROQ_API_KEY"
77
+ base_url = "https://api.groq.com/openai/v1"
78
+
79
+
80
+ def _format_unsupported(e: Exception) -> bool:
81
+ msg = str(e).lower()
82
+ return type(e).__name__ == "BadRequestError" and (
83
+ "response_format" in msg or "timestamp" in msg or "verbose_json" in msg
84
+ )
voxprep/chunker.py ADDED
@@ -0,0 +1,421 @@
1
+ """Prepare audio for a model: re-encode first, split at pauses only when it won't fit.
2
+
3
+ Every chunk remembers where each of its pieces came from in the original file, so
4
+ results can be mapped back exactly, even after silence was stripped out.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import math
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+
16
+ from . import io, presets, vad
17
+ from .io import Audio, SourceInfo
18
+ from .vad import Span
19
+
20
+ MANIFEST = "manifest.json"
21
+ SAFETY = 0.97 # plan chunks a little under the limit; actual sizes are checked after encoding
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Piece:
26
+ """``duration`` seconds starting at ``local_start`` in the chunk come from ``source_start``."""
27
+
28
+ local_start: float
29
+ source_start: float
30
+ duration: float
31
+
32
+
33
+ @dataclass
34
+ class Chunk:
35
+ index: int
36
+ pieces: list[Piece]
37
+ speech: list[Span] # speech spans in chunk-local seconds
38
+ fmt: str
39
+ bitrate: int | None = None
40
+ audio: Audio | None = field(default=None, repr=False)
41
+ path: Path | None = None
42
+ _data: bytes | None = field(default=None, repr=False)
43
+
44
+ @property
45
+ def start(self) -> float:
46
+ return self.pieces[0].source_start
47
+
48
+ @property
49
+ def end(self) -> float:
50
+ last = self.pieces[-1]
51
+ return last.source_start + last.duration
52
+
53
+ @property
54
+ def duration(self) -> float:
55
+ last = self.pieces[-1]
56
+ return last.local_start + last.duration
57
+
58
+ @property
59
+ def filename(self) -> str:
60
+ return f"chunk_{self.index:03d}{io.FORMATS[self.fmt][2]}"
61
+
62
+ @property
63
+ def mime_type(self) -> str:
64
+ return {"wav": "audio/wav", "flac": "audio/flac", "mp3": "audio/mpeg", "opus": "audio/ogg"}[
65
+ self.fmt
66
+ ]
67
+
68
+ def to_bytes(self) -> bytes:
69
+ if self._data is None:
70
+ if self.audio is None:
71
+ if self.path is None:
72
+ raise ValueError("chunk has no audio")
73
+ self._data = Path(self.path).read_bytes()
74
+ else:
75
+ self._data = io.encode(self.audio, self.fmt, self.bitrate)
76
+ return self._data
77
+
78
+ @property
79
+ def size_bytes(self) -> int:
80
+ return len(self.to_bytes())
81
+
82
+ def save(self, path: str | Path) -> Path:
83
+ path = Path(path)
84
+ path.write_bytes(self.to_bytes())
85
+ return path
86
+
87
+ def to_source_time(self, t: float) -> float:
88
+ """Map a time inside this chunk to the original file's timeline."""
89
+ t = max(0.0, t)
90
+ for p in self.pieces:
91
+ if t <= p.local_start + p.duration:
92
+ return p.source_start + max(0.0, t - p.local_start)
93
+ last = self.pieces[-1]
94
+ return last.source_start + last.duration
95
+
96
+ def to_dict(self) -> dict:
97
+ return {
98
+ "index": self.index,
99
+ "file": self.filename,
100
+ "start": round(self.start, 3),
101
+ "end": round(self.end, 3),
102
+ "duration": round(self.duration, 3),
103
+ "size_bytes": self.size_bytes,
104
+ "fmt": self.fmt,
105
+ "pieces": [[p.local_start, p.source_start, p.duration] for p in self.pieces],
106
+ "speech": [[s.start, s.end] for s in self.speech],
107
+ }
108
+
109
+
110
+ @dataclass
111
+ class PreparedResult:
112
+ preset: presets.TranscribePreset
113
+ chunks: list[Chunk]
114
+ duration: float # of the source
115
+ speech: list[Span] # in source seconds
116
+ source: SourceInfo | None = None
117
+ stripped_seconds: float = 0.0
118
+
119
+ @property
120
+ def action(self) -> str:
121
+ if len(self.chunks) > 1:
122
+ return "split"
123
+ return "strip" if self.stripped_seconds > 0 else "compress"
124
+
125
+ def summary(self) -> str:
126
+ total = sum(c.size_bytes for c in self.chunks)
127
+ lines = [
128
+ f"{self.preset.name}: {len(self.chunks)} chunk(s), {total / 1e6:.1f} MB total"
129
+ + (
130
+ f", {self.stripped_seconds:.0f} s of silence removed"
131
+ if self.stripped_seconds
132
+ else ""
133
+ )
134
+ ]
135
+ for c in self.chunks:
136
+ lines.append(
137
+ f" #{c.index:<3d} {_hms(c.start)}–{_hms(c.end)} {c.duration:7.1f} s "
138
+ f"{c.size_bytes / 1e6:6.2f} MB"
139
+ )
140
+ return "\n".join(lines)
141
+
142
+ def to_dict(self) -> dict:
143
+ return {
144
+ "preset": self.preset.name,
145
+ "action": self.action,
146
+ "fmt": self.preset.fmt,
147
+ "duration": round(self.duration, 3),
148
+ "stripped_seconds": round(self.stripped_seconds, 3),
149
+ "source": self.source.path if self.source else None,
150
+ "speech": [[s.start, s.end] for s in self.speech],
151
+ "chunks": [c.to_dict() for c in self.chunks],
152
+ }
153
+
154
+ def save(self, directory: str | Path) -> Path:
155
+ """Write every chunk plus ``manifest.json`` (needed later by ``stitch``)."""
156
+ directory = Path(directory)
157
+ directory.mkdir(parents=True, exist_ok=True)
158
+ for c in self.chunks:
159
+ c.path = c.save(directory / c.filename)
160
+ manifest = directory / MANIFEST
161
+ manifest.write_text(json.dumps(self.to_dict(), ensure_ascii=False, indent=2), "utf-8")
162
+ return manifest
163
+
164
+ @classmethod
165
+ def load(cls, path: str | Path) -> PreparedResult:
166
+ """Read a saved ``manifest.json`` (or the directory holding it)."""
167
+ path = Path(path)
168
+ if path.is_dir():
169
+ path = path / MANIFEST
170
+ data = json.loads(path.read_text("utf-8"))
171
+ preset = presets.TRANSCRIBE.get(data["preset"]) or presets.custom(fmt=data["fmt"])
172
+ chunks = [
173
+ Chunk(
174
+ index=c["index"],
175
+ pieces=[Piece(*p) for p in c["pieces"]],
176
+ speech=[Span(*s) for s in c["speech"]],
177
+ fmt=c["fmt"],
178
+ path=path.parent / c["file"],
179
+ )
180
+ for c in data["chunks"]
181
+ ]
182
+ return cls(
183
+ preset=preset,
184
+ chunks=chunks,
185
+ duration=data["duration"],
186
+ speech=[Span(*s) for s in data["speech"]],
187
+ stripped_seconds=data.get("stripped_seconds", 0.0),
188
+ )
189
+
190
+
191
+ def resolve_preset(
192
+ target: str | presets.TranscribePreset,
193
+ max_mb: float | None = None,
194
+ max_seconds: float | None = None,
195
+ sample_rate: int | None = None,
196
+ fmt: str | None = None,
197
+ bitrate: int | None = None,
198
+ ) -> presets.TranscribePreset:
199
+ if isinstance(target, presets.TranscribePreset):
200
+ p = target
201
+ elif target == "custom":
202
+ p = presets.custom()
203
+ else:
204
+ p = presets.get(target)
205
+ if not isinstance(p, presets.TranscribePreset):
206
+ raise ValueError(f"{target!r} is a voice-clone preset; use extract_reference()")
207
+ return p.with_limits(
208
+ max_bytes=int(max_mb * presets.MB) if max_mb else None,
209
+ max_seconds=max_seconds,
210
+ sample_rate=sample_rate,
211
+ fmt=fmt,
212
+ bitrate=bitrate,
213
+ )
214
+
215
+
216
+ def prepare(
217
+ source: io.Source | Audio,
218
+ target: str | presets.TranscribePreset = "openai",
219
+ *,
220
+ strip_silence: bool = False,
221
+ vad_backend: str = "auto",
222
+ max_mb: float | None = None,
223
+ max_seconds: float | None = None,
224
+ sample_rate: int | None = None,
225
+ fmt: str | None = None,
226
+ bitrate: int | None = None,
227
+ ) -> PreparedResult:
228
+ """Turn ``source`` into chunks that ``target`` accepts.
229
+
230
+ The whole file is re-encoded first; it is split only if it still exceeds the target's
231
+ size or duration limit, and then only at pauses found by VAD (or, inside very long
232
+ unbroken speech, at the quietest moment). ``strip_silence`` removes long pauses first
233
+ and keeps a map so timestamps still point into the original file.
234
+ """
235
+ preset = resolve_preset(target, max_mb, max_seconds, sample_rate, fmt, bitrate)
236
+ if isinstance(source, Audio):
237
+ audio = source.resample(preset.sample_rate)
238
+ else:
239
+ audio = io.load(source, preset.sample_rate)
240
+ duration = audio.duration
241
+ probs = vad.probabilities(audio, vad_backend)
242
+ speech = vad.speech_spans(probs, duration, min_silence=0.3, pad=0.1)
243
+
244
+ # Working timeline: the full file, or only its speech when stripping silence.
245
+ if strip_silence and speech:
246
+ work, work_pieces = _condense(audio, speech, keep=0.25)
247
+ work_speech = [_to_work(s, work_pieces) for s in speech]
248
+ work_probs = vad.probabilities(work, vad_backend)
249
+ else:
250
+ work, work_pieces, work_speech, work_probs = (
251
+ audio,
252
+ [Piece(0.0, 0.0, duration)],
253
+ speech,
254
+ probs,
255
+ )
256
+
257
+ limit = _seconds_limit(preset)
258
+ for _ in range(4):
259
+ cuts = _plan_cuts(work.duration, work_speech, work_probs, limit, preset.min_billed_seconds)
260
+ chunks = _build_chunks(work, work_pieces, work_speech, cuts, preset)
261
+ too_big = [c for c in chunks if preset.max_bytes and c.size_bytes > preset.max_bytes]
262
+ if not too_big:
263
+ break
264
+ worst = max(c.size_bytes / c.duration for c in too_big)
265
+ limit = min(limit, preset.max_bytes / worst * SAFETY)
266
+ else:
267
+ raise RuntimeError("could not fit chunks under the size limit")
268
+
269
+ return PreparedResult(
270
+ preset=preset,
271
+ chunks=chunks,
272
+ duration=duration,
273
+ speech=speech,
274
+ source=audio.source,
275
+ stripped_seconds=round(duration - work.duration, 3) if strip_silence else 0.0,
276
+ )
277
+
278
+
279
+ # ---------- planning ----------
280
+
281
+
282
+ def _seconds_limit(preset: presets.TranscribePreset) -> float:
283
+ limit = preset.max_seconds or math.inf
284
+ if preset.max_bytes:
285
+ overhead = io.estimate_size(0, preset.fmt, preset.sample_rate, preset.bitrate)
286
+ per_sec = io.estimate_size(3600, preset.fmt, preset.sample_rate, preset.bitrate) - overhead
287
+ limit = min(limit, (preset.max_bytes - overhead) / (per_sec / 3600))
288
+ return limit * SAFETY
289
+
290
+
291
+ def _plan_cuts(
292
+ duration: float,
293
+ speech: list[Span],
294
+ probs: np.ndarray,
295
+ limit: float,
296
+ min_chunk: float | None,
297
+ ) -> list[float]:
298
+ """Cut times so every chunk is at most ``limit`` seconds, preferring the middle of pauses."""
299
+ if duration <= limit:
300
+ return []
301
+ # (pause midpoint, pause length) between consecutive speech spans
302
+ pauses = [
303
+ ((a.end + b.start) / 2, b.start - a.end) for a, b in zip(speech, speech[1:], strict=False)
304
+ ]
305
+ floor = max(min_chunk or 0.0, 1.0)
306
+ cuts: list[float] = []
307
+ start = 0.0
308
+ while duration - start > limit:
309
+ window_end = start + limit
310
+ options = [p for p in pauses if start + floor < p[0] <= window_end]
311
+ late = [p for p in options if p[0] >= start + 0.6 * limit]
312
+ if late: # near the limit, prefer the longest pause (between sentences or speakers)
313
+ cut = max(late, key=lambda p: (round(p[1], 1), p[0]))[0]
314
+ elif options:
315
+ cut = options[-1][0]
316
+ else: # unbroken speech: cut where it is quietest
317
+ cut = _quietest(probs, start + limit * 0.5, window_end)
318
+ cuts.append(cut)
319
+ start = cut
320
+ # Avoid a tiny last chunk (e.g. Groq bills anything under 10 s as 10 s).
321
+ if min_chunk and cuts and duration - cuts[-1] < min_chunk:
322
+ prev = cuts[-2] if len(cuts) > 1 else 0.0
323
+ if duration - prev <= limit:
324
+ cuts.pop()
325
+ else:
326
+ earlier = [
327
+ p[0]
328
+ for p in pauses
329
+ if max(prev + floor, duration - limit) <= p[0] <= duration - min_chunk
330
+ ]
331
+ if earlier:
332
+ cuts[-1] = earlier[-1]
333
+ return cuts
334
+
335
+
336
+ def _quietest(probs: np.ndarray, a: float, b: float) -> float:
337
+ """Time of the lowest smoothed speech probability in ``[a, b]``."""
338
+ i, j = int(a / vad.FRAME_SEC), int(b / vad.FRAME_SEC)
339
+ seg = probs[i:j]
340
+ if len(seg) == 0:
341
+ return b
342
+ smooth = np.convolve(seg, np.ones(5) / 5, mode="same") if len(seg) >= 5 else seg
343
+ # among equally quiet frames, take the latest, to keep chunks long
344
+ k = len(smooth) - 1 - int(np.argmin(smooth[::-1]))
345
+ return round((i + k) * vad.FRAME_SEC, 3)
346
+
347
+
348
+ def _build_chunks(
349
+ work: Audio,
350
+ work_pieces: list[Piece],
351
+ speech: list[Span],
352
+ cuts: list[float],
353
+ preset: presets.TranscribePreset,
354
+ ) -> list[Chunk]:
355
+ bounds = [0.0, *cuts, work.duration]
356
+ chunks = []
357
+ for idx, (a, b) in enumerate(zip(bounds, bounds[1:], strict=False)):
358
+ chunks.append(
359
+ Chunk(
360
+ index=idx,
361
+ pieces=_slice_pieces(work_pieces, a, b),
362
+ speech=[
363
+ Span(round(max(s.start, a) - a, 3), round(min(s.end, b) - a, 3))
364
+ for s in speech
365
+ if s.end > a and s.start < b
366
+ ],
367
+ fmt=preset.fmt,
368
+ bitrate=preset.bitrate,
369
+ audio=work.slice(a, b),
370
+ )
371
+ )
372
+ return chunks
373
+
374
+
375
+ def _slice_pieces(pieces: list[Piece], a: float, b: float) -> list[Piece]:
376
+ out = []
377
+ for p in pieces:
378
+ lo, hi = max(a, p.local_start), min(b, p.local_start + p.duration)
379
+ if hi > lo:
380
+ out.append(
381
+ Piece(
382
+ round(lo - a, 3),
383
+ round(p.source_start + lo - p.local_start, 3),
384
+ round(hi - lo, 3),
385
+ )
386
+ )
387
+ return out
388
+
389
+
390
+ def _condense(audio: Audio, speech: list[Span], keep: float) -> tuple[Audio, list[Piece]]:
391
+ """Keep speech plus ``keep`` seconds around it; drop the rest of each pause."""
392
+ regions: list[list[float]] = []
393
+ for s in speech:
394
+ a, b = max(0.0, s.start - keep), min(audio.duration, s.end + keep)
395
+ if regions and a <= regions[-1][1]:
396
+ regions[-1][1] = max(regions[-1][1], b)
397
+ else:
398
+ regions.append([a, b])
399
+ parts, pieces, t = [], [], 0.0
400
+ for a, b in regions:
401
+ part = audio.slice(a, b).samples
402
+ parts.append(part)
403
+ d = len(part) / audio.sample_rate
404
+ pieces.append(Piece(round(t, 3), round(a, 3), round(d, 3)))
405
+ t += d
406
+ return Audio(np.concatenate(parts), audio.sample_rate, audio.source), pieces
407
+
408
+
409
+ def _to_work(span: Span, pieces: list[Piece]) -> Span:
410
+ for p in pieces:
411
+ if p.source_start - 1e-3 <= span.start <= p.source_start + p.duration + 1e-3:
412
+ a = p.local_start + (span.start - p.source_start)
413
+ return Span(round(a, 3), round(a + span.duration, 3))
414
+ return span
415
+
416
+
417
+ def _hms(seconds: float) -> str:
418
+ s = int(round(seconds))
419
+ h, rem = divmod(s, 3600)
420
+ m, s = divmod(rem, 60)
421
+ return f"{h}:{m:02d}:{s:02d}"