epub2m4b 0.1.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.
- epub2m4b-0.1.0.dist-info/METADATA +118 -0
- epub2m4b-0.1.0.dist-info/RECORD +40 -0
- epub2m4b-0.1.0.dist-info/WHEEL +5 -0
- epub2m4b-0.1.0.dist-info/entry_points.txt +2 -0
- epub2m4b-0.1.0.dist-info/licenses/LICENSE +202 -0
- epub2m4b-0.1.0.dist-info/top_level.txt +1 -0
- soundbook/__init__.py +11 -0
- soundbook/__main__.py +6 -0
- soundbook/assemble/__init__.py +1 -0
- soundbook/assemble/concat.py +117 -0
- soundbook/assemble/loudnorm.py +80 -0
- soundbook/assemble/m4b.py +195 -0
- soundbook/assemble/silence.py +29 -0
- soundbook/cli.py +495 -0
- soundbook/config.py +237 -0
- soundbook/db.py +314 -0
- soundbook/ingest/__init__.py +1 -0
- soundbook/ingest/anchors.py +100 -0
- soundbook/ingest/chaptering.py +352 -0
- soundbook/ingest/classify.py +42 -0
- soundbook/ingest/clean.py +136 -0
- soundbook/ingest/loader.py +229 -0
- soundbook/ingest/metrics.py +48 -0
- soundbook/models.py +118 -0
- soundbook/pipeline.py +335 -0
- soundbook/py.typed +0 -0
- soundbook/segment/__init__.py +1 -0
- soundbook/segment/segmenter.py +147 -0
- soundbook/tts/__init__.py +1 -0
- soundbook/tts/base.py +48 -0
- soundbook/tts/fake.py +38 -0
- soundbook/tts/kokoro_local.py +62 -0
- soundbook/tts/openai_compat.py +65 -0
- soundbook/tts/voices.py +95 -0
- soundbook/util/__init__.py +1 -0
- soundbook/util/atomic.py +35 -0
- soundbook/util/audio.py +117 -0
- soundbook/util/disk.py +40 -0
- soundbook/util/hashing.py +22 -0
- soundbook/util/process.py +51 -0
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: epub2m4b
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Chinese EPUB → chaptered M4B audiobook generator (CLI)
|
|
5
|
+
Author: soundbook authors
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Keywords: epub,m4b,audiobook,tts,chinese
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Dist: epub-extended==0.2.3
|
|
12
|
+
Requires-Dist: lxml>=5
|
|
13
|
+
Requires-Dist: click>=8
|
|
14
|
+
Requires-Dist: filelock>=3
|
|
15
|
+
Provides-Extra: kokoro
|
|
16
|
+
Requires-Dist: kokoro==0.9.4; extra == "kokoro"
|
|
17
|
+
Requires-Dist: misaki[zh]==0.9.4; extra == "kokoro"
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: pytest; extra == "dev"
|
|
20
|
+
Requires-Dist: soundfile; extra == "dev"
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# epub2m4b
|
|
24
|
+
|
|
25
|
+
[](https://github.com/whoamiWo/book2sound/actions/workflows/ci.yml)
|
|
26
|
+
|
|
27
|
+
Chinese EPUB → chaptered **M4B** audiobook, as a single resumable CLI.
|
|
28
|
+
|
|
29
|
+
- **Chaptering**: nav → nav+hybrid → outline → spine, with a vetoer that rejects implausible cuts and records *why* (see `epub2m4b inspect --json`).
|
|
30
|
+
- **Resumable**: every segment is cached by `sha256(text + synth_fingerprint)`. Interrupt with Ctrl-C / SIGKILL and rerun — finished segments are never redone.
|
|
31
|
+
- **Switch voices for free**: switching back to a previous voice costs zero synthesis.
|
|
32
|
+
- **Chapter-accurate timeline**: START/END computed from integer sample counts, verified against ffprobe within 150 ms.
|
|
33
|
+
- **Graceful degradation**: DRM/image-only books exit 3; silent loudnorm measurement degrades to "loudnorm off + warning"; per-segment failures exit 2 with `--allow-incomplete` packaging what finished.
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
python3 -m pip install epub2m4b # core (fake + openai_compat TTS)
|
|
39
|
+
python3 -m pip install 'epub2m4b[kokoro]' # + local Kokoro 0.9.4 engine
|
|
40
|
+
ffmpeg -version # ffmpeg + ffprobe are required
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Use
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
epub2m4b doctor # check environment (never touches the DB)
|
|
47
|
+
epub2m4b inspect book.epub # show chaptering strategy and segment counts
|
|
48
|
+
epub2m4b inspect book.epub --json # machine-readable version
|
|
49
|
+
epub2m4b voices # list Kokoro voices (no model download)
|
|
50
|
+
epub2m4b voices --lang z # only Mandarin voices
|
|
51
|
+
epub2m4b run book.epub --tts kokoro --voice zf_xiaobei -o book.m4b
|
|
52
|
+
epub2m4b status # library overview
|
|
53
|
+
epub2m4b status book.epub # one book, including failed segments
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Options on `run`: `--voice`, `--rate`, `--jobs`, `--max-retries`, `--endpoint` (for `openai_compat`), `--bitrate`, `--no-loudnorm`, `--no-speak-titles`, `--include-front-matter`, `--allow-incomplete`.
|
|
57
|
+
|
|
58
|
+
Exit codes: **0** success · **1** general error · **2** failed/incomplete segments · **3** unusable input · **4** TTS unavailable · **5** insufficient disk · **130** interrupted.
|
|
59
|
+
|
|
60
|
+
## State
|
|
61
|
+
|
|
62
|
+
- `SOUNDBOOK_HOME` (default `~/.local/share/soundbook`): `state.sqlite`, `locks/`, `work/`.
|
|
63
|
+
- `SOUNDBOOK_CACHE_DIR` (default `~/.cache/soundbook/audio`): per-segment FLAC files, content-addressed.
|
|
64
|
+
|
|
65
|
+
## TTS backends
|
|
66
|
+
|
|
67
|
+
| `--tts` | what it does |
|
|
68
|
+
| --- | --- |
|
|
69
|
+
| `fake` | Deterministic silence, for tests/CI (loudnorm auto-disabled) |
|
|
70
|
+
| `kokoro` | Local Kokoro 82M, default voice `zf_xiaobei`, `lang_code` inferred from the voice id (`SOUNDBOOK_KOKORO_VOICE`, `SOUNDBOOK_KOKORO_LANG` override) |
|
|
71
|
+
| `openai_compat` | Any OpenAI-compatible `/v1/audio/speech` endpoint (CosyVoice, …). Env: `SOUNDBOOK_TTS_URL`, `SOUNDBOOK_TTS_MODEL`, `SOUNDBOOK_TTS_VOICE` |
|
|
72
|
+
|
|
73
|
+
A failed segment is retried on the next `run` — failure is not sticky.
|
|
74
|
+
|
|
75
|
+
Kokoro notes: `kokoro==0.9.4` requires **Python < 3.13** (use the Docker image, which is
|
|
76
|
+
3.12, if your system Python is newer). Model weights come from Hugging Face on first
|
|
77
|
+
run; behind a firewall set `HF_ENDPOINT=https://hf-mirror.com` and
|
|
78
|
+
`HF_HUB_DISABLE_XET=1` (the Xet CDN is not served by the mirror).
|
|
79
|
+
|
|
80
|
+
## Docker
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
docker build -t epub2m4b .
|
|
84
|
+
docker run --rm -v "$PWD:/data" epub2m4b inspect book.epub
|
|
85
|
+
docker run --rm -v "$PWD:/data" epub2m4b run book.epub --tts fake -o book.m4b
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
The default image ships the core backends only. For the local Kokoro engine use `Dockerfile.kokoro` (Python 3.12, installs `.[kokoro]`; reconstructed recipe, see the comments at its top):
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
docker build -f Dockerfile.kokoro -t epub2m4b-kokoro .
|
|
92
|
+
docker run --rm -v "$PWD:/data" -e HF_ENDPOINT=https://hf-mirror.com -e HF_HUB_DISABLE_XET=1 \
|
|
93
|
+
epub2m4b-kokoro run book.epub --tts kokoro -o book.m4b
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
The `HF_*` variables are only needed behind a firewall. The Kokoro image is large (about 10.5 GB with torch).
|
|
97
|
+
|
|
98
|
+
Two practical notes:
|
|
99
|
+
|
|
100
|
+
- If `pypi.org` is unreachable from your Docker network, pass a mirror:
|
|
101
|
+
`docker build -t epub2m4b --build-arg PIP_INDEX_URL=https://mirrors.aliyun.com/pypi/simple .`
|
|
102
|
+
- The container runs as root, so files it writes into a bind-mounted `/data` (the M4B, the cache, the SQLite state) are root-owned on the host. Use a named volume, or `--user "$(id -u):$(id -g)"` together with `-e SOUNDBOOK_HOME=/tmp/state -e SOUNDBOOK_CACHE_DIR=/tmp/cache`.
|
|
103
|
+
|
|
104
|
+
## Development
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
python3 -m venv .venv && . .venv/bin/activate
|
|
108
|
+
python3 -m pip install -e ".[dev]"
|
|
109
|
+
pytest # unit + e2e (real ffmpeg, --tts fake)
|
|
110
|
+
pytest -m e2e # only end-to-end
|
|
111
|
+
pytest -m corpus # local real-book corpus (never in CI)
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Docs: [`docs/adr.md`](docs/adr.md) (decision records), [`docs/limitations.md`](docs/limitations.md), [`docs/benchmarks.md`](docs/benchmarks.md), [`docs/compare.md`](docs/compare.md), [`docs/licenses.md`](docs/licenses.md).
|
|
115
|
+
|
|
116
|
+
## Legal
|
|
117
|
+
|
|
118
|
+
Apache-2.0. No text, model weights or corpora are redistributed with this project. You are responsible for the legality of the EPUBs you convert.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
epub2m4b-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
2
|
+
soundbook/__init__.py,sha256=A1F018kGvxttqJckXCCtlFMdoW-CnyznTDNLMAxVsqY,301
|
|
3
|
+
soundbook/__main__.py,sha256=z2Pnt3062NHw86Cy_xryK5IXsG7v5PhV1Zt2Uk7ZWFI,134
|
|
4
|
+
soundbook/cli.py,sha256=eLw_qKA9tP4VDww2gWK5A3aUCYQPpOivWqW1YJo3s64,19386
|
|
5
|
+
soundbook/config.py,sha256=Tv3yqXxcWCyeUaBzQ_TdztcO0EXS_x0aM7Y_B311VDk,6697
|
|
6
|
+
soundbook/db.py,sha256=nWM--m8JKZmFC_mPQ32cLElZTWvur3v3QtUqar91pMU,11965
|
|
7
|
+
soundbook/models.py,sha256=YRPjaaHQieTp5pED5hPLCXFU1SylvGGSpAu0Pt6sFpk,2544
|
|
8
|
+
soundbook/pipeline.py,sha256=riU1aN1knkYFcXUpNVUk1bUa4Mplj963dSqj2WxezO4,12065
|
|
9
|
+
soundbook/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
10
|
+
soundbook/assemble/__init__.py,sha256=H9UzPXCcV-7ZetPIUWYZxsfe0eK_8zseaGDVi4jjG4g,24
|
|
11
|
+
soundbook/assemble/concat.py,sha256=insLlzpcAiZ4XY00Nu5iK0q9TDOU5pGU_XkffmcXiWU,4158
|
|
12
|
+
soundbook/assemble/loudnorm.py,sha256=fjb5SP8smB4vheWrbZF3ulRLKKsL4RyzYuhX7jkxcNk,2791
|
|
13
|
+
soundbook/assemble/m4b.py,sha256=FFRn-qj1JeSN8uRXPFJLDELAIST99eWahZsBXKONlC8,6413
|
|
14
|
+
soundbook/assemble/silence.py,sha256=xWkkTAEEZ8fNqoqa2DobW5QD4S0eA88oquMKoPzouK0,960
|
|
15
|
+
soundbook/ingest/__init__.py,sha256=ckWUPXcYI0WTp0wHyx-1XP9zwhOoZA4_DzalzCrjDn8,22
|
|
16
|
+
soundbook/ingest/anchors.py,sha256=CgWa4gsxGzJau9Rs-guUKsx7CLVCHlmAGL6DDaEPV_s,3188
|
|
17
|
+
soundbook/ingest/chaptering.py,sha256=NqHgrNnPa1d9CrNKqx2JNLc8ynex-2Cm2qQMUFMszFo,13278
|
|
18
|
+
soundbook/ingest/classify.py,sha256=KRebXwaZZw6ekme9ZFGVrm1hoYsOhk5tHRntl5wZwcY,1565
|
|
19
|
+
soundbook/ingest/clean.py,sha256=YF1srhGTwlTrNQQaLLpvIXbYduEtrZ0_8yetKY0gv8Y,4793
|
|
20
|
+
soundbook/ingest/loader.py,sha256=pooFb7vs1OOX7WeWwWNOfFeULQloG38m4s9P7njilZk,7352
|
|
21
|
+
soundbook/ingest/metrics.py,sha256=KvXQFpQZ_n71ZxLana17vb9HnhKY3YqxhFL3m8zydvw,1702
|
|
22
|
+
soundbook/segment/__init__.py,sha256=5rmdSdgKssbDYr_F_Oz7b6HRa-Yy7Hgs7CE8T6XqzwM,23
|
|
23
|
+
soundbook/segment/segmenter.py,sha256=9iHxiOuvmqvKAedgfC6O7vJpTV4fUgrORFhU_y1yZG8,4388
|
|
24
|
+
soundbook/tts/__init__.py,sha256=v_C1a_CM6c0MsFn7OT9KzaiThcLHyM54SRQNLfhKqao,19
|
|
25
|
+
soundbook/tts/base.py,sha256=vr2Md9-pmIQm9Bf7xzza7XRstrZZfb1UL478SAyeGmc,1492
|
|
26
|
+
soundbook/tts/fake.py,sha256=6uIGMx0xqO_zH6dwiLftprCOPYwx8iwO5t5MMYHSnn4,1178
|
|
27
|
+
soundbook/tts/kokoro_local.py,sha256=P6ehagWg7UYZUGkiAmudI7AZYKWOsNBTySEKO5H-5GE,2306
|
|
28
|
+
soundbook/tts/openai_compat.py,sha256=gucSb6OdA8TolU8ZNlrc9lf_WKWbAF7p14HufJdchZs,2244
|
|
29
|
+
soundbook/tts/voices.py,sha256=xLX2X1jJO-yKBnAIGcDMv4r0lUA39loMbEFzf5N-g6Q,2947
|
|
30
|
+
soundbook/util/__init__.py,sha256=aDXPjrCBY-qvaZulwuKmCzi3-HbNkjs9D7eUNHOS5H8,20
|
|
31
|
+
soundbook/util/atomic.py,sha256=y61rRrmyUGjfSAUyOKbn3zsHNFWKmF2OqQnXha73A3g,980
|
|
32
|
+
soundbook/util/audio.py,sha256=W1W7RW3w_QzbxhmyxpNCBuWcbzGvw-FbaGsCZZlLu38,4015
|
|
33
|
+
soundbook/util/disk.py,sha256=tCwf1JEyQ0D7ohYRGFrirRIRIn_J0dv5jtr9VGSf1lM,1177
|
|
34
|
+
soundbook/util/hashing.py,sha256=6F2qk6EE4_pWCRL-yqJ_egfBNXkyhXkPgMttFz0AoQ0,558
|
|
35
|
+
soundbook/util/process.py,sha256=geFmXXvlv1D_4DP88G7j4S2tnmh-pTIUVDbZ6JPcSqU,1436
|
|
36
|
+
epub2m4b-0.1.0.dist-info/METADATA,sha256=CPYF_306sRLyNvwYNhjxdv71CzeXWygKWqmkI4AU64c,5714
|
|
37
|
+
epub2m4b-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
38
|
+
epub2m4b-0.1.0.dist-info/entry_points.txt,sha256=gyjL6SNhydIm_PpYG5Ce4X7VUrDamTLYGF1af4DrS60,48
|
|
39
|
+
epub2m4b-0.1.0.dist-info/top_level.txt,sha256=9PJm00V_vlGPkbt4ZCCGqsNzuQHDrOY4JzUjU9QNOZU,10
|
|
40
|
+
epub2m4b-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
soundbook
|
soundbook/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Version and public identity of the package."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
#: Bumped whenever parsing/cleaning/segmentation semantics change.
|
|
6
|
+
PIPELINE_VERSION = "0.1.0"
|
|
7
|
+
|
|
8
|
+
#: Bumped when the on-disk segment audio format changes (invalidates audio_key).
|
|
9
|
+
AUDIO_FORMAT_VERSION = "1"
|
|
10
|
+
|
|
11
|
+
DIST_NAME = "epub2m4b"
|
soundbook/__main__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""assemble package."""
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Timeline, concat list and ffmetadata (spec §10, ADR-017).
|
|
2
|
+
|
|
3
|
+
Timestamps are integer sample counts accumulated in order; milliseconds are
|
|
4
|
+
produced once, at the end, by ``round(1000 * total / sample_rate)``. The
|
|
5
|
+
1200 ms pause that precedes a title belongs to the *previous* chapter: it is
|
|
6
|
+
the trailing silence after that chapter's last body segment, so chapter
|
|
7
|
+
``START`` is the first sample of the title audio (or of the first body segment
|
|
8
|
+
when titles are not spoken).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import sqlite3
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
|
|
16
|
+
from soundbook.assemble.silence import ensure_silence
|
|
17
|
+
from soundbook.models import ChapterSpan, TimelineEntry
|
|
18
|
+
|
|
19
|
+
SAMPLE_RATE = 24_000
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class Timeline:
|
|
24
|
+
entries: list[TimelineEntry]
|
|
25
|
+
spans: list[ChapterSpan]
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def total_samples(self) -> int:
|
|
29
|
+
return sum(e.n_samples for e in self.entries)
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def total_ms(self) -> int:
|
|
33
|
+
return int(round(1000 * self.total_samples / SAMPLE_RATE))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def build_timeline(db: sqlite3.Connection, book_id: str, work_dir: str,
|
|
37
|
+
*, sample_rate: int = SAMPLE_RATE) -> Timeline:
|
|
38
|
+
rows = db.execute(
|
|
39
|
+
"""
|
|
40
|
+
SELECT s.*, c.title AS chapter_title
|
|
41
|
+
FROM segments s JOIN chapters c
|
|
42
|
+
ON c.book_id = s.book_id AND c.chapter_idx = s.chapter_idx
|
|
43
|
+
WHERE s.book_id=? AND s.status='done'
|
|
44
|
+
ORDER BY s.chapter_idx, s.seg_idx
|
|
45
|
+
""",
|
|
46
|
+
(book_id,),
|
|
47
|
+
).fetchall()
|
|
48
|
+
|
|
49
|
+
silences: dict[int, tuple[str, int]] = {}
|
|
50
|
+
|
|
51
|
+
def silence(ms: int) -> tuple[str, int]:
|
|
52
|
+
if ms not in silences:
|
|
53
|
+
path, n = ensure_silence(work_dir, ms, sample_rate=sample_rate)
|
|
54
|
+
silences[ms] = (str(path), n)
|
|
55
|
+
return silences[ms]
|
|
56
|
+
|
|
57
|
+
entries: list[TimelineEntry] = []
|
|
58
|
+
spans: list[ChapterSpan] = []
|
|
59
|
+
cum = 0
|
|
60
|
+
current: int | None = None
|
|
61
|
+
current_title = ""
|
|
62
|
+
span_start = 0
|
|
63
|
+
|
|
64
|
+
for row in rows:
|
|
65
|
+
if row["chapter_idx"] != current:
|
|
66
|
+
if current is not None:
|
|
67
|
+
spans.append(ChapterSpan(chapter_idx=current, title=current_title,
|
|
68
|
+
start_ms=_ms(span_start), end_ms=_ms(cum)))
|
|
69
|
+
current = row["chapter_idx"]
|
|
70
|
+
current_title = row["chapter_title"] or ""
|
|
71
|
+
span_start = cum
|
|
72
|
+
entries.append(TimelineEntry(path=row["audio_path"], n_samples=row["n_samples"],
|
|
73
|
+
kind="title" if row["seg_idx"] == -1 else "body",
|
|
74
|
+
chapter_idx=current))
|
|
75
|
+
cum += int(row["n_samples"])
|
|
76
|
+
sil_path, sil_n = silence(int(row["pause_after_ms"] or 0))
|
|
77
|
+
if sil_n > 0:
|
|
78
|
+
entries.append(TimelineEntry(path=sil_path, n_samples=sil_n, kind="silence",
|
|
79
|
+
chapter_idx=current))
|
|
80
|
+
cum += sil_n
|
|
81
|
+
if current is not None:
|
|
82
|
+
spans.append(ChapterSpan(chapter_idx=current, title=current_title,
|
|
83
|
+
start_ms=_ms(span_start), end_ms=_ms(cum)))
|
|
84
|
+
return Timeline(entries=entries, spans=spans)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _ms(samples: int) -> int:
|
|
88
|
+
return int(round(1000 * samples / SAMPLE_RATE))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def build_concat_list(entries: list[TimelineEntry]) -> str:
|
|
92
|
+
"""Only ``file`` lines, absolute paths, single quotes doubled."""
|
|
93
|
+
|
|
94
|
+
lines: list[str] = []
|
|
95
|
+
for entry in entries:
|
|
96
|
+
escaped = entry.path.replace("'", "'\\''")
|
|
97
|
+
lines.append(f"file '{escaped}'")
|
|
98
|
+
return "\n".join(lines) + "\n"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def build_ffmeta(spans: list[ChapterSpan], *, title: str, artist: str = "epub2m4b",
|
|
102
|
+
language: str = "zho") -> str:
|
|
103
|
+
def esc(value: str) -> str:
|
|
104
|
+
return (value.replace("\\", "\\\\").replace("\n", "\\n")
|
|
105
|
+
.replace("=", "\\=").replace(";", "\\;").replace("#", "\\#"))
|
|
106
|
+
|
|
107
|
+
lines = [";FFMETADATA1", f"title={esc(title)}", f"artist={esc(artist)}",
|
|
108
|
+
f"album={esc(title)}", f"language={language}"]
|
|
109
|
+
for span in spans:
|
|
110
|
+
lines += [
|
|
111
|
+
"[CHAPTER]",
|
|
112
|
+
"TIMEBASE=1/1000",
|
|
113
|
+
f"START={span.start_ms}",
|
|
114
|
+
f"END={span.end_ms}",
|
|
115
|
+
f"title={esc(span.title)}",
|
|
116
|
+
]
|
|
117
|
+
return "\n".join(lines) + "\n"
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Two-pass loudnorm, with the silence guard from plan §3.1.
|
|
2
|
+
|
|
3
|
+
Pass 1 prints a JSON measurement on stderr; pass 2 applies it linearly. When
|
|
4
|
+
the measurement is unusable (silence, ``LRA=0``, non-finite values) loudnorm is
|
|
5
|
+
skipped and the caller records a warning — CI always walks this path because
|
|
6
|
+
``--tts fake`` produces silence by construction.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from soundbook.config import AudioPolicy
|
|
16
|
+
from soundbook.util.process import CommandError, run
|
|
17
|
+
|
|
18
|
+
_KEYS = ("input_i", "input_tp", "input_lra", "input_thresh", "target_offset")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def build_measure_argv(concat_list: str | Path, audio: AudioPolicy) -> list[str]:
|
|
22
|
+
return [
|
|
23
|
+
"ffmpeg", "-hide_banner", "-nostats", "-y",
|
|
24
|
+
"-f", "concat", "-safe", "0", "-i", str(concat_list),
|
|
25
|
+
"-af", (f"loudnorm=I={audio.loudnorm_i}:TP={audio.loudnorm_tp}"
|
|
26
|
+
f":LRA={audio.loudnorm_lra}:print_format=json"),
|
|
27
|
+
"-f", "null", "-",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def parse_measurement(stderr: str) -> dict[str, float] | None:
|
|
32
|
+
"""Extract the last JSON object ffmpeg printed; None if there is none."""
|
|
33
|
+
|
|
34
|
+
start = stderr.rfind("{")
|
|
35
|
+
end = stderr.rfind("}")
|
|
36
|
+
if start < 0 or end <= start:
|
|
37
|
+
return None
|
|
38
|
+
try:
|
|
39
|
+
raw = json.loads(stderr[start:end + 1])
|
|
40
|
+
except json.JSONDecodeError:
|
|
41
|
+
return None
|
|
42
|
+
result: dict[str, float] = {}
|
|
43
|
+
for key in _KEYS:
|
|
44
|
+
try:
|
|
45
|
+
result[key] = float(raw[key])
|
|
46
|
+
except (KeyError, TypeError, ValueError):
|
|
47
|
+
return None
|
|
48
|
+
return result
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def validate_measurement(params: dict[str, float] | None) -> tuple[bool, str]:
|
|
52
|
+
if params is None:
|
|
53
|
+
return False, "loudnorm measurement missing"
|
|
54
|
+
if params["input_lra"] <= 0:
|
|
55
|
+
return False, "loudnorm measurement is silent (LRA=0)"
|
|
56
|
+
for key in _KEYS:
|
|
57
|
+
if not math.isfinite(params[key]):
|
|
58
|
+
return False, f"loudnorm measurement not finite ({key})"
|
|
59
|
+
return True, ""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def measure(concat_list: str | Path, audio: AudioPolicy) -> dict[str, float] | None:
|
|
63
|
+
try:
|
|
64
|
+
result = run(build_measure_argv(concat_list, audio), check=False)
|
|
65
|
+
except OSError:
|
|
66
|
+
return None
|
|
67
|
+
if result.returncode != 0:
|
|
68
|
+
return None
|
|
69
|
+
return parse_measurement(result.stderr_text)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def loudnorm_filter(params: dict[str, float], audio: AudioPolicy,
|
|
73
|
+
*, out_sample_rate: int = 24_000) -> str:
|
|
74
|
+
return (
|
|
75
|
+
f"loudnorm=I={audio.loudnorm_i}:TP={audio.loudnorm_tp}:LRA={audio.loudnorm_lra}"
|
|
76
|
+
f":measured_I={params['input_i']}:measured_LRA={params['input_lra']}"
|
|
77
|
+
f":measured_TP={params['input_tp']}:measured_thresh={params['input_thresh']}"
|
|
78
|
+
f":offset={params['target_offset']}:linear=true,"
|
|
79
|
+
f"aresample={out_sample_rate}:first_pts=0"
|
|
80
|
+
)
|