readalign 1.3.0__tar.gz → 1.3.2__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 (39) hide show
  1. {readalign-1.3.0 → readalign-1.3.2}/CHANGELOG.md +22 -0
  2. {readalign-1.3.0 → readalign-1.3.2}/PKG-INFO +17 -3
  3. {readalign-1.3.0 → readalign-1.3.2}/README.md +16 -2
  4. {readalign-1.3.0 → readalign-1.3.2}/pyproject.toml +1 -1
  5. {readalign-1.3.0 → readalign-1.3.2}/src/readalign/__init__.py +1 -1
  6. {readalign-1.3.0 → readalign-1.3.2}/src/readalign/cli.py +25 -1
  7. {readalign-1.3.0 → readalign-1.3.2}/src/readalign/package.py +12 -2
  8. readalign-1.3.2/src/readalign/smil.py +135 -0
  9. {readalign-1.3.0 → readalign-1.3.2}/tests/test_output.py +93 -2
  10. readalign-1.3.2/tests/test_smil.py +147 -0
  11. readalign-1.3.0/src/readalign/smil.py +0 -78
  12. {readalign-1.3.0 → readalign-1.3.2}/.gitignore +0 -0
  13. {readalign-1.3.0 → readalign-1.3.2}/LICENSE +0 -0
  14. {readalign-1.3.0 → readalign-1.3.2}/scripts/fetch_samples.py +0 -0
  15. {readalign-1.3.0 → readalign-1.3.2}/src/readalign/__main__.py +0 -0
  16. {readalign-1.3.0 → readalign-1.3.2}/src/readalign/align.py +0 -0
  17. {readalign-1.3.0 → readalign-1.3.2}/src/readalign/asr.py +0 -0
  18. {readalign-1.3.0 → readalign-1.3.2}/src/readalign/audio.py +0 -0
  19. {readalign-1.3.0 → readalign-1.3.2}/src/readalign/clock.py +0 -0
  20. {readalign-1.3.0 → readalign-1.3.2}/src/readalign/epub.py +0 -0
  21. {readalign-1.3.0 → readalign-1.3.2}/src/readalign/errors.py +0 -0
  22. {readalign-1.3.0 → readalign-1.3.2}/src/readalign/fs.py +0 -0
  23. {readalign-1.3.0 → readalign-1.3.2}/src/readalign/members.py +0 -0
  24. {readalign-1.3.0 → readalign-1.3.2}/src/readalign/refine.py +0 -0
  25. {readalign-1.3.0 → readalign-1.3.2}/src/readalign/report.py +0 -0
  26. {readalign-1.3.0 → readalign-1.3.2}/src/readalign/sentences.py +0 -0
  27. {readalign-1.3.0 → readalign-1.3.2}/src/readalign/sidecar.py +0 -0
  28. {readalign-1.3.0 → readalign-1.3.2}/src/readalign/textnorm.py +0 -0
  29. {readalign-1.3.0 → readalign-1.3.2}/src/readalign/verify.py +0 -0
  30. {readalign-1.3.0 → readalign-1.3.2}/tests/conftest.py +0 -0
  31. {readalign-1.3.0 → readalign-1.3.2}/tests/test_align.py +0 -0
  32. {readalign-1.3.0 → readalign-1.3.2}/tests/test_asr.py +0 -0
  33. {readalign-1.3.0 → readalign-1.3.2}/tests/test_audio.py +0 -0
  34. {readalign-1.3.0 → readalign-1.3.2}/tests/test_cli.py +0 -0
  35. {readalign-1.3.0 → readalign-1.3.2}/tests/test_epub.py +0 -0
  36. {readalign-1.3.0 → readalign-1.3.2}/tests/test_fs.py +0 -0
  37. {readalign-1.3.0 → readalign-1.3.2}/tests/test_sidecar_report.py +0 -0
  38. {readalign-1.3.0 → readalign-1.3.2}/tests/test_text.py +0 -0
  39. {readalign-1.3.0 → readalign-1.3.2}/tests/test_verify.py +0 -0
