readalign 1.3.2__tar.gz → 1.3.3__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 (38) hide show
  1. {readalign-1.3.2 → readalign-1.3.3}/.gitignore +20 -20
  2. {readalign-1.3.2 → readalign-1.3.3}/CHANGELOG.md +16 -0
  3. {readalign-1.3.2 → readalign-1.3.3}/PKG-INFO +1 -1
  4. {readalign-1.3.2 → readalign-1.3.3}/pyproject.toml +1 -1
  5. {readalign-1.3.2 → readalign-1.3.3}/src/readalign/__init__.py +1 -1
  6. {readalign-1.3.2 → readalign-1.3.3}/src/readalign/align.py +16 -9
  7. {readalign-1.3.2 → readalign-1.3.3}/src/readalign/asr.py +14 -7
  8. {readalign-1.3.2 → readalign-1.3.3}/src/readalign/refine.py +2 -14
  9. {readalign-1.3.2 → readalign-1.3.3}/src/readalign/textnorm.py +8 -1
  10. {readalign-1.3.2 → readalign-1.3.3}/src/readalign/verify.py +2 -2
  11. {readalign-1.3.2 → readalign-1.3.3}/tests/test_align.py +35 -0
  12. {readalign-1.3.2 → readalign-1.3.3}/tests/test_asr.py +34 -0
  13. {readalign-1.3.2 → readalign-1.3.3}/tests/test_cli.py +4 -1
  14. {readalign-1.3.2 → readalign-1.3.3}/tests/test_text.py +5 -0
  15. {readalign-1.3.2 → readalign-1.3.3}/tests/test_verify.py +3 -2
  16. {readalign-1.3.2 → readalign-1.3.3}/LICENSE +0 -0
  17. {readalign-1.3.2 → readalign-1.3.3}/README.md +0 -0
  18. {readalign-1.3.2 → readalign-1.3.3}/scripts/fetch_samples.py +0 -0
  19. {readalign-1.3.2 → readalign-1.3.3}/src/readalign/__main__.py +0 -0
  20. {readalign-1.3.2 → readalign-1.3.3}/src/readalign/audio.py +0 -0
  21. {readalign-1.3.2 → readalign-1.3.3}/src/readalign/cli.py +0 -0
  22. {readalign-1.3.2 → readalign-1.3.3}/src/readalign/clock.py +0 -0
  23. {readalign-1.3.2 → readalign-1.3.3}/src/readalign/epub.py +0 -0
  24. {readalign-1.3.2 → readalign-1.3.3}/src/readalign/errors.py +0 -0
  25. {readalign-1.3.2 → readalign-1.3.3}/src/readalign/fs.py +0 -0
  26. {readalign-1.3.2 → readalign-1.3.3}/src/readalign/members.py +0 -0
  27. {readalign-1.3.2 → readalign-1.3.3}/src/readalign/package.py +0 -0
  28. {readalign-1.3.2 → readalign-1.3.3}/src/readalign/report.py +0 -0
  29. {readalign-1.3.2 → readalign-1.3.3}/src/readalign/sentences.py +0 -0
  30. {readalign-1.3.2 → readalign-1.3.3}/src/readalign/sidecar.py +0 -0
  31. {readalign-1.3.2 → readalign-1.3.3}/src/readalign/smil.py +0 -0
  32. {readalign-1.3.2 → readalign-1.3.3}/tests/conftest.py +0 -0
  33. {readalign-1.3.2 → readalign-1.3.3}/tests/test_audio.py +0 -0
  34. {readalign-1.3.2 → readalign-1.3.3}/tests/test_epub.py +0 -0
  35. {readalign-1.3.2 → readalign-1.3.3}/tests/test_fs.py +0 -0
  36. {readalign-1.3.2 → readalign-1.3.3}/tests/test_output.py +0 -0
  37. {readalign-1.3.2 → readalign-1.3.3}/tests/test_sidecar_report.py +0 -0
  38. {readalign-1.3.2 → readalign-1.3.3}/tests/test_smil.py +0 -0
@@ -1,20 +1,20 @@
1
- __pycache__/
2
- *.py[cod]
3
- *.egg-info/
4
- .eggs/
5
- build/
6
- dist/
7
- .venv/
8
- venv/
9
- .pytest_cache/
10
- .ruff_cache/
11
- .coverage
12
- htmlcov/
13
- *.epub
14
- !examples/aesop/*.epub
15
- readalign-report.json
16
- *-sidecars/
17
- .readalign-cache/
18
- examples/output/
19
- .DS_Store
20
- Thumbs.db
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .eggs/
5
+ build/
6
+ dist/
7
+ .venv/
8
+ venv/
9
+ .pytest_cache/
10
+ .ruff_cache/
11
+ .coverage
12
+ htmlcov/
13
+ *.epub
14
+ !examples/aesop/*.epub
15
+ readalign-report.json
16
+ *-sidecars/
17
+ .readalign-cache/
18
+ examples/output/
19
+ .DS_Store
20
+ Thumbs.db
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.3.3 - 2026-12-05
4
+
5
+ - Fixed: consecutive aligned sentences clustered within 50ms of a track's end could step
6
+ backwards during monotonic clamping and fail SMIL clip validation. `enforce_monotonic` now
7
+ preserves non-decreasing starts and is shared with `--refine`, removing a separate boundary
8
+ repair path that could produce zero-length or out-of-track spans.
9
+ - Fixed: word normalisation now splits on em-dashes, en-dashes, horizontal bars, ASCII
10
+ double-dashes and slashes, and strips underscores, so phrases like `dark—the`, `1890–1910`
11
+ and `and/or` match spoken words while keeping compound hyphens (`To-morrow`) and apostrophes
12
+ intact.
13
+ - Fixed: ASR word timestamps and probabilities are clamped to finite valid bounds before
14
+ writing the transcript cache so edge-case model outputs never poison cached entries.
15
+ - Fixed: `--verify` now counts `FATAL(` lines alongside `ERROR(` in epubcheck output.
16
+ - Fixed: the sidecar directory CLI test resolves the bundled Aesop sample relative to the test
17
+ file instead of the working directory.
18
+
3
19
  ## 1.3.2 - 2026-10-25
4
20
 
5
21
  - Maintenance: Linux CI installs ffmpeg without optional recommended packages. Package
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: readalign
3
- Version: 1.3.2
3
+ Version: 1.3.3
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
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "readalign"
7
- version = "1.3.2"
7
+ version = "1.3.3"
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.2"
3
+ __version__ = "1.3.3"
@@ -270,7 +270,7 @@ def align(
270
270
  )
271
271
 
272
272
  _interpolate_gaps(sentences, sentence_spans, timed, tracks, first_match, last_match)
273
- _enforce_monotonic(timed, tracks)
273
+ enforce_monotonic(timed, tracks)
274
274
 
275
275
  result.timed = [entry for entry in timed if entry is not None]
276
276
  result.skipped = [
@@ -326,27 +326,34 @@ def _interpolate_gaps(
326
326
  )
327
327
 
328
328
 
329
- def _enforce_monotonic(timed: list[TimedSentence | None], tracks: list[AudioTrack]) -> None:
329
+ def enforce_monotonic(
330
+ timed: list[TimedSentence | None], tracks: list[AudioTrack], *, record_drift: bool = True
331
+ ) -> None:
330
332
  """Keep clips ordered, inside their own file, and never past the file's real duration.
331
333
 
332
- How far a start has to be pushed is recorded as drift: a sentence matched to the wrong
333
- occurrence of its own words is what makes the order go backwards in the first place.
334
+ When ``record_drift`` is true, how far a start has to be pushed is recorded as drift: a
335
+ sentence matched to the wrong occurrence of its own words is what makes the order go
336
+ backwards in the first place.
334
337
  """
335
338
  by_track = {track.index: track for track in tracks}
339
+ previous_start = 0.0
336
340
  previous_end = 0.0
337
341
  for entry in timed:
338
342
  if entry is None:
339
343
  continue
340
344
  track = by_track[entry.track_index]
341
345
  anchored_start = entry.start
342
- entry.start = max(entry.start, previous_end)
343
- entry.drift = round(max(entry.drift, entry.start - anchored_start), 3)
346
+ entry.start = max(entry.start, track.offset, previous_end)
347
+ if record_drift:
348
+ entry.drift = round(max(entry.drift, entry.start - anchored_start), 3)
344
349
  if entry.start >= track.end:
345
- entry.start = max(track.offset, track.end - 0.05)
350
+ entry.start = max(track.offset, previous_start, track.end - 0.05)
346
351
  entry.end = max(entry.end, entry.start + 0.05)
347
352
  if entry.end > track.end:
348
353
  entry.end = track.end
349
- entry.clamped = True
354
+ if record_drift:
355
+ entry.clamped = True
350
356
  if entry.end <= entry.start:
351
- entry.start = max(track.offset, entry.end - 0.05)
357
+ entry.start = max(track.offset, previous_start, entry.end - 0.05)
358
+ previous_start = entry.start
352
359
  previous_end = entry.end
@@ -136,13 +136,20 @@ def _transcribe_track(model, track, count, settings, *, before, total, started,
136
136
  for segment in segments:
137
137
  for word in segment.words or []:
138
138
  text = word.word.strip()
139
- if text:
140
- # float() because CTranslate2 hands back numpy scalars, which would
141
- # otherwise travel all the way into the JSON report and fail to encode.
142
- words.append(
143
- Word(text, start + float(word.start), start + float(word.end),
144
- float(word.probability))
145
- )
139
+ if not text:
140
+ continue
141
+ # float() because CTranslate2 hands back numpy scalars, which would
142
+ # otherwise travel all the way into the JSON report and fail to encode.
143
+ word_start = start + float(word.start)
144
+ word_end = start + float(word.end)
145
+ probability = float(word.probability)
146
+ if not (math.isfinite(word_start) and math.isfinite(word_end)
147
+ and math.isfinite(probability)):
148
+ continue
149
+ word_start = max(0.0, word_start)
150
+ word_end = max(word_start, word_end)
151
+ probability = min(1.0, max(0.0, probability))
152
+ words.append(Word(text, word_start, word_end, probability))
146
153
  settings.language = settings.language or detected.language
147
154
  elapsed = time.monotonic() - started
148
155
  log(f" {len(words)} words so far, {_hms(before + end)}/{_hms(total)} "
@@ -11,7 +11,7 @@ never downloaded otherwise.
11
11
 
12
12
  from __future__ import annotations
13
13
 
14
- from .align import AlignmentResult, TimedSentence
14
+ from .align import AlignmentResult, TimedSentence, enforce_monotonic
15
15
  from .audio import SAMPLE_RATE, AudioTrack, read_wav_segment
16
16
  from .errors import DependencyError
17
17
  from .textnorm import tokenize_words
@@ -151,7 +151,7 @@ def refine(
151
151
  entry.interpolated = False
152
152
  adjusted += 1
153
153
 
154
- _repair_order(result.timed, by_index)
154
+ enforce_monotonic(result.timed, tracks, record_drift=False)
155
155
  skipped = f", {failed} chunk(s) skipped" if failed else ""
156
156
  log(f" refined {adjusted} sentence boundaries{skipped}")
157
157
  return {
@@ -161,15 +161,3 @@ def refine(
161
161
  "mean_shift": round(total_shift / adjusted, 3) if adjusted else 0.0,
162
162
  "licence": LICENCE_NOTE,
163
163
  }
164
-
165
-
166
- def _repair_order(timed: list[TimedSentence], tracks: dict[int, AudioTrack]) -> None:
167
- """Keep the sequence monotonic and inside each track after boundaries moved."""
168
- previous: float | None = None
169
- for entry in timed:
170
- track = tracks[entry.track_index]
171
- entry.start = min(max(entry.start, track.offset), track.end)
172
- entry.end = min(max(entry.end, entry.start + 0.05), track.end)
173
- if previous is not None and entry.start < previous:
174
- entry.start = min(previous, entry.end - 0.05)
175
- previous = entry.end
@@ -31,6 +31,7 @@ _ROMAN_VALUES = {"i": 1, "v": 5, "x": 10, "l": 50, "c": 100, "d": 500, "m": 1000
31
31
  _ROMAN_RE = re.compile(r"^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$")
32
32
  _ORDINAL_SUFFIX_RE = re.compile(r"^(\d+)(?:st|nd|rd|th)$")
33
33
  _DIGITS_RE = re.compile(r"\d")
34
+ _WORD_SPLIT_RE = re.compile(r"[—–―/]+|-{2,}") # noqa: RUF001
34
35
 
35
36
 
36
37
  def _small_number_words(value: int) -> list[str]:
@@ -111,9 +112,15 @@ def tokenize_word(raw: str) -> list[str]:
111
112
  """Normalise one whitespace-delimited word into zero or more comparison tokens."""
112
113
  if not raw:
113
114
  return []
115
+ parts = _WORD_SPLIT_RE.split(raw)
116
+ if len(parts) > 1:
117
+ tokens: list[str] = []
118
+ for part in parts:
119
+ tokens.extend(tokenize_word(part))
120
+ return tokens
114
121
  # Roman numerals are only recognised as written in the source, before case folding,
115
122
  # so that the pronoun "I" and ordinary lowercase words are never rewritten as numbers.
116
- stripped = re.sub(r"[^\w]", "", _strip_accents(raw), flags=re.UNICODE)
123
+ stripped = re.sub(r"[^\w]|_", "", _strip_accents(raw), flags=re.UNICODE)
117
124
  if not stripped:
118
125
  return []
119
126
  if stripped.isupper():
@@ -43,8 +43,8 @@ def find_epubcheck(explicit: str | None) -> str:
43
43
 
44
44
 
45
45
  def parse_epubcheck(output: str) -> tuple[int, int]:
46
- """Count the ERROR and WARNING lines epubcheck prints, whatever its exit code says."""
47
- errors = sum(1 for line in output.splitlines() if "ERROR(" in line)
46
+ """Count the FATAL/ERROR and WARNING lines epubcheck prints, whatever its exit code says."""
47
+ errors = sum(1 for line in output.splitlines() if "FATAL(" in line or "ERROR(" in line)
48
48
  warnings = sum(1 for line in output.splitlines() if "WARNING(" in line)
49
49
  return errors, warnings
50
50
 
@@ -136,3 +136,38 @@ def test_unaligned_regions_carry_an_excerpt_of_the_book(tmp_path, monkeypatch):
136
136
  _, origins = tokenize_words(sentence.words)
137
137
  expected.extend(sentence.words[origin] for origin in origins)
138
138
  assert result.unaligned_regions[0]["excerpt"] == " ".join(expected)
139
+
140
+
141
+ def test_consecutive_sentences_near_track_end_stay_ordered_for_smil(tmp_path):
142
+ """Sentences clustered within 50ms of track end must never step backwards."""
143
+ from readalign.align import TimedSentence, enforce_monotonic
144
+ from readalign.smil import continuous_clips
145
+
146
+ _, sentences = book(tmp_path)
147
+ tracks = make_tracks([10.0])
148
+ timed = [
149
+ TimedSentence(sentences[0], 9.97, 10.0, 1.0, 1),
150
+ TimedSentence(sentences[1], 9.98, 10.0, 1.0, 1),
151
+ ]
152
+ enforce_monotonic(timed, tracks)
153
+ assert timed[0].start <= timed[1].start < timed[1].end <= tracks[0].end
154
+ clips = continuous_clips(timed, tracks)
155
+ assert clips
156
+ assert all(0.0 <= clip.start < clip.end <= 10.0 for clip in clips)
157
+
158
+
159
+ def test_enforce_monotonic_without_drift_repairs_refined_bounds(tmp_path):
160
+ from readalign.align import TimedSentence, enforce_monotonic
161
+ from readalign.smil import continuous_clips
162
+
163
+ _, sentences = book(tmp_path)
164
+ tracks = make_tracks([10.0, 10.0])
165
+ timed = [
166
+ TimedSentence(sentences[0], -0.2, 0.1, 1.0, 1),
167
+ TimedSentence(sentences[1], 10.0, 10.2, 1.0, 1),
168
+ TimedSentence(sentences[2], 9.9, 10.5, 1.0, 2),
169
+ ]
170
+ enforce_monotonic(timed, tracks, record_drift=False)
171
+ assert all(entry.drift == 0.0 and not entry.clamped for entry in timed)
172
+ clips = continuous_clips(timed, tracks)
173
+ assert len(clips) == 3
@@ -197,3 +197,37 @@ def test_a_cache_entry_that_is_old_or_broken(monkeypatch, tmp_path, mangle, cach
197
197
  assert info["cached_tracks"] == cached_tracks
198
198
  assert [word.text for word in words] == ["hello"]
199
199
  assert info["language"] == (None if cached_tracks else "en")
200
+
201
+
202
+ def test_transcribe_track_sanitizes_word_bounds_for_cache(monkeypatch, tmp_path):
203
+ """Negative starts, inverted ends or out-of-range probabilities never poison the cache."""
204
+ from types import SimpleNamespace
205
+
206
+ from readalign import audio
207
+
208
+ class FakeModel:
209
+ def transcribe(self, *_a, **_k):
210
+ words = [
211
+ SimpleNamespace(word=" hello ", start=-0.02, end=-0.01, probability=1.05),
212
+ SimpleNamespace(word="world", start=0.5, end=0.4, probability=-0.1),
213
+ SimpleNamespace(word="nanword", start=float("nan"), end=1.0, probability=0.9),
214
+ ]
215
+ return [SimpleNamespace(words=words)], SimpleNamespace(language="en")
216
+
217
+ tracks = one_track(tmp_path)
218
+ tracks[0].wav_path = str(tmp_path / "part001.wav")
219
+ monkeypatch.setattr(audio, "plan_windows", lambda track, max_s: [(0.0, track.duration)])
220
+ monkeypatch.setattr(asr, "read_wav_segment", lambda *_: b"")
221
+ settings = asr._Settings("tiny", None, True, 5, 3600.0)
222
+ words = asr._transcribe_track(
223
+ FakeModel(), tracks[0], 1, settings, before=0.0, total=10.0, started=0.0,
224
+ log=lambda *_: None,
225
+ )
226
+ assert [(w.text, w.start, w.end, w.probability) for w in words] == [
227
+ ("hello", 0.0, 0.0, 1.0),
228
+ ("world", 0.5, 0.5, 0.0),
229
+ ]
230
+ cache = tmp_path / "cache"
231
+ asr._store_cached(str(cache), "k", words, "en", log=lambda *_: None)
232
+ loaded = asr._load_cached(str(cache), "k")
233
+ assert loaded == (words, "en")
@@ -88,11 +88,14 @@ def test_sidecar_directory_cannot_contain_protected_paths(tmp_path, monkeypatch,
88
88
 
89
89
  @pytest.mark.skipif(not has_ffmpeg, reason="ffmpeg is needed")
90
90
  def test_no_sidecars_allows_input_in_sidecar_directory(tmp_path):
91
+ from pathlib import Path
92
+
91
93
  directory = tmp_path / "out-sidecars"
92
94
  directory.mkdir()
93
95
  epub = build_epub(str(directory / "book.epub"))
94
96
  original = (directory / "book.epub").read_bytes()
95
- assert main(["build", "--audio", "examples/aesop/aesop-section-37.mp3", "--epub", epub,
97
+ sample = Path(__file__).resolve().parent.parent / "examples" / "aesop" / "aesop-section-37.mp3"
98
+ assert main(["build", "--audio", str(sample), "--epub", epub,
96
99
  "--out", str(tmp_path / "out.epub"), "--no-sidecars", "--dry-run"]) == 0
97
100
  assert (directory / "book.epub").read_bytes() == original
98
101
 
@@ -20,6 +20,11 @@ from readalign.textnorm import tokenize_word, tokenize_words
20
20
  ("IV", ["four"]),
21
21
  ("I", ["i"]),
22
22
  ("—", []),
23
+ ("dark—the", ["dark", "the"]),
24
+ ("dark--the", ["dark", "the"]),
25
+ ("1890–1910", ["eighteen", "ninety", "nineteen", "ten"]), # noqa: RUF001
26
+ ("and/or", ["and", "or"]),
27
+ ("_italic_", ["italic"]),
23
28
  ],
24
29
  )
25
30
  def test_tokenize_word(raw, expected):
@@ -15,11 +15,12 @@ has_ffmpeg = shutil.which("ffmpeg") and shutil.which("ffprobe")
15
15
  def test_epubcheck_output_is_counted():
16
16
  output = (
17
17
  "Validating using EPUB version 3.3 ruleset.\n"
18
+ "FATAL(PKG-001): corrupt package\n"
18
19
  "ERROR(RSC-005): something is wrong\n"
19
20
  "WARNING(OPF-001): something is odd\n"
20
- "Messages: 1 warnings / 1 errors\n"
21
+ "Messages: 1 fatals / 1 errors / 1 warnings\n"
21
22
  )
22
- assert verify.parse_epubcheck(output) == (1, 1)
23
+ assert verify.parse_epubcheck(output) == (2, 1)
23
24
  assert verify.parse_epubcheck("") == (0, 0)
24
25
 
25
26
 
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes