readalign 1.2.0__tar.gz → 1.3.1__tar.gz

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.
Files changed (40) hide show
  1. {readalign-1.2.0 → readalign-1.3.1}/CHANGELOG.md +32 -0
  2. {readalign-1.2.0 → readalign-1.3.1}/PKG-INFO +89 -11
  3. {readalign-1.2.0 → readalign-1.3.1}/README.md +88 -10
  4. {readalign-1.2.0 → readalign-1.3.1}/pyproject.toml +1 -1
  5. {readalign-1.2.0 → readalign-1.3.1}/src/readalign/__init__.py +1 -1
  6. {readalign-1.2.0 → readalign-1.3.1}/src/readalign/audio.py +14 -6
  7. {readalign-1.2.0 → readalign-1.3.1}/src/readalign/cli.py +48 -11
  8. {readalign-1.2.0 → readalign-1.3.1}/src/readalign/fs.py +10 -0
  9. {readalign-1.2.0 → readalign-1.3.1}/src/readalign/members.py +13 -4
  10. {readalign-1.2.0 → readalign-1.3.1}/src/readalign/package.py +16 -4
  11. {readalign-1.2.0 → readalign-1.3.1}/src/readalign/sidecar.py +14 -1
  12. readalign-1.3.1/src/readalign/smil.py +135 -0
  13. readalign-1.3.1/tests/test_audio.py +145 -0
  14. {readalign-1.2.0 → readalign-1.3.1}/tests/test_cli.py +105 -0
  15. {readalign-1.2.0 → readalign-1.3.1}/tests/test_fs.py +9 -1
  16. {readalign-1.2.0 → readalign-1.3.1}/tests/test_output.py +165 -2
  17. {readalign-1.2.0 → readalign-1.3.1}/tests/test_sidecar_report.py +25 -0
  18. readalign-1.3.1/tests/test_smil.py +147 -0
  19. readalign-1.2.0/src/readalign/smil.py +0 -78
  20. readalign-1.2.0/tests/test_audio.py +0 -77
  21. {readalign-1.2.0 → readalign-1.3.1}/.gitignore +0 -0
  22. {readalign-1.2.0 → readalign-1.3.1}/LICENSE +0 -0
  23. {readalign-1.2.0 → readalign-1.3.1}/scripts/fetch_samples.py +0 -0
  24. {readalign-1.2.0 → readalign-1.3.1}/src/readalign/__main__.py +0 -0
  25. {readalign-1.2.0 → readalign-1.3.1}/src/readalign/align.py +0 -0
  26. {readalign-1.2.0 → readalign-1.3.1}/src/readalign/asr.py +0 -0
  27. {readalign-1.2.0 → readalign-1.3.1}/src/readalign/clock.py +0 -0
  28. {readalign-1.2.0 → readalign-1.3.1}/src/readalign/epub.py +0 -0
  29. {readalign-1.2.0 → readalign-1.3.1}/src/readalign/errors.py +0 -0
  30. {readalign-1.2.0 → readalign-1.3.1}/src/readalign/refine.py +0 -0
  31. {readalign-1.2.0 → readalign-1.3.1}/src/readalign/report.py +0 -0
  32. {readalign-1.2.0 → readalign-1.3.1}/src/readalign/sentences.py +0 -0
  33. {readalign-1.2.0 → readalign-1.3.1}/src/readalign/textnorm.py +0 -0
  34. {readalign-1.2.0 → readalign-1.3.1}/src/readalign/verify.py +0 -0
  35. {readalign-1.2.0 → readalign-1.3.1}/tests/conftest.py +0 -0
  36. {readalign-1.2.0 → readalign-1.3.1}/tests/test_align.py +0 -0
  37. {readalign-1.2.0 → readalign-1.3.1}/tests/test_asr.py +0 -0
  38. {readalign-1.2.0 → readalign-1.3.1}/tests/test_epub.py +0 -0
  39. {readalign-1.2.0 → readalign-1.3.1}/tests/test_text.py +0 -0
  40. {readalign-1.2.0 → readalign-1.3.1}/tests/test_verify.py +0 -0
@@ -1,5 +1,37 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.3.1 - 2026-10-25
4
+
5
+ - Fixed: SMIL playback no longer skips audio between consecutive aligned sentences, including
6
+ chapter boundaries and gaps spanning audio files. Gaps play with the preceding sentence's
7
+ highlight; file-local clip bounds and overlay duration metadata include the recovered audio.
8
+ Alignment reports and WebVTT timestamps remain unchanged. Audio outside the first-to-last
9
+ aligned range stays excluded to preserve excerpt behavior. Regenerate existing EPUBs to apply.
10
+ - Fixed: overlapping sentence timings no longer replay audio. Millisecond-collapsed clips are
11
+ omitted and duration metadata uses the exact serialized file-local clocks. Invalid, nonfinite
12
+ or backward timing data and inconsistent track timelines fail with readable input errors.
13
+ - Enhanced: `check` warns about forward gaps and backward jumps across clips and chapter
14
+ boundaries without rejecting intentional third-party discontinuities. It counts unique text
15
+ targets separately from audio clips, so splitting a sentence across files does not inflate
16
+ the reported sentence count.
17
+
18
+ ## 1.3.0 - 2026-10-25
19
+
20
+ - Fixed: work-directory audio/WAV paths cannot overwrite the input ebook, output EPUB or
21
+ report. Inputs must stay outside the generated sidecar directory when sidecars are enabled.
22
+ - Fixed: chapter-derived subtitle names cannot escape the sidecar directory through Windows
23
+ separators or use reserved device names. Sanitized names still receive collision handling.
24
+ - Added a real surround-AAC to stereo-MP3 regression checking retained chapter marks and
25
+ unchanged source bytes.
26
+ - New: `--audio-format mp3` stream-copies existing MP3 sources and transcodes other codecs
27
+ to MP3 for readers with AAC/Opus decoder limitations. The default `auto` retains the existing
28
+ behavior. Timing uses the prepared audio and the report records the selected format.
29
+ - Fixed: streamed audiobook entries now declare their size before ZIP writing so large files
30
+ select ZIP64 headers instead of failing at the end of the write. Small entries retain their
31
+ existing archive format.
32
+ - Added long-book packaging regressions and evidence-linked reader guidance distinguishing
33
+ codec support, large-track loading, sentence highlighting and narration-position restoration.
34
+
3
35
  ## 1.2.0 - 2026-10-22
4
36
 
5
37
  - New: `--report PATH` selects a separate JSON report for each batch build, with guards
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: readalign
3
- Version: 1.2.0
3
+ Version: 1.3.1
4
4
  Summary: Turn an audiobook and the matching ebook you own into one EPUB 3 with Media Overlays.
5
5
  Project-URL: Homepage, https://github.com/Booyaka101/readalign
6
6
  Project-URL: Repository, https://github.com/Booyaka101/readalign
@@ -263,6 +263,7 @@ take precedence over this gate when more than one check fails.
263
263
  --beam-size N whisper beam size (default: 5)
264
264
  --no-vad disable the voice-activity filter
265
265
  --audio-bitrate RATE bitrate when audio has to be transcoded (default: 96k)
266
+ --audio-format auto|mp3 preserve supported codecs (default: auto), or use MP3 for compatibility
266
267
  --verify [JAR] validate the result with epubcheck after writing it (needs Java);
267
268
  pass its jar path, or leave the value off to search PATH,
268
269
  EPUBCHECK_HOME and JAVA_HOME for one
@@ -276,6 +277,29 @@ Multiple files are ordered by natural sort, so `part2.mp3` comes before `part10.
276
277
  file covering the whole book is fine, and so is a chapter split over several files; readalign
277
278
  works from a continuous timeline and does not assume one file per chapter.
278
279
 
280
+ For a reader that cannot decode AAC or Opus, select MP3 output:
281
+
282
+ The `--audio-format` option requires readalign 1.3.0 or later.
283
+
284
+ ```
285
+ readalign build --audio book.m4b --epub book.epub --out read-along.epub --audio-format mp3
286
+ ```
287
+
288
+ Existing MP3 sources are stream-copied. Other codecs are re-encoded with ffmpeg's `libmp3lame`
289
+ encoder at `--audio-bitrate` (default 96k). Re-encoding takes time and can reduce quality; it
290
+ does not change your source files. Timings are measured against the prepared MP3, not the
291
+ original AAC/Opus track. Changing the prepared audio also changes the transcript cache key,
292
+ so the first build in this mode may need to transcribe again. The report records the requested
293
+ `audio_format` and which source files were transcoded. This option does not fix reader resume
294
+ bugs or split a long track into chapters.
295
+
296
+ Use a dedicated `--work-dir`: its `audio/partNNN.mp3`, `.m4a`, `.opus` and
297
+ `wav/partNNN.wav` paths are reserved for generated files. Builds refuse aliases of the input
298
+ ebook, source audio, output EPUB or report at those paths before preparing audio. The generated
299
+ `<output-name>-sidecars/` directory must also be separate from your inputs and report; previous
300
+ `align.json` and `.vtt` files there are replaced on a rerun. Chapter-derived VTT filenames are
301
+ sanitized for safe local paths, while `align.json` retains the original document hrefs.
302
+
279
303
  ### The optional refine pass
280
304
 
281
305
  `pip install 'readalign[refine]'` adds torch and torchaudio, and `--refine` then runs a CTC
@@ -297,20 +321,71 @@ it, and any run that uses it records the restriction in the report's warnings.
297
321
  reported as untimed. They will never reach full coverage.
298
322
  - Audio is embedded in the EPUB, so the file is as large as the audiobook. Frankenstein at 64 kbps
299
323
  is 205 MB. There is no streaming or external-audio option in this version.
300
- - The audio timeline is shared across files. A sentence never spans two audio files; if one would,
301
- it is clipped at the file boundary.
324
+ - Media overlays preserve all audio between the first aligned sentence's start and the last
325
+ aligned sentence's end. Gaps between sentence timings play under the preceding sentence's
326
+ highlight, including across chapters and audio files. A gap that crosses files gets separate
327
+ file-local clips; even an intervening file with no matched words is included. Audio outside
328
+ that aligned range remains excluded, so an ebook excerpt does not play unrelated opening or
329
+ closing narration. Regenerate existing EPUBs to apply this fix.
330
+ - The alignment report and WebVTT sidecars keep the original matched sentence times; only the
331
+ EPUB playback clips are extended. Overlay `media:duration` includes the recovered audio.
332
+ Overlapping sentence timings are joined at the next sentence's start instead of replaying
333
+ audio. SMIL uses millisecond precision: collapsed boundaries do not create empty clips, and
334
+ duration metadata sums the exact serialized file-local clips. Invalid or backward alignment
335
+ timestamps fail with an input error rather than silently dropping audio.
336
+ - `readalign check` warns about forward gaps and backward jumps between clips, including chapter
337
+ transitions in the same audio file. These are warnings, not failures, because third-party
338
+ books may intentionally omit or replay audio. It counts unique text targets as `sentences`
339
+ and reports `clips` separately; one text target can have several file-local playback clips.
302
340
  - Sentence splitting is tuned for English-style punctuation. Other languages align fine but may
303
341
  produce longer or shorter units than a native reader would choose.
304
342
 
305
343
  ## Reader support
306
344
 
307
- Media Overlays are part of EPUB 3, but support is uneven. Readium-based readers (Thorium Reader
308
- on desktop, Colibrio-based web readers) and Apple Books implement them. Kindle does not read EPUB
309
- overlays at all, and several popular mobile readers ignore the `media-overlay` attribute and just
310
- show the book. If a reader shows the text but plays no audio, it does not support overlays; the
311
- file is still a valid EPUB and still readable.
312
-
313
- readalign's output is validated against epubcheck 5.2.1, and `readalign check` is validated
345
+ Media Overlays are part of EPUB 3, but support is uneven. Text rendering, audio decoding,
346
+ sentence highlighting and saving the narration position are separate capabilities. A silent
347
+ book can mean an unsupported codec or a reader bug, not just missing overlay support.
348
+
349
+ ### Compatibility evidence (October 25, 2026)
350
+
351
+ This is a record of available evidence, **not a personally tested reader certification table**.
352
+ Reader fixes merged upstream may not yet be in the version you have installed.
353
+
354
+ | Reader / platform | Evidence and limits |
355
+ | --- | --- |
356
+ | Calibre and Thorium, reporter's PC | A [Readest reporter](https://github.com/readest/readest/issues/6989) says their large narrated EPUB plays in both. Versions and complete seek/reopen behavior were not recorded. |
357
+ | Readest, web and desktop | [#7004](https://github.com/readest/readest/pull/7004) fixes loading a large stored audio entry without copying it all into memory. Upstream tested a 921 MB shared MP3, including an eight-hour seek. This is upstream testing, not a readalign reader test. |
358
+ | Readest, Android and iOS | [#7010](https://github.com/readest/readest/pull/7010) and [#7019](https://github.com/readest/readest/pull/7019) extend direct audio access to native players. Upstream tests are described in those PRs; they do not establish playback of every readalign book. |
359
+ | Readest, Linux app | The maintainer [reports no AAC decoder](https://github.com/readest/readest/issues/6989#issuecomment-6357568308). Try `--audio-format mp3`; updating for large-track fixes alone does not resolve that codec limitation. |
360
+ | Episteme, Android | An [independent readalign-output user](https://github.com/Aryan-Raj3112/episteme/issues/579) reports narration restarting at the beginning of a long section after reopening. The same book highlights sentences correctly on PC. No readalign-side fix is established. |
361
+ | Apple Books and other readers | Overlay support alone is not proof of long-track seeking or saved narration position. These behaviors have not been verified here. |
362
+ | Kindle | EPUB Media Overlays are not supported. |
363
+
364
+ ### Long books and playback troubleshooting
365
+
366
+ 1. Run `readalign check read-along.epub` and, if available, epubcheck. A clean result checks
367
+ package structure and clip bounds, not whether a specific reader plays or resumes correctly.
368
+ 2. Check the reader version and audio codec. MP3 output is an option for AAC/Opus decoder
369
+ limitations; an EPUB can be valid while a reader cannot decode its narration.
370
+ 3. For large books, use a reader version containing its large-track fixes. readalign stores
371
+ prepared MP3/M4A/Opus entries without ZIP compression so readers can seek directly. A reader
372
+ may still extract or copy the whole track before playback. One overlay per content document
373
+ does not mean the audio is split into separate files. If you already own chapter-sized
374
+ narration files, pass their directory; they are naturally sorted.
375
+ 4. Test a later chapter, cross a chapter boundary, pause/resume, then close and reopen the book.
376
+ Saving the text position is not the same as saving the narration sentence and audio offset.
377
+ Re-encoding to MP3 is not a guaranteed workaround for narration-position loss.
378
+ 5. Compare the same EPUB in another overlay-capable reader. If only one reader fails, include
379
+ that comparison when reporting it rather than assuming the EPUB generation is defective.
380
+
381
+ When reporting a problem, include readalign's version, reader version, OS/device, audio format,
382
+ approximate track duration/size, the chapter and sentence where it happens, and whether it is
383
+ startup, seeking, highlighting or reopening that fails. Include the output of `readalign check`
384
+ and a short public-domain reproduction if possible. Reports and sidecars can contain local paths
385
+ and quoted book text: inspect them before sharing. Do not upload a copyrighted book or narration
386
+ unless you have permission.
387
+
388
+ readalign's sample output is validated against epubcheck 5.2.1, and `readalign check` is validated
314
389
  against the reference Media Overlays title from the EPUB test suite at
315
390
  <https://epubtest.org/test-books>.
316
391
 
@@ -338,9 +413,12 @@ python -m pytest tests -q
338
413
  python -m ruff check .
339
414
  ```
340
415
 
341
- The suite runs in about a second and needs neither a GPU nor network access; it builds its own
416
+ The suite needs neither a GPU nor network access; it builds its own
342
417
  EPUBs and synthesises word timings. A few cases need ffmpeg and skip without it, and one is
343
418
  skipped unless `READALIGN_MO_TESTBOOK` points at a copy of the epubtest.org Media Overlays book.
419
+ Long-book packaging tests cover shared 16-hour timelines, separate-track clock resets, stored
420
+ audio entries and ZIP64 selection using a lowered size threshold. Synthetic timings and a lowered
421
+ threshold do not substitute for a real multi-gigabyte book or reader playback test.
344
422
 
345
423
  ## Distribution
346
424
 
@@ -230,6 +230,7 @@ take precedence over this gate when more than one check fails.
230
230
  --beam-size N whisper beam size (default: 5)
231
231
  --no-vad disable the voice-activity filter
232
232
  --audio-bitrate RATE bitrate when audio has to be transcoded (default: 96k)
233
+ --audio-format auto|mp3 preserve supported codecs (default: auto), or use MP3 for compatibility
233
234
  --verify [JAR] validate the result with epubcheck after writing it (needs Java);
234
235
  pass its jar path, or leave the value off to search PATH,
235
236
  EPUBCHECK_HOME and JAVA_HOME for one
@@ -243,6 +244,29 @@ Multiple files are ordered by natural sort, so `part2.mp3` comes before `part10.
243
244
  file covering the whole book is fine, and so is a chapter split over several files; readalign
244
245
  works from a continuous timeline and does not assume one file per chapter.
245
246
 
247
+ For a reader that cannot decode AAC or Opus, select MP3 output:
248
+
249
+ The `--audio-format` option requires readalign 1.3.0 or later.
250
+
251
+ ```
252
+ readalign build --audio book.m4b --epub book.epub --out read-along.epub --audio-format mp3
253
+ ```
254
+
255
+ Existing MP3 sources are stream-copied. Other codecs are re-encoded with ffmpeg's `libmp3lame`
256
+ encoder at `--audio-bitrate` (default 96k). Re-encoding takes time and can reduce quality; it
257
+ does not change your source files. Timings are measured against the prepared MP3, not the
258
+ original AAC/Opus track. Changing the prepared audio also changes the transcript cache key,
259
+ so the first build in this mode may need to transcribe again. The report records the requested
260
+ `audio_format` and which source files were transcoded. This option does not fix reader resume
261
+ bugs or split a long track into chapters.
262
+
263
+ Use a dedicated `--work-dir`: its `audio/partNNN.mp3`, `.m4a`, `.opus` and
264
+ `wav/partNNN.wav` paths are reserved for generated files. Builds refuse aliases of the input
265
+ ebook, source audio, output EPUB or report at those paths before preparing audio. The generated
266
+ `<output-name>-sidecars/` directory must also be separate from your inputs and report; previous
267
+ `align.json` and `.vtt` files there are replaced on a rerun. Chapter-derived VTT filenames are
268
+ sanitized for safe local paths, while `align.json` retains the original document hrefs.
269
+
246
270
  ### The optional refine pass
247
271
 
248
272
  `pip install 'readalign[refine]'` adds torch and torchaudio, and `--refine` then runs a CTC
@@ -264,20 +288,71 @@ it, and any run that uses it records the restriction in the report's warnings.
264
288
  reported as untimed. They will never reach full coverage.
265
289
  - Audio is embedded in the EPUB, so the file is as large as the audiobook. Frankenstein at 64 kbps
266
290
  is 205 MB. There is no streaming or external-audio option in this version.
267
- - The audio timeline is shared across files. A sentence never spans two audio files; if one would,
268
- it is clipped at the file boundary.
291
+ - Media overlays preserve all audio between the first aligned sentence's start and the last
292
+ aligned sentence's end. Gaps between sentence timings play under the preceding sentence's
293
+ highlight, including across chapters and audio files. A gap that crosses files gets separate
294
+ file-local clips; even an intervening file with no matched words is included. Audio outside
295
+ that aligned range remains excluded, so an ebook excerpt does not play unrelated opening or
296
+ closing narration. Regenerate existing EPUBs to apply this fix.
297
+ - The alignment report and WebVTT sidecars keep the original matched sentence times; only the
298
+ EPUB playback clips are extended. Overlay `media:duration` includes the recovered audio.
299
+ Overlapping sentence timings are joined at the next sentence's start instead of replaying
300
+ audio. SMIL uses millisecond precision: collapsed boundaries do not create empty clips, and
301
+ duration metadata sums the exact serialized file-local clips. Invalid or backward alignment
302
+ timestamps fail with an input error rather than silently dropping audio.
303
+ - `readalign check` warns about forward gaps and backward jumps between clips, including chapter
304
+ transitions in the same audio file. These are warnings, not failures, because third-party
305
+ books may intentionally omit or replay audio. It counts unique text targets as `sentences`
306
+ and reports `clips` separately; one text target can have several file-local playback clips.
269
307
  - Sentence splitting is tuned for English-style punctuation. Other languages align fine but may
270
308
  produce longer or shorter units than a native reader would choose.
271
309
 
272
310
  ## Reader support
273
311
 
274
- Media Overlays are part of EPUB 3, but support is uneven. Readium-based readers (Thorium Reader
275
- on desktop, Colibrio-based web readers) and Apple Books implement them. Kindle does not read EPUB
276
- overlays at all, and several popular mobile readers ignore the `media-overlay` attribute and just
277
- show the book. If a reader shows the text but plays no audio, it does not support overlays; the
278
- file is still a valid EPUB and still readable.
279
-
280
- readalign's output is validated against epubcheck 5.2.1, and `readalign check` is validated
312
+ Media Overlays are part of EPUB 3, but support is uneven. Text rendering, audio decoding,
313
+ sentence highlighting and saving the narration position are separate capabilities. A silent
314
+ book can mean an unsupported codec or a reader bug, not just missing overlay support.
315
+
316
+ ### Compatibility evidence (October 25, 2026)
317
+
318
+ This is a record of available evidence, **not a personally tested reader certification table**.
319
+ Reader fixes merged upstream may not yet be in the version you have installed.
320
+
321
+ | Reader / platform | Evidence and limits |
322
+ | --- | --- |
323
+ | Calibre and Thorium, reporter's PC | A [Readest reporter](https://github.com/readest/readest/issues/6989) says their large narrated EPUB plays in both. Versions and complete seek/reopen behavior were not recorded. |
324
+ | Readest, web and desktop | [#7004](https://github.com/readest/readest/pull/7004) fixes loading a large stored audio entry without copying it all into memory. Upstream tested a 921 MB shared MP3, including an eight-hour seek. This is upstream testing, not a readalign reader test. |
325
+ | Readest, Android and iOS | [#7010](https://github.com/readest/readest/pull/7010) and [#7019](https://github.com/readest/readest/pull/7019) extend direct audio access to native players. Upstream tests are described in those PRs; they do not establish playback of every readalign book. |
326
+ | Readest, Linux app | The maintainer [reports no AAC decoder](https://github.com/readest/readest/issues/6989#issuecomment-6357568308). Try `--audio-format mp3`; updating for large-track fixes alone does not resolve that codec limitation. |
327
+ | Episteme, Android | An [independent readalign-output user](https://github.com/Aryan-Raj3112/episteme/issues/579) reports narration restarting at the beginning of a long section after reopening. The same book highlights sentences correctly on PC. No readalign-side fix is established. |
328
+ | Apple Books and other readers | Overlay support alone is not proof of long-track seeking or saved narration position. These behaviors have not been verified here. |
329
+ | Kindle | EPUB Media Overlays are not supported. |
330
+
331
+ ### Long books and playback troubleshooting
332
+
333
+ 1. Run `readalign check read-along.epub` and, if available, epubcheck. A clean result checks
334
+ package structure and clip bounds, not whether a specific reader plays or resumes correctly.
335
+ 2. Check the reader version and audio codec. MP3 output is an option for AAC/Opus decoder
336
+ limitations; an EPUB can be valid while a reader cannot decode its narration.
337
+ 3. For large books, use a reader version containing its large-track fixes. readalign stores
338
+ prepared MP3/M4A/Opus entries without ZIP compression so readers can seek directly. A reader
339
+ may still extract or copy the whole track before playback. One overlay per content document
340
+ does not mean the audio is split into separate files. If you already own chapter-sized
341
+ narration files, pass their directory; they are naturally sorted.
342
+ 4. Test a later chapter, cross a chapter boundary, pause/resume, then close and reopen the book.
343
+ Saving the text position is not the same as saving the narration sentence and audio offset.
344
+ Re-encoding to MP3 is not a guaranteed workaround for narration-position loss.
345
+ 5. Compare the same EPUB in another overlay-capable reader. If only one reader fails, include
346
+ that comparison when reporting it rather than assuming the EPUB generation is defective.
347
+
348
+ When reporting a problem, include readalign's version, reader version, OS/device, audio format,
349
+ approximate track duration/size, the chapter and sentence where it happens, and whether it is
350
+ startup, seeking, highlighting or reopening that fails. Include the output of `readalign check`
351
+ and a short public-domain reproduction if possible. Reports and sidecars can contain local paths
352
+ and quoted book text: inspect them before sharing. Do not upload a copyrighted book or narration
353
+ unless you have permission.
354
+
355
+ readalign's sample output is validated against epubcheck 5.2.1, and `readalign check` is validated
281
356
  against the reference Media Overlays title from the EPUB test suite at
282
357
  <https://epubtest.org/test-books>.
283
358
 
@@ -305,9 +380,12 @@ python -m pytest tests -q
305
380
  python -m ruff check .
306
381
  ```
307
382
 
308
- The suite runs in about a second and needs neither a GPU nor network access; it builds its own
383
+ The suite needs neither a GPU nor network access; it builds its own
309
384
  EPUBs and synthesises word timings. A few cases need ffmpeg and skip without it, and one is
310
385
  skipped unless `READALIGN_MO_TESTBOOK` points at a copy of the epubtest.org Media Overlays book.
386
+ Long-book packaging tests cover shared 16-hour timelines, separate-track clock resets, stored
387
+ audio entries and ZIP64 selection using a lowered size threshold. Synthetic timings and a lowered
388
+ threshold do not substitute for a real multi-gigabyte book or reader playback test.
311
389
 
312
390
  ## Distribution
313
391
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "readalign"
7
- version = "1.2.0"
7
+ version = "1.3.1"
8
8
  description = "Turn an audiobook and the matching ebook you own into one EPUB 3 with Media Overlays."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -1,3 +1,3 @@
1
1
  """readalign: build an EPUB 3 with Media Overlays from an audiobook and the matching ebook."""
2
2
 
3
- __version__ = "1.2.0"
3
+ __version__ = "1.3.1"
@@ -199,10 +199,12 @@ def _chapters_from(probe: dict) -> list[Chapter]:
199
199
  return chapters
200
200
 
201
201
 
202
- def _output_plan(path: str, probe: dict) -> tuple[str, str, bool]:
202
+ def _output_plan(path: str, probe: dict, audio_format: str = "auto") -> tuple[str, str, bool]:
203
203
  """Pick the extension, media type and whether a transcode is needed for a source file."""
204
204
  stream = _audio_stream(probe, path)
205
205
  codec = (stream.get("codec_name") or "").lower()
206
+ if audio_format == "mp3":
207
+ return ".mp3", "audio/mpeg", codec != "mp3"
206
208
  names = (probe.get("format", {}).get("format_name") or "").split(",")
207
209
  container = {name.strip() for name in names}
208
210
  if codec == "mp3":
@@ -214,13 +216,17 @@ def _output_plan(path: str, probe: dict) -> tuple[str, str, bool]:
214
216
  return ".m4a", "audio/mp4", True
215
217
 
216
218
 
217
- def prepare_tracks(sources: list[str], workdir: str, bitrate: str, log=print) -> list[AudioTrack]:
219
+ def prepare_tracks(
220
+ sources: list[str], workdir: str, bitrate: str, log=print, *, audio_format: str = "auto",
221
+ ) -> list[AudioTrack]:
218
222
  """Copy or transcode every source into an EPUB core media type and measure the result.
219
223
 
220
224
  MP3, AAC-in-MP4 and Opus-in-Ogg are core media types in EPUB 3, so they are stream-copied.
221
225
  Anything else (FLAC, WAV, ALAC, WMA) is transcoded to AAC, because a reading system is not
222
- required to play it.
226
+ required to play it. Explicit MP3 output avoids AAC/Opus decoder limitations in some readers.
223
227
  """
228
+ if audio_format not in {"auto", "mp3"}:
229
+ raise InputError("audio format must be auto or mp3")
224
230
  audio_dir = os.path.join(workdir, "audio")
225
231
  os.makedirs(audio_dir, exist_ok=True)
226
232
  tracks: list[AudioTrack] = []
@@ -228,15 +234,17 @@ def prepare_tracks(sources: list[str], workdir: str, bitrate: str, log=print) ->
228
234
  for index, source in enumerate(sources, start=1):
229
235
  probe = ffprobe(source)
230
236
  _reject_drm(source, probe)
231
- suffix, media_type, transcode = _output_plan(source, probe)
237
+ suffix, media_type, transcode = _output_plan(source, probe, audio_format)
232
238
  target = os.path.join(audio_dir, f"part{index:03d}{suffix}")
233
239
  if any(same_path(target, original) for original in sources):
234
240
  raise InputError(f"the work directory would overwrite source audio: {target}")
235
241
  label = f"[{index}/{len(sources)}] {os.path.basename(source)}"
236
- log(f" {label} -> {'transcoding to AAC' if transcode else 'stream copy'}")
242
+ codec_label = "MP3" if suffix == ".mp3" else "AAC"
243
+ log(f" {label} -> {'transcoding to ' + codec_label if transcode else 'stream copy'}")
237
244
  command = ["ffmpeg", "-nostdin", "-v", "error", "-y", "-i", source,
238
245
  "-map", "0:a:0", "-map_chapters", "0", "-vn"]
239
- command += ["-c:a", "aac", "-b:a", bitrate] if transcode else ["-c:a", "copy"]
246
+ codec = "libmp3lame" if suffix == ".mp3" else "aac"
247
+ command += ["-c:a", codec, "-b:a", bitrate] if transcode else ["-c:a", "copy"]
240
248
  if suffix == ".m4a":
241
249
  command += ["-movflags", "+faststart"]
242
250
  result = _run([*command, target], f"preparing {source}")
@@ -21,7 +21,7 @@ from urllib.parse import unquote
21
21
 
22
22
  from . import __version__
23
23
  from .errors import InputError, ReadAlignError
24
- from .fs import ensure_directory, same_path
24
+ from .fs import ensure_directory, is_within, same_path
25
25
  from .members import open_archive
26
26
 
27
27
  DEFAULT_MODEL = "large-v3-turbo"
@@ -79,6 +79,9 @@ def build_parser() -> argparse.ArgumentParser:
79
79
  help="disable the voice-activity filter")
80
80
  build.add_argument("--audio-bitrate", default="96k",
81
81
  help="bitrate used when audio has to be transcoded (default: 96k)")