@@ -1,5 +1,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.3.2 - 2026-10-25
4
+
5
+ - Maintenance: Linux CI installs ffmpeg without optional recommended packages. Package
6
+ downloads, dependency installation and CI jobs now have bounded timeouts so a slow
7
+ package mirror cannot leave release verification waiting indefinitely.
8
+ - No application behavior changes from 1.3.1.
9
+
10
+ ## 1.3.1 - 2026-10-25
11
+
12
+ - Fixed: SMIL playback no longer skips audio between consecutive aligned sentences, including
13
+ chapter boundaries and gaps spanning audio files. Gaps play with the preceding sentence's
14
+ highlight; file-local clip bounds and overlay duration metadata include the recovered audio.
15
+ Alignment reports and WebVTT timestamps remain unchanged. Audio outside the first-to-last
16
+ aligned range stays excluded to preserve excerpt behavior. Regenerate existing EPUBs to apply.
17
+ - Fixed: overlapping sentence timings no longer replay audio. Millisecond-collapsed clips are
18
+ omitted and duration metadata uses the exact serialized file-local clocks. Invalid, nonfinite
19
+ or backward timing data and inconsistent track timelines fail with readable input errors.
20
+ - Enhanced: `check` warns about forward gaps and backward jumps across clips and chapter
21
+ boundaries without rejecting intentional third-party discontinuities. It counts unique text
22
+ targets separately from audio clips, so splitting a sentence across files does not inflate
23
+ the reported sentence count.
24
+
3
25
  ## 1.3.0 - 2026-10-25
4
26
 
5
27
  - Fixed: work-directory audio/WAV paths cannot overwrite the input ebook, output EPUB or
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: readalign
3
- Version: 1.3.0
3
+ Version: 1.3.2
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
@@ -321,8 +321,22 @@ it, and any run that uses it records the restriction in the report's warnings.
321
321
  reported as untimed. They will never reach full coverage.
322
322
  - Audio is embedded in the EPUB, so the file is as large as the audiobook. Frankenstein at 64 kbps
323
323
  is 205 MB. There is no streaming or external-audio option in this version.
324
- - The audio timeline is shared across files. A sentence never spans two audio files; if one would,
325
- 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.
326
340
  - Sentence splitting is tuned for English-style punctuation. Other languages align fine but may
327
341
  produce longer or shorter units than a native reader would choose.
328
342
 
@@ -288,8 +288,22 @@ it, and any run that uses it records the restriction in the report's warnings.
288
288
  reported as untimed. They will never reach full coverage.
289
289
  - Audio is embedded in the EPUB, so the file is as large as the audiobook. Frankenstein at 64 kbps
290
290
  is 205 MB. There is no streaming or external-audio option in this version.
291
- - The audio timeline is shared across files. A sentence never spans two audio files; if one would,
292
- 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.
293
307
  - Sentence splitting is tuned for English-style punctuation. Other languages align fine but may
294
308
  produce longer or shorter units than a native reader would choose.
295
309
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "readalign"
7
- version = "1.3.0"
7
+ version = "1.3.2"
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.3.0"
3
+ __version__ = "1.3.2"
@@ -499,6 +499,10 @@ def _check_epub(path: str, *, probe_audio: bool) -> dict:
499
499
  max_clip_end: dict[str, float] = {}
500
500
  overlays = 0
501
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] = {}
502
506
  clip_total = 0.0
503
507
 
504
508
  for idref in spine:
@@ -546,6 +550,7 @@ def _check_epub(path: str, *, probe_audio: bool) -> dict:
546
550
  src = text.get("src")
547
551
  doc_path = _resolve(smil_path, src)
548
552
  fragment = unquote(src.split("#", 1)[1]) if "#" in src else ""
553
+ text_targets.add((doc_path, fragment))
549
554
  if doc_path != expected_document:
550
555
  errors.append(f"{smil_path}: text points outside its associated document")
551
556
  if manifested.get(doc_path) not in {"application/xhtml+xml", "image/svg+xml"}:
@@ -573,6 +578,15 @@ def _check_epub(path: str, *, probe_audio: bool) -> dict:
573
578
  continue
574
579
  if end <= begin:
575
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
576
590
  overlay_clip += max(0.0, end - begin)
577
591
  max_clip_end[audio_path] = max(max_clip_end.get(audio_path, 0.0), end)
578
592
  clip_total += overlay_clip
@@ -583,6 +597,14 @@ def _check_epub(path: str, *, probe_audio: bool) -> dict:
583
597
  f"{overlay_clip:.3f}s"
584
598
  )
585
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
+ )
586
608
  audio_durations = (
587
609
  _probe_clip_ends(archive, max_clip_end, errors, warnings)
588
610
  if probe_audio and max_clip_end
@@ -601,7 +623,8 @@ def _check_epub(path: str, *, probe_audio: bool) -> dict:
601
623
  return {
602
624
  "epub": os.path.abspath(path),
603
625
  "overlays": overlays,
604
- "sentences": pars,
626
+ "sentences": len(text_targets),
627
+ "clips": pars,
605
628
  "clip_seconds": round(clip_total, 3),
606
629
  "declared_total": round(total_meta, 3) if total_meta is not None else None,
607
630
  "audio_durations": audio_durations,
@@ -620,6 +643,7 @@ def run_check(args) -> int:
620
643
  print(f"checking {findings['epub']}")
621
644
  print(f" overlays {findings['overlays']}")
622
645
  print(f" sentences {findings['sentences']}")
646
+ print(f" audio clips {findings['clips']}")
623
647
  print(f" clip time {findings['clip_seconds'] / 3600:.2f} hours")
624
648
  if findings["declared_total"] is not None:
625
649
  print(f" media:duration {findings['declared_total'] / 3600:.2f} hours declared")
@@ -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
 
@@ -0,0 +1,135 @@
1
+ """Write one media overlay document per content document.
2
+
3
+ Structure follows EPUB 3.3 section 9.2.2: a ``smil`` root at version 3.0, a ``body`` carrying
4
+ ``par`` elements, and nested ``seq`` wrappers mirroring the structures a reading system may let
5
+ the user skip (a footnote, a page number) or escape out of (a table, a list, a figure).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ import posixpath
12
+ from dataclasses import replace
13
+ from urllib.parse import quote
14
+
15
+ from lxml import etree
16
+
17
+ from .align import TimedSentence
18
+ from .audio import AudioTrack
19
+ from .clock import format_clock
20
+ from .errors import InputError
21
+
22
+ SMIL_NS = "http://www.w3.org/ns/SMIL"
23
+ EPUB_NS = "http://www.idpf.org/2007/ops"
24
+
25
+ _NSMAP = {None: SMIL_NS, "epub": EPUB_NS}
26
+
27
+
28
+ def relative_href(from_path: str, to_path: str) -> str:
29
+ """Path from one archive member to another, as a path-relative-scheme-less-URL string."""
30
+ relative = posixpath.relpath(to_path, posixpath.dirname(from_path))
31
+ return quote(relative.replace("\\", "/"))
32
+
33
+
34
+ def continuous_clips(
35
+ entries: list[TimedSentence], tracks: list[AudioTrack]
36
+ ) -> list[TimedSentence]:
37
+ """Cover inter-sentence audio without changing the alignment or excerpt boundaries."""
38
+ positions = {track.index: index for index, track in enumerate(tracks)}
39
+ for index, track in enumerate(tracks):
40
+ if (not math.isfinite(track.offset) or not math.isfinite(track.duration)
41
+ or track.offset < 0 or track.duration <= 0
42
+ or (index and not math.isclose(track.offset, tracks[index - 1].end,
43
+ rel_tol=0, abs_tol=1e-6))):
44
+ raise InputError("audio tracks must form a finite, contiguous playback timeline")
45
+ if len(positions) != len(tracks):
46
+ raise InputError("audio track indices must be unique")
47
+ previous_start = -math.inf
48
+ for entry in entries:
49
+ if entry.track_index not in positions:
50
+ raise InputError(f"alignment references unknown audio track {entry.track_index}")
51
+ track = tracks[positions[entry.track_index]]
52
+ if (not math.isfinite(entry.start) or not math.isfinite(entry.end)
53
+ or not track.offset <= entry.start < entry.end <= track.end
54
+ or entry.start < previous_start):
55
+ raise InputError("alignment timestamps must be finite, ordered and inside their track")
56
+ previous_start = entry.start
57
+ clips = []
58
+ for index, entry in enumerate(entries):
59
+ end = entries[index + 1].start if index + 1 < len(entries) else entry.end
60
+ start = entry.start
61
+ position = positions[entry.track_index]
62
+ # A gap can span files, including a file with no matched words. Each SMIL
63
+ # clip must still use that file's local clock and stop at its real end.
64
+ while position < len(tracks) and start < end:
65
+ track = tracks[position]
66
+ stop = min(end, track.end)
67
+ clip = replace(entry, start=start, end=stop, track_index=track.index)
68
+ begin_ms, end_ms = _clip_milliseconds(clip, track)
69
+ if end_ms > begin_ms:
70
+ clips.append(clip)
71
+ start = stop
72
+ position += 1
73
+ if entries and not clips:
74
+ raise InputError("the aligned audio range is too short for millisecond SMIL clips")
75
+ return clips
76
+
77
+
78
+ def _clip_milliseconds(entry: TimedSentence, track: AudioTrack) -> tuple[int, int]:
79
+ """Use the same file-local rounding for clip serialization and metadata."""
80
+ return round((entry.start - track.offset) * 1000), round((entry.end - track.offset) * 1000)
81
+
82
+
83
+ def build_smil(
84
+ smil_path: str,
85
+ doc_path: str,
86
+ entries: list[TimedSentence],
87
+ tracks: dict[int, AudioTrack],
88
+ audio_paths: dict[int, str],
89
+ ) -> bytes:
90
+ """Serialise the overlay for one content document."""
91
+ text_href = relative_href(smil_path, doc_path)
92
+ root = etree.Element(f"{{{SMIL_NS}}}smil", nsmap=_NSMAP)
93
+ root.set("version", "3.0")
94
+ body = etree.SubElement(root, f"{{{SMIL_NS}}}body")
95
+ body.set(f"{{{EPUB_NS}}}textref", text_href)
96
+
97
+ # Open seqs, innermost last. Nesting has to mirror the document for escapability to work,
98
+ # and entries arrive in document order, so a structure is left as soon as its ids stop matching.
99
+ open_seqs: list[tuple[str, etree._Element]] = []
100
+ for entry in entries:
101
+ track = tracks[entry.track_index]
102
+ begin_ms, end_ms = _clip_milliseconds(entry, track)
103
+ if end_ms <= begin_ms:
104
+ continue
105
+ chain = entry.sentence.structure
106
+ shared = 0
107
+ while (
108
+ shared < len(open_seqs)
109
+ and shared < len(chain)
110
+ and open_seqs[shared][0] == chain[shared].container_id
111
+ ):
112
+ shared += 1
113
+ del open_seqs[shared:]
114
+ for level in chain[shared:]:
115
+ parent = open_seqs[-1][1] if open_seqs else body
116
+ seq = etree.SubElement(parent, f"{{{SMIL_NS}}}seq")
117
+ seq.set(f"{{{EPUB_NS}}}textref", f"{text_href}#{quote(level.container_id, safe='')}")
118
+ seq.set(f"{{{EPUB_NS}}}type", level.epub_type)
119
+ open_seqs.append((level.container_id, seq))
120
+ container = open_seqs[-1][1] if open_seqs else body
121
+ par = etree.SubElement(container, f"{{{SMIL_NS}}}par")
122
+ text = etree.SubElement(par, f"{{{SMIL_NS}}}text")
123
+ text.set("src", f"{text_href}#{quote(entry.sentence.fragment_id, safe='')}")
124
+ audio = etree.SubElement(par, f"{{{SMIL_NS}}}audio")
125
+ audio.set("src", relative_href(smil_path, audio_paths[entry.track_index]))
126
+ audio.set("clipBegin", format_clock(begin_ms / 1000))
127
+ audio.set("clipEnd", format_clock(end_ms / 1000))
128
+ return etree.tostring(root, xml_declaration=True, encoding="utf-8", pretty_print=True)
129
+
130
+
131
+ def overlay_duration(entries: list[TimedSentence], tracks: dict[int, AudioTrack]) -> float:
132
+ """Playing time of an overlay: the sum of its clips, which is what media:duration means."""
133
+ return sum(max(0, end - begin) for begin, end in (
134
+ _clip_milliseconds(entry, tracks[entry.track_index]) for entry in entries
135
+ )) / 1000
@@ -4,14 +4,17 @@ import os
4
4
  import shutil
5
5
  import subprocess
6
6
  import zipfile
7
+ from dataclasses import replace
8
+ from itertools import pairwise
7
9
  from urllib.parse import quote
8
10
 
9
11
  import pytest
10
12
  from lxml import etree
11
13
 
12
14
  from conftest import CHAPTERS, STRUCTURED, build_epub, make_tracks, speak
13
- from readalign.align import align
15
+ from readalign.align import TimedSentence, align
14
16
  from readalign.cli import check_epub
17
+ from readalign.clock import parse_clock
15
18
  from readalign.epub import OPF_NS, load_epub, local_name
16
19
  from readalign.members import ArchiveMember, SourceFile
17
20
  from readalign.package import ACTIVE_CLASS, build_output, ensure_mimetype, write_epub
@@ -106,6 +109,92 @@ def test_package_document_carries_the_overlay_metadata(aligned):
106
109
  assert ("media:narrator", None, "A Narrator") in metas
107
110
 
108
111
 
112
+ @pytest.mark.parametrize("durations", [[700], [655, 2, 43]])
113
+ @pytest.mark.parametrize("across_chapters", [True, False])
114
+ def test_overlays_preserve_audio_between_sentences_and_chapters(
115
+ tmp_path, durations, across_chapters
116
+ ):
117
+ package = load_epub(build_epub(str(tmp_path / "gaps.epub")))
118
+ tracks = make_tracks(durations)
119
+ first = package.docs[0].sentences[0]
120
+ second = package.docs[int(across_chapters)].sentences[1]
121
+ entries = {
122
+ "c1": [TimedSentence(first, 652, 654, 1.0, 1)],
123
+ }
124
+ entries.setdefault("c2" if across_chapters else "c1", []).append(
125
+ TimedSentence(second, 658, 662, 1.0, len(tracks)))
126
+ original = {key: [replace(entry) for entry in values] for key, values in entries.items()}
127
+ files, summary = build_output(package, entries, tracks)
128
+ clips = []
129
+ for index, _doc in enumerate(package.docs, start=1):
130
+ path = f"EPUB/media-overlays/chapter{index}.smil"
131
+ if path not in files:
132
+ continue
133
+ root = etree.fromstring(files[path])
134
+ for audio in root.iter(f"{{{SMIL_NS}}}audio"):
135
+ track = next(track for track in tracks if audio.get("src").endswith(
136
+ f"part{track.index:03d}.mp3"))
137
+ begin = parse_clock(audio.get("clipBegin"))
138
+ end = parse_clock(audio.get("clipEnd"))
139
+ assert 0 <= begin < end <= track.duration
140
+ clips.append((track.offset + begin, track.offset + end))
141
+ assert clips[0][0] == 652 # Preserve the excerpt's outer boundaries.
142
+ assert clips[-1][1] == 662
143
+ assert all(left[1] == right[0] for left, right in pairwise(clips))
144
+ assert parse_clock(summary["total_duration"]) == 10
145
+ opf = etree.fromstring(files[package.opf_path])
146
+ durations_in_opf = [parse_clock(meta.text) for meta in opf.iter(f"{{{OPF_NS}}}meta")
147
+ if meta.get("property") == "media:duration" and meta.get("refines")]
148
+ assert sum(durations_in_opf) == 10
149
+ assert summary["audio_files"] == len(tracks)
150
+ assert entries == original # Sidecars and diagnostics retain the alignment evidence.
151
+
152
+
153
+ @pytest.mark.parametrize("across_chapters", [True, False])
154
+ @pytest.mark.parametrize("delta, warning", [(0.125, "unreferenced"), (-0.125, "replayed")])
155
+ def test_check_warns_about_audio_discontinuities(
156
+ aligned, tmp_path, across_chapters, delta, warning
157
+ ):
158
+ package, _, tracks, entries = aligned
159
+ files, _ = build_output(package, entries, tracks)
160
+ path = f"EPUB/media-overlays/chapter{2 if across_chapters else 1}.smil"
161
+ root = etree.fromstring(files[path])
162
+ audio = list(root.iter(f"{{{SMIL_NS}}}audio"))[0 if across_chapters else 1]
163
+ from readalign.clock import format_clock
164
+
165
+ audio.set("clipBegin", format_clock(parse_clock(audio.get("clipBegin")) + delta))
166
+ files[path] = etree.tostring(root)
167
+ ensure_mimetype(files)
168
+ output = str(tmp_path / "discontinuous.epub")
169
+ # Structural checks only: the fixture may use nonexistent audio paths without ffmpeg.
170
+ for name, data in list(files.items()):
171
+ if isinstance(data, SourceFile) and not os.path.exists(data.path):
172
+ files[name] = b"synthetic audio"
173
+ write_epub(output, files, package.order)
174
+ findings = check_epub(output, probe_audio=False)
175
+ assert findings["ok"] # Third-party overlays may intentionally omit or repeat audio.
176
+ assert any(warning in item and "0.125s" in item for item in findings["warnings"])
177
+
178
+
179
+ def test_check_counts_split_playback_clips_separately_from_text_targets(tmp_path):
180
+ package = load_epub(build_epub(str(tmp_path / "input.epub")))
181
+ tracks = make_tracks([10, 10])
182
+ for track in tracks:
183
+ path = tmp_path / f"part{track.index}.mp3"
184
+ path.write_bytes(b"synthetic audio")
185
+ track.path = str(path)
186
+ entries = {"c1": [TimedSentence(package.docs[0].sentences[0], 2, 4, 1.0, 1)],
187
+ "c2": [TimedSentence(package.docs[1].sentences[0], 12, 14, 1.0, 2)]}
188
+ files, _ = build_output(package, entries, tracks)
189
+ ensure_mimetype(files)
190
+ output = str(tmp_path / "split.epub")
191
+ write_epub(output, files, package.order)
192
+ findings = check_epub(output, probe_audio=False)
193
+ assert findings["sentences"] == 2
194
+ assert findings["clips"] == 3
195
+ assert findings["warnings"] == []
196
+
197
+
109
198
  def test_archive_starts_with_a_stored_mimetype(aligned, tmp_path):
110
199
  package, _, tracks, entries = aligned
111
200
  if not has_ffmpeg:
@@ -273,7 +362,9 @@ def test_long_book_uses_file_local_clocks_and_stored_audio(tmp_path, shared_trac
273
362
  clips = list(root.iter(f"{{{SMIL_NS}}}audio"))
274
363
  expected_start = index * 8 * 3600 + 15.125 if shared_track else 15.125
275
364
  assert parse_clock(clips[0].get("clipBegin")) == expected_start
276
- assert len(clips) == len(doc.sentences) == 450
365
+ # Crossing a file boundary adds a clip for the gap in the next file.
366
+ assert len(clips) == 450 + int(not shared_track and index == 0)
367
+ assert len(doc.sentences) == 450
277
368
  track = tracks[0 if shared_track else index]
278
369
  vtt = build_vtt(by_doc[doc.manifest_id], track, track.href)
279
370
  assert ("08:00:15.125" if shared_track and index else "00:00:15.125") in vtt
@@ -0,0 +1,147 @@
1
+ import random
2
+
3
+ import pytest
4
+ from lxml import etree
5
+
6
+ from conftest import build_epub, make_tracks
7
+ from readalign.align import TimedSentence
8
+ from readalign.clock import parse_clock
9
+ from readalign.epub import load_epub
10
+ from readalign.errors import InputError
11
+ from readalign.smil import SMIL_NS, build_smil, continuous_clips, overlay_duration
12
+
13
+
14
+ def test_continuous_clips_preserve_adjacent_clips_and_outer_boundaries(tmp_path):
15
+ package = load_epub(build_epub(str(tmp_path / "input.epub")))
16
+ sentences = package.docs[0].sentences
17
+ tracks = make_tracks([20])
18
+ entries = [TimedSentence(sentences[0], 2, 4, 1.0, 1),
19
+ TimedSentence(sentences[1], 4, 7, 1.0, 1)]
20
+ assert continuous_clips(entries, tracks) == entries
21
+ assert continuous_clips([], tracks) == []
22
+ assert continuous_clips(entries[:1], tracks) == entries[:1]
23
+
24
+
25
+ def test_gap_ending_at_track_boundary_does_not_add_zero_length_clip(tmp_path):
26
+ package = load_epub(build_epub(str(tmp_path / "input.epub")))
27
+ sentences = package.docs[0].sentences
28
+ tracks = make_tracks([10, 10])
29
+ entries = [TimedSentence(sentences[0], 2, 4, 1.0, 1),
30
+ TimedSentence(sentences[1], 10, 12, 1.0, 2)]
31
+ clips = continuous_clips(entries, tracks)
32
+ assert [(entry.start, entry.end, entry.track_index) for entry in clips] == [
33
+ (2, 10, 1), (10, 12, 2)]
34
+
35
+
36
+ def test_playback_does_not_repeat_overlapping_alignment_audio(tmp_path):
37
+ package = load_epub(build_epub(str(tmp_path / "input.epub")))
38
+ sentences = package.docs[0].sentences
39
+ tracks = make_tracks([20])
40
+ entries = [TimedSentence(sentences[0], 2, 6, 1.0, 1),
41
+ TimedSentence(sentences[1], 4, 7, 1.0, 1)]
42
+ clips = continuous_clips(entries, tracks)
43
+ assert [(entry.start, entry.end) for entry in clips] == [(2, 4), (4, 7)]
44
+ assert entries[0].end == 6
45
+
46
+
47
+ def test_submillisecond_boundary_never_serializes_an_empty_clip(tmp_path):
48
+ package = load_epub(build_epub(str(tmp_path / "input.epub")))
49
+ sentences = package.docs[0].sentences
50
+ tracks = make_tracks([10, 10])
51
+ entries = [TimedSentence(sentences[0], 2, 4, 1.0, 1),
52
+ TimedSentence(sentences[1], 10.0001, 12, 1.0, 2)]
53
+ clips = continuous_clips(entries, tracks)
54
+ xml = build_smil("EPUB/test.smil", "EPUB/chapter1.xhtml", clips,
55
+ {track.index: track for track in tracks},
56
+ {track.index: track.href for track in tracks})
57
+ audio = list(etree.fromstring(xml).iter(f"{{{SMIL_NS}}}audio"))
58
+ assert len(audio) == 2
59
+ assert all(parse_clock(item.get("clipEnd")) > parse_clock(item.get("clipBegin"))
60
+ for item in audio)
61
+
62
+
63
+ @pytest.mark.parametrize("bad_start", [1, float("nan"), float("inf")])
64
+ def test_invalid_playback_order_or_timestamps_fail_clearly(tmp_path, bad_start):
65
+ package = load_epub(build_epub(str(tmp_path / "input.epub")))
66
+ sentences = package.docs[0].sentences
67
+ tracks = make_tracks([20])
68
+ entries = [TimedSentence(sentences[0], 2, 4, 1.0, 1),
69
+ TimedSentence(sentences[1], bad_start, 7, 1.0, 1)]
70
+ with pytest.raises(InputError):
71
+ continuous_clips(entries, tracks)
72
+
73
+
74
+ def test_overlay_duration_matches_serialized_file_local_clocks(tmp_path):
75
+ package = load_epub(build_epub(str(tmp_path / "input.epub")))
76
+ tracks = make_tracks([10])
77
+ entries = [TimedSentence(package.docs[0].sentences[0], 1.0004, 1.0006, 1.0, 1)]
78
+ by_index = {1: tracks[0]}
79
+ xml = build_smil("EPUB/test.smil", "EPUB/chapter1.xhtml", entries,
80
+ by_index, {1: tracks[0].href})
81
+ audio = etree.fromstring(xml).find(f".//{{{SMIL_NS}}}audio")
82
+ serialized = parse_clock(audio.get("clipEnd")) - parse_clock(audio.get("clipBegin"))
83
+ assert overlay_duration(entries, by_index) == pytest.approx(serialized)
84
+
85
+
86
+ def test_duplicate_starts_do_not_replay_audio_or_emit_empty_highlights(tmp_path):
87
+ package = load_epub(build_epub(str(tmp_path / "input.epub")))
88
+ sentences = package.docs[0].sentences
89
+ tracks = make_tracks([10])
90
+ entries = [TimedSentence(sentences[0], 2, 4, 1.0, 1),
91
+ TimedSentence(sentences[1], 2, 5, 1.0, 1)]
92
+ assert continuous_clips(entries, tracks) == entries[1:]
93
+
94
+
95
+ @pytest.mark.parametrize("fault", ["unknown", "duplicate", "gap", "nonfinite", "outside"])
96
+ def test_invalid_track_timeline_fails_instead_of_silently_dropping_audio(tmp_path, fault):
97
+ package = load_epub(build_epub(str(tmp_path / "input.epub")))
98
+ tracks = make_tracks([10, 10])
99
+ entry = TimedSentence(package.docs[0].sentences[0], 2, 4, 1.0, 1)
100
+ if fault == "unknown":
101
+ entry.track_index = 99
102
+ elif fault == "duplicate":
103
+ tracks[1].index = 1
104
+ elif fault == "gap":
105
+ tracks[1].offset += 1
106
+ elif fault == "nonfinite":
107
+ tracks[1].duration = float("inf")
108
+ else:
109
+ entry.end = 11
110
+ with pytest.raises(InputError):
111
+ continuous_clips([entry], tracks)
112
+
113
+
114
+ def test_randomized_file_local_clocks_are_contiguous_and_match_metadata(tmp_path):
115
+ package = load_epub(build_epub(str(tmp_path / "input.epub")))
116
+ sentence = package.docs[0].sentences[0]
117
+ rng = random.Random(3)
118
+ for _ in range(100):
119
+ tracks = make_tracks([rng.uniform(5, 30) for _ in range(3)])
120
+ by_index = {track.index: track for track in tracks}
121
+ starts = sorted(rng.uniform(0.1, tracks[-1].end - 0.1) for _ in range(30))
122
+ entries = []
123
+ for start in starts:
124
+ track = next(track for track in tracks if start < track.end)
125
+ entries.append(TimedSentence(sentence, start, min(start + 0.05, track.end),
126
+ 1.0, track.index))
127
+ clips = continuous_clips(entries, tracks)
128
+ xml = build_smil("EPUB/test.smil", "EPUB/chapter1.xhtml", clips, by_index,
129
+ {track.index: track.href for track in tracks})
130
+ previous = None
131
+ milliseconds = 0
132
+ for audio, clip in zip(etree.fromstring(xml).iter(f"{{{SMIL_NS}}}audio"),
133
+ clips, strict=True):
134
+ begin = round(parse_clock(audio.get("clipBegin")) * 1000)
135
+ end = round(parse_clock(audio.get("clipEnd")) * 1000)
136
+ track = by_index[clip.track_index]
137
+ assert 0 <= begin < end <= round(track.duration * 1000)
138
+ if previous is not None:
139
+ last_track, last_end = previous
140
+ if last_track == track.index:
141
+ assert begin == last_end
142
+ else:
143
+ assert last_end == round(by_index[last_track].duration * 1000)
144
+ assert begin == 0
145
+ previous = track.index, end
146
+ milliseconds += end - begin
147
+ assert overlay_duration(clips, by_index) == milliseconds / 1000
@@ -1,78 +0,0 @@
1
- """Write one media overlay document per content document.
2
-
3
- Structure follows EPUB 3.3 section 9.2.2: a ``smil`` root at version 3.0, a ``body`` carrying
4
- ``par`` elements, and nested ``seq`` wrappers mirroring the structures a reading system may let
5
- the user skip (a footnote, a page number) or escape out of (a table, a list, a figure).
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- import posixpath
11
- from urllib.parse import quote
12
-
13
- from lxml import etree
14
-
15
- from .align import TimedSentence
16
- from .audio import AudioTrack
17
- from .clock import format_clock
18
-
19
- SMIL_NS = "http://www.w3.org/ns/SMIL"
20
- EPUB_NS = "http://www.idpf.org/2007/ops"
21
-
22
- _NSMAP = {None: SMIL_NS, "epub": EPUB_NS}
23
-
24
-
25
- def relative_href(from_path: str, to_path: str) -> str:
26
- """Path from one archive member to another, as a path-relative-scheme-less-URL string."""
27
- relative = posixpath.relpath(to_path, posixpath.dirname(from_path))
28
- return quote(relative.replace("\\", "/"))
29
-
30
-
31
- def build_smil(
32
- smil_path: str,
33
- doc_path: str,
34
- entries: list[TimedSentence],
35
- tracks: dict[int, AudioTrack],
36
- audio_paths: dict[int, str],
37
- ) -> bytes:
38
- """Serialise the overlay for one content document."""
39
- text_href = relative_href(smil_path, doc_path)
40
- root = etree.Element(f"{{{SMIL_NS}}}smil", nsmap=_NSMAP)
41
- root.set("version", "3.0")
42
- body = etree.SubElement(root, f"{{{SMIL_NS}}}body")
43
- body.set(f"{{{EPUB_NS}}}textref", text_href)
44
-
45
- # Open seqs, innermost last. Nesting has to mirror the document for escapability to work,
46
- # and entries arrive in document order, so a structure is left as soon as its ids stop matching.
47
- open_seqs: list[tuple[str, etree._Element]] = []
48
- for entry in entries:
49
- chain = entry.sentence.structure
50
- shared = 0
51
- while (
52
- shared < len(open_seqs)
53
- and shared < len(chain)
54
- and open_seqs[shared][0] == chain[shared].container_id
55
- ):
56
- shared += 1
57
- del open_seqs[shared:]
58
- for level in chain[shared:]:
59
- parent = open_seqs[-1][1] if open_seqs else body
60
- seq = etree.SubElement(parent, f"{{{SMIL_NS}}}seq")
61
- seq.set(f"{{{EPUB_NS}}}textref", f"{text_href}#{quote(level.container_id, safe='')}")
62
- seq.set(f"{{{EPUB_NS}}}type", level.epub_type)
63
- open_seqs.append((level.container_id, seq))
64
- container = open_seqs[-1][1] if open_seqs else body
65
- par = etree.SubElement(container, f"{{{SMIL_NS}}}par")
66
- text = etree.SubElement(par, f"{{{SMIL_NS}}}text")
67
- text.set("src", f"{text_href}#{quote(entry.sentence.fragment_id, safe='')}")
68
- track = tracks[entry.track_index]
69
- audio = etree.SubElement(par, f"{{{SMIL_NS}}}audio")
70
- audio.set("src", relative_href(smil_path, audio_paths[entry.track_index]))
71
- audio.set("clipBegin", format_clock(entry.start - track.offset))
72
- audio.set("clipEnd", format_clock(entry.end - track.offset))
73
- return etree.tostring(root, xml_declaration=True, encoding="utf-8", pretty_print=True)
74
-
75
-
76
- def overlay_duration(entries: list[TimedSentence]) -> float:
77
- """Playing time of an overlay: the sum of its clips, which is what media:duration means."""
78
- return sum(max(0.0, entry.end - entry.start) for entry in entries)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes