yakbox 0.3.0__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 yakbox might be problematic. Click here for more details.
- yakbox/__init__.py +27 -0
- yakbox/__main__.py +4 -0
- yakbox/_build.py +95 -0
- yakbox/_build_commit.py +3 -0
- yakbox/_files.py +159 -0
- yakbox/_http.py +20 -0
- yakbox/_version.py +20 -0
- yakbox/audio/__init__.py +14 -0
- yakbox/audio/assemble.py +209 -0
- yakbox/audio/crop.py +628 -0
- yakbox/audio/inspect.py +391 -0
- yakbox/audio/master.py +188 -0
- yakbox/audio/splice.py +505 -0
- yakbox/audiobook/__init__.py +197 -0
- yakbox/audiobook/artifacts.py +215 -0
- yakbox/audiobook/assembly_manifest.py +349 -0
- yakbox/audiobook/build.py +4698 -0
- yakbox/audiobook/cache.py +292 -0
- yakbox/audiobook/cleanup.py +560 -0
- yakbox/audiobook/dialogue.py +278 -0
- yakbox/audiobook/journal.py +157 -0
- yakbox/audiobook/manifest.py +1892 -0
- yakbox/audiobook/performance.py +208 -0
- yakbox/audiobook/planner.py +999 -0
- yakbox/audiobook/repair.py +1766 -0
- yakbox/audiobook/repair_cache.py +205 -0
- yakbox/audiobook/repairs.py +280 -0
- yakbox/audiobook/shards.py +129 -0
- yakbox/audiobook/sources.py +1498 -0
- yakbox/cli.py +2910 -0
- yakbox/cli_dialogue.py +188 -0
- yakbox/cli_help.py +137 -0
- yakbox/cli_migrate.py +150 -0
- yakbox/cli_options.py +116 -0
- yakbox/cli_repair.py +565 -0
- yakbox/cli_runtime.py +188 -0
- yakbox/cli_speech_review.py +177 -0
- yakbox/cli_whisper.py +926 -0
- yakbox/cli_workspace.py +148 -0
- yakbox/cloud/__init__.py +71 -0
- yakbox/cloud/batch.py +1180 -0
- yakbox/cloud/client.py +759 -0
- yakbox/cloud/errors.py +92 -0
- yakbox/cloud/journal.py +162 -0
- yakbox/cloud/models.py +157 -0
- yakbox/cloud/output.py +82 -0
- yakbox/cloud/rate_limit.py +24 -0
- yakbox/cloud/retry.py +88 -0
- yakbox/cloud/service.py +209 -0
- yakbox/cloud/usage.py +159 -0
- yakbox/config.py +73 -0
- yakbox/contracts.py +27 -0
- yakbox/credentials.py +45 -0
- yakbox/data/speech-evaluation-protocol-v1.toml +40 -0
- yakbox/data/speech-model-candidates-v1.toml +147 -0
- yakbox/data/speech-model-registry-v1.toml +270 -0
- yakbox/data/speech-performance-protocol-v1.toml +24 -0
- yakbox/data/whisper-calibration-v1.toml +93 -0
- yakbox/diagnostics/__init__.py +17 -0
- yakbox/diagnostics/checks.py +645 -0
- yakbox/diagnostics/models.py +65 -0
- yakbox/errors.py +70 -0
- yakbox/fingerprints.py +89 -0
- yakbox/local.py +395 -0
- yakbox/local_alignment.py +592 -0
- yakbox/local_phoneme_alignment.py +436 -0
- yakbox/local_runtime.py +1023 -0
- yakbox/phoneme_models.py +132 -0
- yakbox/phoneme_qa.py +78 -0
- yakbox/py.typed +1 -0
- yakbox/release_automation.py +321 -0
- yakbox/release_preflight.py +441 -0
- yakbox/runtimes/analysis-worker.pyz +0 -0
- yakbox/runtimes/parakeet/pyproject.toml +14 -0
- yakbox/runtimes/parakeet/runtime.toml +7 -0
- yakbox/runtimes/parakeet/uv.lock +838 -0
- yakbox/runtimes/qwen/pyproject.toml +14 -0
- yakbox/runtimes/qwen/runtime.toml +7 -0
- yakbox/runtimes/qwen/uv.lock +729 -0
- yakbox/runtimes/whisper/pyproject.toml +14 -0
- yakbox/runtimes/whisper/runtime.toml +7 -0
- yakbox/runtimes/whisper/uv.lock +900 -0
- yakbox/schemas/__init__.py +34 -0
- yakbox/schemas/audio-inspection-v1.schema.json +23 -0
- yakbox/schemas/audiobook-artifact-v1.schema.json +29 -0
- yakbox/schemas/audiobook-assembly-v1.schema.json +61 -0
- yakbox/schemas/audiobook-audition-v1.schema.json +16 -0
- yakbox/schemas/audiobook-chapter-inspection-v1.schema.json +16 -0
- yakbox/schemas/audiobook-cleanup-plan-v1.schema.json +23 -0
- yakbox/schemas/audiobook-cleanup-report-v1.schema.json +17 -0
- yakbox/schemas/audiobook-cleanup-v1.schema.json +13 -0
- yakbox/schemas/audiobook-inventory-v1.schema.json +19 -0
- yakbox/schemas/audiobook-journal-v1.schema.json +17 -0
- yakbox/schemas/audiobook-manifest-migration-preview-v1.schema.json +49 -0
- yakbox/schemas/audiobook-manifest-migration-v1.schema.json +42 -0
- yakbox/schemas/audiobook-manifest-v1.schema.json +213 -0
- yakbox/schemas/audiobook-manifest-v2.schema.json +136 -0
- yakbox/schemas/audiobook-performance-v1.schema.json +135 -0
- yakbox/schemas/audiobook-plan-v1.schema.json +149 -0
- yakbox/schemas/audiobook-quarantine-v1.schema.json +19 -0
- yakbox/schemas/audiobook-release-check-v1.schema.json +19 -0
- yakbox/schemas/audiobook-release-v1.schema.json +27 -0
- yakbox/schemas/audiobook-repair-batch-generation-v1.schema.json +17 -0
- yakbox/schemas/audiobook-repair-batch-v1.schema.json +56 -0
- yakbox/schemas/audiobook-repair-location-v1.schema.json +20 -0
- yakbox/schemas/audiobook-repair-session-v1.schema.json +111 -0
- yakbox/schemas/audiobook-repair-splice-v1.schema.json +36 -0
- yakbox/schemas/audiobook-repairs-v1.schema.json +46 -0
- yakbox/schemas/audiobook-run-v1.schema.json +18 -0
- yakbox/schemas/audiobook-shard-v1.schema.json +20 -0
- yakbox/schemas/batch-journal-v1.schema.json +18 -0
- yakbox/schemas/batch-report-v1.schema.json +20 -0
- yakbox/schemas/cli-output-v1.schema.json +91 -0
- yakbox/schemas/dialogue-routes-v1.schema.json +29 -0
- yakbox/schemas/dialogue-transformation-v1.schema.json +78 -0
- yakbox/schemas/doctor-report-v1.schema.json +22 -0
- yakbox/schemas/local-runtime-endpoint-v1.schema.json +19 -0
- yakbox/schemas/local-runtime-status-v1.schema.json +23 -0
- yakbox/schemas/phoneme-inspection-v1.schema.json +47 -0
- yakbox/schemas/pronunciations-v2.schema.json +50 -0
- yakbox/schemas/short-utterance-preflight-v1.schema.json +32 -0
- yakbox/schemas/short-utterance-qa-v1.schema.json +24 -0
- yakbox/schemas/short-utterance-test-v1.schema.json +21 -0
- yakbox/schemas/speech-analysis-cutover-readiness-v1.schema.json +46 -0
- yakbox/schemas/speech-analysis-evaluation-v1.schema.json +99 -0
- yakbox/schemas/speech-analysis-independent-evidence-v1.schema.json +65 -0
- yakbox/schemas/speech-analysis-preflight-v1.schema.json +34 -0
- yakbox/schemas/speech-analysis-runtimes-v1.schema.json +51 -0
- yakbox/schemas/speech-analysis-shadow-v1.schema.json +38 -0
- yakbox/schemas/speech-chapter-verification-v1.schema.json +61 -0
- yakbox/schemas/speech-consensus-v1.schema.json +74 -0
- yakbox/schemas/speech-corpus-boundary-authoring-v1.schema.json +77 -0
- yakbox/schemas/speech-corpus-boundary-truth-v1.schema.json +65 -0
- yakbox/schemas/speech-corpus-partition-v1.schema.json +39 -0
- yakbox/schemas/speech-corpus-source-archives-v1.schema.json +39 -0
- yakbox/schemas/speech-corpus-source-inventory-v1.schema.json +49 -0
- yakbox/schemas/speech-corpus-text-anchors-v1.schema.json +67 -0
- yakbox/schemas/speech-corpus-text-sources-v1.schema.json +46 -0
- yakbox/schemas/speech-corpus-transcript-agreement-v1.schema.json +67 -0
- yakbox/schemas/speech-corpus-transcript-draft-v1.schema.json +60 -0
- yakbox/schemas/speech-corpus-transcript-truth-v1.schema.json +40 -0
- yakbox/schemas/speech-forced-alignment-v1.schema.json +100 -0
- yakbox/schemas/speech-human-disposition-v1.schema.json +31 -0
- yakbox/schemas/speech-human-review-candidate-v1.schema.json +40 -0
- yakbox/schemas/speech-human-review-status-v1.schema.json +34 -0
- yakbox/schemas/speech-join-verification-v1.schema.json +35 -0
- yakbox/schemas/speech-performance-qualification-v1.schema.json +51 -0
- yakbox/schemas/speech-qualification-review-v1.schema.json +45 -0
- yakbox/schemas/speech-recognition-v1.schema.json +133 -0
- yakbox/schemas/speech-release-evidence-snapshot-v1.schema.json +40 -0
- yakbox/schemas/speech-release-verification-v1.schema.json +134 -0
- yakbox/schemas/speech-repair-candidate-verification-v1.schema.json +61 -0
- yakbox/schemas/speech-verification-v1.schema.json +27 -0
- yakbox/schemas/voice-quality-v1.schema.json +83 -0
- yakbox/schemas/whisper-calibration-v1.schema.json +27 -0
- yakbox/schemas/whisper-changed-region-verification-v1.schema.json +44 -0
- yakbox/schemas/whisper-inspection-v1.schema.json +29 -0
- yakbox/schemas/whisper-join-inspection-v1.schema.json +65 -0
- yakbox/schemas/whisper-manuscript-verification-v1.schema.json +36 -0
- yakbox/short_testing.py +279 -0
- yakbox/speech/__init__.py +65 -0
- yakbox/speech/accelerator.py +52 -0
- yakbox/speech/alignment.py +608 -0
- yakbox/speech/analysis_adapters.py +1018 -0
- yakbox/speech/analysis_attestation.py +292 -0
- yakbox/speech/analysis_cache.py +592 -0
- yakbox/speech/analysis_calibration.py +195 -0
- yakbox/speech/analysis_capabilities.py +169 -0
- yakbox/speech/analysis_corpus_archives.py +416 -0
- yakbox/speech/analysis_corpus_boundaries.py +712 -0
- yakbox/speech/analysis_corpus_partition.py +341 -0
- yakbox/speech/analysis_corpus_passages.py +321 -0
- yakbox/speech/analysis_corpus_review.py +137 -0
- yakbox/speech/analysis_corpus_sources.py +546 -0
- yakbox/speech/analysis_corpus_text_anchors.py +711 -0
- yakbox/speech/analysis_corpus_text_sources.py +854 -0
- yakbox/speech/analysis_corpus_transcripts.py +737 -0
- yakbox/speech/analysis_corpus_truth.py +670 -0
- yakbox/speech/analysis_cutover.py +250 -0
- yakbox/speech/analysis_disposition.py +652 -0
- yakbox/speech/analysis_evaluation.py +1346 -0
- yakbox/speech/analysis_fingerprints.py +62 -0
- yakbox/speech/analysis_manifest.py +669 -0
- yakbox/speech/analysis_migration.py +781 -0
- yakbox/speech/analysis_models.py +995 -0
- yakbox/speech/analysis_performance_qualification.py +545 -0
- yakbox/speech/analysis_pipeline.py +800 -0
- yakbox/speech/analysis_policy.py +314 -0
- yakbox/speech/analysis_preflight.py +281 -0
- yakbox/speech/analysis_protocol.py +1349 -0
- yakbox/speech/analysis_release.py +977 -0
- yakbox/speech/analysis_repair.py +613 -0
- yakbox/speech/analysis_review.py +424 -0
- yakbox/speech/analysis_runtime.py +1007 -0
- yakbox/speech/analysis_runtime_identity.py +83 -0
- yakbox/speech/analysis_runtime_install.py +522 -0
- yakbox/speech/analysis_scheduler.py +1189 -0
- yakbox/speech/analysis_serialization.py +488 -0
- yakbox/speech/analysis_services.py +130 -0
- yakbox/speech/analysis_text_plan.py +302 -0
- yakbox/speech/analysis_windows.py +280 -0
- yakbox/speech/analysis_worker.py +887 -0
- yakbox/speech/analysis_worker_artifact.py +196 -0
- yakbox/speech/canonical_audio.py +424 -0
- yakbox/speech/capabilities.py +16 -0
- yakbox/speech/chunking.py +92 -0
- yakbox/speech/consensus.py +466 -0
- yakbox/speech/fingerprints.py +48 -0
- yakbox/speech/guardrails.py +154 -0
- yakbox/speech/model_registry.py +639 -0
- yakbox/speech/models.py +176 -0
- yakbox/speech/normalization.py +253 -0
- yakbox/speech/phonemes.py +129 -0
- yakbox/speech/services.py +321 -0
- yakbox/speech/shadow.py +97 -0
- yakbox/speech/short_synthesis.py +1794 -0
- yakbox/speech/short_utterances.py +590 -0
- yakbox/speech/waves.py +267 -0
- yakbox/speech/workers.py +633 -0
- yakbox/textutils.py +115 -0
- yakbox/voice_quality.py +606 -0
- yakbox/whisper_cache.py +259 -0
- yakbox/whisper_calibration.py +223 -0
- yakbox/whisper_inspection.py +183 -0
- yakbox/whisper_models.py +179 -0
- yakbox/whisper_qa.py +1305 -0
- yakbox/yaml_config.py +74 -0
- yakbox-0.3.0.dist-info/METADATA +147 -0
- yakbox-0.3.0.dist-info/RECORD +233 -0
- yakbox-0.3.0.dist-info/WHEEL +4 -0
- yakbox-0.3.0.dist-info/entry_points.txt +4 -0
- yakbox-0.3.0.dist-info/licenses/LICENSE +21 -0
- yakbox-0.3.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +104 -0
yakbox/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Yakbox audiobook build system."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
from yakbox.errors import (
|
|
6
|
+
ArtifactError,
|
|
7
|
+
BackendUnavailableError,
|
|
8
|
+
BuildError,
|
|
9
|
+
ConfigurationError,
|
|
10
|
+
ValidationError,
|
|
11
|
+
YakboxError,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
try:
|
|
15
|
+
__version__ = version("yakbox")
|
|
16
|
+
except PackageNotFoundError: # pragma: no cover - source tree without install
|
|
17
|
+
__version__ = "0.3.0"
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"ArtifactError",
|
|
21
|
+
"BackendUnavailableError",
|
|
22
|
+
"BuildError",
|
|
23
|
+
"ConfigurationError",
|
|
24
|
+
"ValidationError",
|
|
25
|
+
"YakboxError",
|
|
26
|
+
"__version__",
|
|
27
|
+
]
|
yakbox/__main__.py
ADDED
yakbox/_build.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Embed the source commit in distributions built with the native uv backend."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import re
|
|
7
|
+
import shutil
|
|
8
|
+
import stat
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
from collections.abc import Generator, Sequence
|
|
12
|
+
from contextlib import contextmanager
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from yakbox._files import atomic_write_bytes
|
|
16
|
+
from yakbox.errors import BuildError
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@contextmanager
|
|
20
|
+
def embedded_commit(root: Path, commit: str) -> Generator[None]:
|
|
21
|
+
if re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", commit) is None:
|
|
22
|
+
raise BuildError("Build commit must be a full Git commit hash")
|
|
23
|
+
root = root.resolve()
|
|
24
|
+
metadata = root / "src" / "yakbox" / "_build_commit.py"
|
|
25
|
+
if metadata.is_symlink() or not metadata.resolve().is_relative_to(root):
|
|
26
|
+
raise BuildError("Build commit metadata must stay inside the source root")
|
|
27
|
+
try:
|
|
28
|
+
original = metadata.read_bytes()
|
|
29
|
+
mode = stat.S_IMODE(metadata.stat().st_mode)
|
|
30
|
+
except OSError as error:
|
|
31
|
+
raise BuildError("Cannot read source build commit metadata") from error
|
|
32
|
+
stamped = (
|
|
33
|
+
'"""Immutable source commit embedded during packaging."""\n\n'
|
|
34
|
+
f"COMMIT: str | None = {commit!r}\n"
|
|
35
|
+
).encode()
|
|
36
|
+
try:
|
|
37
|
+
atomic_write_bytes(metadata, stamped, overwrite=True)
|
|
38
|
+
metadata.chmod(mode)
|
|
39
|
+
yield
|
|
40
|
+
finally:
|
|
41
|
+
atomic_write_bytes(metadata, original, overwrite=True)
|
|
42
|
+
metadata.chmod(mode)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def main(arguments: Sequence[str] | None = None) -> None:
|
|
46
|
+
parser = argparse.ArgumentParser(
|
|
47
|
+
description="Build distributions with their commit."
|
|
48
|
+
)
|
|
49
|
+
parser.add_argument("--root", type=Path, default=Path.cwd())
|
|
50
|
+
parser.add_argument("--out-dir", type=Path, default=Path("dist"))
|
|
51
|
+
options = parser.parse_args(arguments)
|
|
52
|
+
root = options.root.resolve()
|
|
53
|
+
output = (root / options.out_dir).resolve()
|
|
54
|
+
if output == root or not output.is_relative_to(root):
|
|
55
|
+
parser.error("Build output must be a child of the project root")
|
|
56
|
+
git = shutil.which("git")
|
|
57
|
+
uv = shutil.which("uv")
|
|
58
|
+
if git is None or uv is None:
|
|
59
|
+
parser.error("Building commit metadata requires Git and uv")
|
|
60
|
+
try:
|
|
61
|
+
status = subprocess.check_output( # noqa: S603 - fixed Git argv; no shell
|
|
62
|
+
(git, "status", "--porcelain", "--untracked-files=all"),
|
|
63
|
+
cwd=root,
|
|
64
|
+
text=True,
|
|
65
|
+
timeout=10,
|
|
66
|
+
)
|
|
67
|
+
if status.strip():
|
|
68
|
+
raise BuildError("Commit-stamped builds require a clean Git worktree")
|
|
69
|
+
commit = subprocess.check_output( # noqa: S603 - fixed Git argv; no shell
|
|
70
|
+
(git, "rev-parse", "--verify", "HEAD"),
|
|
71
|
+
cwd=root,
|
|
72
|
+
text=True,
|
|
73
|
+
timeout=10,
|
|
74
|
+
).strip()
|
|
75
|
+
with embedded_commit(root, commit):
|
|
76
|
+
result = subprocess.run( # noqa: S603 - fixed uv argv and managed paths
|
|
77
|
+
(
|
|
78
|
+
uv,
|
|
79
|
+
"build",
|
|
80
|
+
"--no-sources",
|
|
81
|
+
"--clear",
|
|
82
|
+
"--no-create-gitignore",
|
|
83
|
+
"--out-dir",
|
|
84
|
+
str(output),
|
|
85
|
+
),
|
|
86
|
+
cwd=root,
|
|
87
|
+
check=False,
|
|
88
|
+
)
|
|
89
|
+
except (BuildError, OSError, subprocess.SubprocessError) as error:
|
|
90
|
+
parser.exit(1, f"Build failed: {error}\n")
|
|
91
|
+
sys.exit(result.returncode)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
if __name__ == "__main__":
|
|
95
|
+
main()
|
yakbox/_build_commit.py
ADDED
yakbox/_files.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Safe filesystem primitives shared by application services."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import tempfile
|
|
9
|
+
from collections.abc import Generator, Mapping
|
|
10
|
+
from contextlib import contextmanager
|
|
11
|
+
from functools import lru_cache
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from yakbox.errors import ArtifactError
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def sha256_bytes(data: bytes) -> str:
|
|
18
|
+
return hashlib.sha256(data).hexdigest()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def sha256_file(path: Path) -> str:
|
|
22
|
+
resolved = path.resolve()
|
|
23
|
+
before = _file_signature(resolved)
|
|
24
|
+
digest = _sha256_snapshot(str(resolved), *before)
|
|
25
|
+
after = _file_signature(resolved)
|
|
26
|
+
if after != before:
|
|
27
|
+
digest = _sha256_snapshot(str(resolved), *after)
|
|
28
|
+
return digest
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@lru_cache(maxsize=4_096)
|
|
32
|
+
def _sha256_snapshot(
|
|
33
|
+
path: str,
|
|
34
|
+
_size: int,
|
|
35
|
+
_mtime_ns: int,
|
|
36
|
+
_ctime_ns: int,
|
|
37
|
+
_inode: int,
|
|
38
|
+
) -> str:
|
|
39
|
+
digest = hashlib.sha256()
|
|
40
|
+
with Path(path).open("rb") as stream:
|
|
41
|
+
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
|
42
|
+
digest.update(chunk)
|
|
43
|
+
return digest.hexdigest()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _file_signature(path: Path) -> tuple[int, int, int, int]:
|
|
47
|
+
status = path.stat()
|
|
48
|
+
return (
|
|
49
|
+
status.st_size,
|
|
50
|
+
status.st_mtime_ns,
|
|
51
|
+
status.st_ctime_ns,
|
|
52
|
+
status.st_ino,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def atomic_write_bytes(path: Path, data: bytes, *, overwrite: bool = False) -> None:
|
|
57
|
+
path = path.resolve()
|
|
58
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
59
|
+
if path.exists() and not overwrite:
|
|
60
|
+
raise ArtifactError(f"Output already exists: {path}")
|
|
61
|
+
descriptor, temporary_name = tempfile.mkstemp(
|
|
62
|
+
prefix=f".{path.name}.", suffix=".part", dir=path.parent
|
|
63
|
+
)
|
|
64
|
+
temporary = Path(temporary_name)
|
|
65
|
+
try:
|
|
66
|
+
with os.fdopen(descriptor, "wb") as stream:
|
|
67
|
+
stream.write(data)
|
|
68
|
+
stream.flush()
|
|
69
|
+
os.fsync(stream.fileno())
|
|
70
|
+
_publish_temporary_file(temporary, path, overwrite=overwrite)
|
|
71
|
+
finally:
|
|
72
|
+
temporary.unlink(missing_ok=True)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def atomic_write_json(
|
|
76
|
+
path: Path, value: Mapping[str, object], *, overwrite: bool = True
|
|
77
|
+
) -> None:
|
|
78
|
+
payload = json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False)
|
|
79
|
+
atomic_write_bytes(path, f"{payload}\n".encode(), overwrite=overwrite)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@contextmanager
|
|
83
|
+
def atomic_output_path(path: Path, *, overwrite: bool = False) -> Generator[Path]:
|
|
84
|
+
"""Yield a sibling temporary path and atomically commit it on success."""
|
|
85
|
+
path = path.resolve()
|
|
86
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
87
|
+
# Media encoders infer their container from the final suffix. Preserve it
|
|
88
|
+
# on the temporary file while keeping the partial-file marker visible.
|
|
89
|
+
temporary_suffix = f".part{path.suffix}" if path.suffix else ".part"
|
|
90
|
+
descriptor, temporary_name = tempfile.mkstemp(
|
|
91
|
+
prefix=f".{path.name}.", suffix=temporary_suffix, dir=path.parent
|
|
92
|
+
)
|
|
93
|
+
os.close(descriptor)
|
|
94
|
+
temporary = Path(temporary_name)
|
|
95
|
+
try:
|
|
96
|
+
yield temporary
|
|
97
|
+
if not temporary.is_file():
|
|
98
|
+
raise ArtifactError(f"Output writer did not create a file: {temporary}")
|
|
99
|
+
commit_temporary_file(temporary, path, overwrite=overwrite)
|
|
100
|
+
finally:
|
|
101
|
+
temporary.unlink(missing_ok=True)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def commit_temporary_file(
|
|
105
|
+
temporary: Path,
|
|
106
|
+
destination: Path,
|
|
107
|
+
*,
|
|
108
|
+
overwrite: bool = False,
|
|
109
|
+
) -> None:
|
|
110
|
+
"""Durably commit an already-written sibling temporary file."""
|
|
111
|
+
|
|
112
|
+
temporary = temporary.resolve()
|
|
113
|
+
destination = destination.resolve()
|
|
114
|
+
if temporary.parent != destination.parent:
|
|
115
|
+
raise ArtifactError("Atomic commit requires a sibling temporary file")
|
|
116
|
+
if not temporary.is_file() or temporary.stat().st_size == 0:
|
|
117
|
+
raise ArtifactError(f"Output writer produced no data: {temporary}")
|
|
118
|
+
# Windows requires a writable file descriptor for fsync(). Reopening the
|
|
119
|
+
# completed artifact read-only works on POSIX but fails with EBADF on
|
|
120
|
+
# Windows before the atomic replace can happen.
|
|
121
|
+
with temporary.open("rb+") as stream:
|
|
122
|
+
os.fsync(stream.fileno())
|
|
123
|
+
_publish_temporary_file(temporary, destination, overwrite=overwrite)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _publish_temporary_file(
|
|
127
|
+
temporary: Path, destination: Path, *, overwrite: bool
|
|
128
|
+
) -> None:
|
|
129
|
+
if overwrite:
|
|
130
|
+
temporary.replace(destination)
|
|
131
|
+
else:
|
|
132
|
+
try:
|
|
133
|
+
os.link(temporary, destination)
|
|
134
|
+
except FileExistsError as error:
|
|
135
|
+
raise ArtifactError(f"Output already exists: {destination}") from error
|
|
136
|
+
except OSError as error:
|
|
137
|
+
raise ArtifactError(
|
|
138
|
+
f"Filesystem cannot safely commit output: {destination}"
|
|
139
|
+
) from error
|
|
140
|
+
temporary.unlink()
|
|
141
|
+
_sync_directory(destination.parent)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def safe_child(root: Path, candidate: Path) -> Path:
|
|
145
|
+
resolved_root = root.resolve()
|
|
146
|
+
resolved = candidate.resolve()
|
|
147
|
+
if not resolved.is_relative_to(resolved_root):
|
|
148
|
+
raise ArtifactError(f"Path escapes managed root {resolved_root}: {candidate}")
|
|
149
|
+
return resolved
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _sync_directory(path: Path) -> None:
|
|
153
|
+
if os.name == "nt":
|
|
154
|
+
return
|
|
155
|
+
descriptor = os.open(path, os.O_RDONLY)
|
|
156
|
+
try:
|
|
157
|
+
os.fsync(descriptor)
|
|
158
|
+
finally:
|
|
159
|
+
os.close(descriptor)
|
yakbox/_http.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Internal HTTP response helpers for bounded, decoded bodies."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def buffered_response(response: httpx.Response, content: bytes) -> httpx.Response:
|
|
9
|
+
"""Retain response metadata without decoding the buffered body twice."""
|
|
10
|
+
headers = httpx.Headers(response.headers)
|
|
11
|
+
for name in ("content-encoding", "content-length", "transfer-encoding"):
|
|
12
|
+
headers.pop(name, None)
|
|
13
|
+
return httpx.Response(
|
|
14
|
+
response.status_code,
|
|
15
|
+
headers=headers,
|
|
16
|
+
content=content,
|
|
17
|
+
request=response.request,
|
|
18
|
+
extensions=response.extensions,
|
|
19
|
+
history=response.history,
|
|
20
|
+
)
|
yakbox/_version.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Version output reads immutable package metadata without consulting Git."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import click
|
|
6
|
+
|
|
7
|
+
from yakbox import __version__, _build_commit
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def version_output(version: str, commit: str | None) -> str:
|
|
11
|
+
return f"yakbox, version {version} (commit {commit or 'unknown'})"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def show_version(
|
|
15
|
+
context: click.Context, _parameter: click.Parameter, value: bool
|
|
16
|
+
) -> None:
|
|
17
|
+
if not value or context.resilient_parsing:
|
|
18
|
+
return
|
|
19
|
+
click.echo(version_output(__version__, _build_commit.COMMIT))
|
|
20
|
+
context.exit()
|
yakbox/audio/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""FFmpeg-backed audiobook audio operations."""
|
|
2
|
+
|
|
3
|
+
from yakbox.audio.assemble import assemble_m4b
|
|
4
|
+
from yakbox.audio.inspect import AudioInspection, AudioQualityPolicy, inspect_audio
|
|
5
|
+
from yakbox.audio.master import encode_mp3, master_wav
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"AudioInspection",
|
|
9
|
+
"AudioQualityPolicy",
|
|
10
|
+
"assemble_m4b",
|
|
11
|
+
"encode_mp3",
|
|
12
|
+
"inspect_audio",
|
|
13
|
+
"master_wav",
|
|
14
|
+
]
|
yakbox/audio/assemble.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import shutil
|
|
5
|
+
import subprocess
|
|
6
|
+
import tempfile
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from yakbox._files import commit_temporary_file
|
|
10
|
+
from yakbox.audio.inspect import inspect_audio
|
|
11
|
+
from yakbox.errors import ArtifactError, BackendUnavailableError
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def assemble_m4b(
|
|
15
|
+
chapters: tuple[Path, ...],
|
|
16
|
+
destination: Path,
|
|
17
|
+
*,
|
|
18
|
+
title: str,
|
|
19
|
+
author: str | None = None,
|
|
20
|
+
narrator: str | None = None,
|
|
21
|
+
subtitle: str | None = None,
|
|
22
|
+
genre: str | None = None,
|
|
23
|
+
publisher: str | None = None,
|
|
24
|
+
copyright: str | None = None,
|
|
25
|
+
language: str | None = None,
|
|
26
|
+
date: str | None = None,
|
|
27
|
+
series: str | None = None,
|
|
28
|
+
series_position: str | None = None,
|
|
29
|
+
cover: Path | None = None,
|
|
30
|
+
chapter_titles: tuple[str, ...] | None = None,
|
|
31
|
+
bitrate: str = "192k",
|
|
32
|
+
overwrite: bool = False,
|
|
33
|
+
) -> None:
|
|
34
|
+
"""Assemble ordered chapter audio into an atomic, metadata-rich M4B file."""
|
|
35
|
+
_validate_assembly_inputs(chapters, destination, overwrite=overwrite)
|
|
36
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
37
|
+
descriptor, list_name = tempfile.mkstemp(
|
|
38
|
+
prefix=".yakbox-concat-", suffix=".txt", dir=destination.parent
|
|
39
|
+
)
|
|
40
|
+
list_path = Path(list_name)
|
|
41
|
+
metadata_path = list_path.with_suffix(".ffmetadata")
|
|
42
|
+
output_descriptor, output_name = tempfile.mkstemp(
|
|
43
|
+
prefix=f".{destination.stem}.", suffix=".m4b", dir=destination.parent
|
|
44
|
+
)
|
|
45
|
+
os.close(output_descriptor)
|
|
46
|
+
output = Path(output_name)
|
|
47
|
+
output.unlink()
|
|
48
|
+
try:
|
|
49
|
+
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
|
|
50
|
+
for chapter in chapters:
|
|
51
|
+
escaped = str(chapter.resolve()).replace("'", "'\\''")
|
|
52
|
+
stream.write(f"file '{escaped}'\n")
|
|
53
|
+
if chapter_titles is not None and len(chapter_titles) != len(chapters):
|
|
54
|
+
raise ArtifactError("M4B chapter_titles must match the chapter count")
|
|
55
|
+
_write_chapter_metadata(
|
|
56
|
+
metadata_path,
|
|
57
|
+
chapters,
|
|
58
|
+
title=title,
|
|
59
|
+
author=author,
|
|
60
|
+
chapter_titles=chapter_titles,
|
|
61
|
+
)
|
|
62
|
+
command = [
|
|
63
|
+
"ffmpeg",
|
|
64
|
+
"-nostdin",
|
|
65
|
+
"-v",
|
|
66
|
+
"error",
|
|
67
|
+
"-f",
|
|
68
|
+
"concat",
|
|
69
|
+
"-safe",
|
|
70
|
+
"0",
|
|
71
|
+
"-i",
|
|
72
|
+
str(list_path),
|
|
73
|
+
"-i",
|
|
74
|
+
str(metadata_path),
|
|
75
|
+
]
|
|
76
|
+
if cover is not None:
|
|
77
|
+
if not cover.is_file():
|
|
78
|
+
raise ArtifactError(f"Missing M4B cover image: {cover}")
|
|
79
|
+
command.extend(["-i", str(cover)])
|
|
80
|
+
command.extend(
|
|
81
|
+
[
|
|
82
|
+
"-map",
|
|
83
|
+
"0:a:0",
|
|
84
|
+
"-map_metadata",
|
|
85
|
+
"1",
|
|
86
|
+
"-map_chapters",
|
|
87
|
+
"1",
|
|
88
|
+
"-c:a",
|
|
89
|
+
"aac",
|
|
90
|
+
"-b:a",
|
|
91
|
+
bitrate,
|
|
92
|
+
]
|
|
93
|
+
)
|
|
94
|
+
if cover is not None:
|
|
95
|
+
command.extend(
|
|
96
|
+
[
|
|
97
|
+
"-map",
|
|
98
|
+
"2:v:0",
|
|
99
|
+
"-c:v",
|
|
100
|
+
"copy",
|
|
101
|
+
"-disposition:v:0",
|
|
102
|
+
"attached_pic",
|
|
103
|
+
]
|
|
104
|
+
)
|
|
105
|
+
metadata = {
|
|
106
|
+
"title": title,
|
|
107
|
+
"artist": author,
|
|
108
|
+
"composer": narrator,
|
|
109
|
+
"subtitle": subtitle,
|
|
110
|
+
"genre": genre,
|
|
111
|
+
"publisher": publisher,
|
|
112
|
+
"copyright": copyright,
|
|
113
|
+
"language": language,
|
|
114
|
+
"date": date,
|
|
115
|
+
"show": series,
|
|
116
|
+
"episode_sort": series_position,
|
|
117
|
+
}
|
|
118
|
+
for key, value in metadata.items():
|
|
119
|
+
if value:
|
|
120
|
+
command.extend(["-metadata", f"{key}={value}"])
|
|
121
|
+
command.append(str(output))
|
|
122
|
+
_run_ffmpeg_assembly(command)
|
|
123
|
+
inspection = inspect_audio(output)
|
|
124
|
+
if not inspection.valid:
|
|
125
|
+
raise ArtifactError(
|
|
126
|
+
"Assembled M4B is invalid: " + "; ".join(inspection.issues)
|
|
127
|
+
)
|
|
128
|
+
commit_temporary_file(output, destination, overwrite=overwrite)
|
|
129
|
+
finally:
|
|
130
|
+
list_path.unlink(missing_ok=True)
|
|
131
|
+
metadata_path.unlink(missing_ok=True)
|
|
132
|
+
output.unlink(missing_ok=True)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _validate_assembly_inputs(
|
|
136
|
+
chapters: tuple[Path, ...],
|
|
137
|
+
destination: Path,
|
|
138
|
+
*,
|
|
139
|
+
overwrite: bool,
|
|
140
|
+
) -> None:
|
|
141
|
+
if not chapters:
|
|
142
|
+
raise ArtifactError("At least one chapter is required for assembly")
|
|
143
|
+
if shutil.which("ffmpeg") is None:
|
|
144
|
+
raise BackendUnavailableError("FFmpeg is required for M4B assembly")
|
|
145
|
+
if destination.exists() and not overwrite:
|
|
146
|
+
raise ArtifactError(f"Output already exists: {destination}")
|
|
147
|
+
missing = next((chapter for chapter in chapters if not chapter.is_file()), None)
|
|
148
|
+
if missing is not None:
|
|
149
|
+
raise ArtifactError(f"Missing chapter for assembly: {missing}")
|
|
150
|
+
if len({chapter.resolve() for chapter in chapters}) != len(chapters):
|
|
151
|
+
raise ArtifactError("Assembly chapters must not contain duplicates")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _run_ffmpeg_assembly(command: list[str]) -> None:
|
|
155
|
+
try:
|
|
156
|
+
result = subprocess.run( # noqa: S603 - validated argv; shell is disabled
|
|
157
|
+
command, check=False, capture_output=True, text=True, timeout=1800
|
|
158
|
+
)
|
|
159
|
+
except subprocess.TimeoutExpired as error:
|
|
160
|
+
raise ArtifactError("FFmpeg assembly timed out") from error
|
|
161
|
+
except OSError as error:
|
|
162
|
+
raise ArtifactError(f"Cannot start FFmpeg assembly: {error}") from error
|
|
163
|
+
if result.returncode:
|
|
164
|
+
raise ArtifactError(f"FFmpeg assembly failed: {result.stderr[-2048:]}")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _write_chapter_metadata(
|
|
168
|
+
destination: Path,
|
|
169
|
+
chapters: tuple[Path, ...],
|
|
170
|
+
*,
|
|
171
|
+
title: str,
|
|
172
|
+
author: str | None,
|
|
173
|
+
chapter_titles: tuple[str, ...] | None,
|
|
174
|
+
) -> None:
|
|
175
|
+
lines = [";FFMETADATA1", f"title={_escape_metadata(title)}"]
|
|
176
|
+
if author:
|
|
177
|
+
lines.append(f"artist={_escape_metadata(author)}")
|
|
178
|
+
start = 0
|
|
179
|
+
for index, chapter in enumerate(chapters):
|
|
180
|
+
inspection = inspect_audio(chapter)
|
|
181
|
+
if not inspection.valid:
|
|
182
|
+
raise ArtifactError(
|
|
183
|
+
f"Cannot assemble invalid chapter {chapter}: "
|
|
184
|
+
+ "; ".join(inspection.issues)
|
|
185
|
+
)
|
|
186
|
+
duration = max(1, round(inspection.duration_seconds * 1_000))
|
|
187
|
+
end = start + duration
|
|
188
|
+
chapter_title = chapter_titles[index] if chapter_titles else chapter.stem
|
|
189
|
+
lines.extend(
|
|
190
|
+
[
|
|
191
|
+
"[CHAPTER]",
|
|
192
|
+
"TIMEBASE=1/1000",
|
|
193
|
+
f"START={start}",
|
|
194
|
+
f"END={end}",
|
|
195
|
+
f"title={_escape_metadata(chapter_title)}",
|
|
196
|
+
]
|
|
197
|
+
)
|
|
198
|
+
start = end
|
|
199
|
+
destination.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _escape_metadata(value: str) -> str:
|
|
203
|
+
return (
|
|
204
|
+
value.replace("\\", "\\\\")
|
|
205
|
+
.replace("=", "\\=")
|
|
206
|
+
.replace(";", "\\;")
|
|
207
|
+
.replace("#", "\\#")
|
|
208
|
+
.replace("\n", " ")
|
|
209
|
+
)
|