82
+ build.add_argument("--audio-format", choices=["auto", "mp3"], default="auto",
83
+ help="embedded audio format: auto preserves supported codecs; mp3 avoids "
84
+ "AAC/Opus decoder limitations (default: auto)")
82
85
  build.add_argument("--verify", nargs="?", const="auto", default=None, metavar="EPUBCHECK",
83
86
  help="validate the result with epubcheck after writing it (needs Java). "
84
87
  "Pass its jar path, or leave the value off to search PATH, "
@@ -162,11 +165,8 @@ def run_build(args) -> int:
162
165
  raise InputError("--report would overwrite the input or output EPUB")
163
166
  directory = os.path.join(os.path.dirname(out_path),
164
167
  os.path.splitext(os.path.basename(out_path))[0] + "-sidecars")
165
- if args.sidecars:
166
- sidecar_root = os.path.normcase(os.path.realpath(directory))
167
- report_real = os.path.normcase(os.path.realpath(report_path))
168
- if report_real == sidecar_root or report_real.startswith(sidecar_root + os.sep):
169
- raise InputError("--report must be outside the generated sidecar directory")
168
+ if args.sidecars and is_within(report_path, directory):
169
+ raise InputError("--report must be outside the generated sidecar directory")
170
170
 
171
171
  verification_tool = None
172
172
  if args.verify and not args.dry_run:
@@ -190,16 +190,28 @@ def run_build(args) -> int:
190
190
  for source in sources:
191
191
  if same_path(out_path, source) or same_path(report_path, source):
192
192
  raise InputError(f"an output path would overwrite source audio: {source}")
193
+ if args.sidecars:
194
+ for path in [args.epub, out_path, *sources]:
195
+ if is_within(path, directory):
196
+ raise InputError(f"inputs and output EPUB must be outside the generated "
197
+ f"sidecar directory: {path}")
193
198
  log(f"preparing {len(sources)} audio file(s)")
194
199
  work_dir = args.work_dir or tempfile.mkdtemp(prefix="readalign-")
195
200
  temporary = args.work_dir is None
196
201
  ensure_directory(work_dir, "work directory")
197
202
  try:
198
203
  for index in range(1, len(sources) + 1):
199
- wav_path = os.path.join(work_dir, "wav", f"part{index:03d}.wav")
200
- if any(same_path(wav_path, source) for source in [args.epub, *sources]):
201
- raise InputError(f"the work directory would overwrite an input: {wav_path}")
202
- tracks = prepare_tracks(sources, work_dir, args.audio_bitrate, log=log)
204
+ # Reserve all prepared formats before ffmpeg can modify any existing output.
205
+ scratch_paths = [os.path.join(work_dir, "audio", f"part{index:03d}{suffix}")
206
+ for suffix in (".mp3", ".m4a", ".opus")]
207
+ scratch_paths.append(os.path.join(work_dir, "wav", f"part{index:03d}.wav"))
208
+ for path in scratch_paths:
209
+ if any(same_path(path, protected)
210
+ for protected in [args.epub, out_path, report_path, *sources]):
211
+ raise InputError(f"the work directory would overwrite an input or output: "
212
+ f"{path}")
213
+ tracks = prepare_tracks(sources, work_dir, args.audio_bitrate, log=log,
214
+ audio_format=args.audio_format)
203
215
  if args.dry_run:
204
216
  return _dry_run_plan(package, tracks, log)
205
217
 
@@ -279,6 +291,7 @@ def run_build(args) -> int:
279
291
  drift_threshold=args.drift_threshold,
280
292
  warnings=warnings,
281
293
  extras={"elapsed_seconds": round(time.monotonic() - started, 1),
294
+ "audio_format": args.audio_format,
282
295
  "token_match_gate": {
283
296
  "threshold": args.min_token_match,
284
297
  "passed": (result.matched_tokens / result.book_tokens
@@ -486,6 +499,10 @@ def _check_epub(path: str, *, probe_audio: bool) -> dict:
486
499
  max_clip_end: dict[str, float] = {}
487
500
  overlays = 0
488
501
  pars = 0
502
+ text_targets: set[tuple[str, str]] = set()
503
+ last_clip_end: dict[str, float] = {}
504
+ gaps: dict[str, float] = {}
505
+ backward_jumps: dict[str, float] = {}
489
506
  clip_total = 0.0
490
507
 
491
508
  for idref in spine:
@@ -533,6 +550,7 @@ def _check_epub(path: str, *, probe_audio: bool) -> dict:
533
550
  src = text.get("src")
534
551
  doc_path = _resolve(smil_path, src)
535
552
  fragment = unquote(src.split("#", 1)[1]) if "#" in src else ""
553
+ text_targets.add((doc_path, fragment))
536
554
  if doc_path != expected_document:
537
555
  errors.append(f"{smil_path}: text points outside its associated document")
538
556
  if manifested.get(doc_path) not in {"application/xhtml+xml", "image/svg+xml"}:
@@ -560,6 +578,15 @@ def _check_epub(path: str, *, probe_audio: bool) -> dict:
560
578
  continue
561
579
  if end <= begin:
562
580
  errors.append(f"{smil_path}: clipEnd {end} is not after clipBegin {begin}")
581
+ else:
582
+ previous_end = last_clip_end.get(audio_path)
583
+ if previous_end is not None:
584
+ delta = begin - previous_end
585
+ if delta > 0.0005:
586
+ gaps[audio_path] = gaps.get(audio_path, 0.0) + delta
587
+ elif delta < -0.0005:
588
+ backward_jumps[audio_path] = backward_jumps.get(audio_path, 0.0) - delta
589
+ last_clip_end[audio_path] = end
563
590
  overlay_clip += max(0.0, end - begin)
564
591
  max_clip_end[audio_path] = max(max_clip_end.get(audio_path, 0.0), end)
565
592
  clip_total += overlay_clip
@@ -570,6 +597,14 @@ def _check_epub(path: str, *, probe_audio: bool) -> dict:
570
597
  f"{overlay_clip:.3f}s"
571
598
  )
572
599
 
600
+ # Third-party overlays may intentionally skip or replay audio. Diagnose
601
+ # discontinuities in spine order, including chapter boundaries, as warnings.
602
+ for audio_path, seconds in gaps.items():
603
+ warnings.append(f"{audio_path}: {seconds:.3f}s of unreferenced audio between clips")
604
+ for audio_path, seconds in backward_jumps.items():
605
+ warnings.append(
606
+ f"{audio_path}: backward jumps total {seconds:.3f}s; audio may be replayed"
607
+ )
573
608
  audio_durations = (
574
609
  _probe_clip_ends(archive, max_clip_end, errors, warnings)
575
610
  if probe_audio and max_clip_end
@@ -588,7 +623,8 @@ def _check_epub(path: str, *, probe_audio: bool) -> dict:
588
623
  return {
589
624
  "epub": os.path.abspath(path),
590
625
  "overlays": overlays,
591
- "sentences": pars,
626
+ "sentences": len(text_targets),
627
+ "clips": pars,
592
628
  "clip_seconds": round(clip_total, 3),
593
629
  "declared_total": round(total_meta, 3) if total_meta is not None else None,
594
630
  "audio_durations": audio_durations,
@@ -607,6 +643,7 @@ def run_check(args) -> int:
607
643
  print(f"checking {findings['epub']}")
608
644
  print(f" overlays {findings['overlays']}")
609
645
  print(f" sentences {findings['sentences']}")
646
+ print(f" audio clips {findings['clips']}")
610
647
  print(f" clip time {findings['clip_seconds'] / 3600:.2f} hours")
611
648
  if findings["declared_total"] is not None:
612
649
  print(f" media:duration {findings['declared_total'] / 3600:.2f} hours declared")
@@ -24,6 +24,16 @@ def same_path(first: str, second: str) -> bool:
24
24
  and os.path.samefile(first, second)))
25
25
 
26
26
 
27
+ def is_within(path: str, directory: str) -> bool:
28
+ """Include the directory itself and resolve aliases before comparing path components."""
29
+ path = os.path.normcase(os.path.realpath(path))
30
+ directory = os.path.normcase(os.path.realpath(directory))
31
+ try:
32
+ return os.path.commonpath([path, directory]) == directory
33
+ except ValueError: # Windows paths can be on different drives.
34
+ return False
35
+
36
+
27
37
  def write_text(path: str, text: str) -> None:
28
38
  try:
29
39
  with atomic_output(path) as temporary, \
@@ -60,11 +60,20 @@ class MemberReader(AbstractContextManager):
60
60
  def open(self, member: SourceFile | ArchiveMember) -> BinaryIO:
61
61
  if isinstance(member, SourceFile):
62
62
  return open(member.path, "rb")
63
- archive = self._archives.get(member.epub_path)
63
+ return self._archive(member.epub_path).open(member.name)
64
+
65
+ def size(self, member: SourceFile | ArchiveMember) -> int:
66
+ """Read metadata, not content, so large entries can select ZIP64 before streaming."""
67
+ if isinstance(member, SourceFile):
68
+ return os.path.getsize(member.path)
69
+ return self._archive(member.epub_path).getinfo(member.name).file_size
70
+
71
+ def _archive(self, path: str) -> zipfile.ZipFile:
72
+ archive = self._archives.get(path)
64
73
  if archive is None:
65
- archive = zipfile.ZipFile(member.epub_path)
66
- self._archives[member.epub_path] = archive
67
- return archive.open(member.name)
74
+ archive = zipfile.ZipFile(path)
75
+ self._archives[path] = archive
76
+ return archive
68
77
 
69
78
  def __exit__(self, *_) -> None:
70
79
  while self._archives:
@@ -2,7 +2,7 @@
2
2
 
3
3
  The OPF gains the audio and overlay manifest items, the ``media-overlay`` attribute on every
4
4
  narrated content document, and the ``media:`` metadata EPUB 3.3 section 9.3.5 requires. The
5
- archive is written mimetype-first and uncompressed, as OCF demands.
5
+ archive is written mimetype-first, with that entry stored as OCF demands.
6
6
  """
7
7
 
8
8
  from __future__ import annotations
@@ -23,7 +23,7 @@ from .epub import OPF_NS, EpubPackage, ManifestItem, local_name
23
23
  from .errors import InputError
24
24
  from .fs import atomic_output, ensure_directory, unique_filenames
25
25
  from .members import Member, MemberReader, SourceFile
26
- from .smil import build_smil, overlay_duration, relative_href
26
+ from .smil import build_smil, continuous_clips, overlay_duration, relative_href
27
27
 
28
28
  AUDIO_DIR = "audio"
29
29
  OVERLAY_DIR = "media-overlays"
@@ -198,6 +198,16 @@ def build_output(
198
198
  narrator: str | None = None,
199
199
  ) -> tuple[Member, dict]:
200
200
  """Produce the member-name-to-bytes map of the output EPUB, and a summary of what changed."""
201
+ # Normalize across the whole spine, not separately per chapter: readers also
202
+ # skip unreferenced audio between two different overlay documents.
203
+ entries = continuous_clips([
204
+ entry for doc in package.docs for entry in entries_by_doc.get(doc.manifest_id, [])
205
+ ], tracks)
206
+ doc_ids = {index: doc.manifest_id for index, doc in enumerate(package.docs)}
207
+ entries_by_doc = {}
208
+ for entry in entries:
209
+ entries_by_doc.setdefault(doc_ids[entry.sentence.doc_index], []).append(entry)
210
+
201
211
  manifest = _manifest_element(package)
202
212
  metadata = _metadata_element(package)
203
213
  _drop_existing_overlay_metadata(metadata)
@@ -255,7 +265,7 @@ def build_output(
255
265
  overlay_id = _free_id(package, f"readalign-smil-{doc.manifest_id}")
256
266
  _add_manifest_item(package, manifest, overlay_id, href, "application/smil+xml")
257
267
  package.manifest[doc.manifest_id].element.set("media-overlay", overlay_id)
258
- duration = overlay_duration(entries)
268
+ duration = overlay_duration(entries, by_index)
259
269
  overlays.append((overlay_id, duration))
260
270
  total += duration
261
271
 
@@ -284,7 +294,7 @@ def build_output(
284
294
 
285
295
 
286
296
  def write_epub(path: str, files: Member, original_order: list[str]) -> None:
287
- """Write an OCF archive: mimetype first and stored, everything else deflated."""
297
+ """Write an OCF archive: mimetype first and stored, audio stored for direct seeking."""
288
298
  ordered: list[str] = []
289
299
  seen = set()
290
300
  for name in ["mimetype", "META-INF/container.xml", *original_order]:
@@ -323,6 +333,8 @@ def _write_archive(path: str, files: Member, ordered: list[str]) -> None:
323
333
  if isinstance(data, bytes):
324
334
  archive.writestr(info, data)
325
335
  else:
336
+ # zipfile must reserve a ZIP64 header before streaming a large audiobook.
337
+ info.file_size = read.size(data)
326
338
  with read.open(data) as source, archive.open(info, "w") as target:
327
339
  shutil.copyfileobj(source, target, 1 << 20)
328
340