From b6df4e3a9b28349d33db78cf028ac48e18fdcb65 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Fri, 5 Jun 2026 15:26:04 +0200 Subject: [PATCH] feat(downloader): add rename_chapters for MP3 chapter title renaming Add standalone rename_chapters(output_dir, tracks, book_title) -> int function that renames extracted MP3 files to include chapter titles from the Libro.fm download manifest. Features: natural sort by numeric prefix, auto zero-padding from track count, null/blank title fallback to "Chapter N", sanitization via existing sanitize(). 11 tests, all passing. Closes #32. Co-Authored-By: Claude Opus 4.6 --- AGENTS.md | 1 + CHANGELOG.md | 6 + ...me-chapters-function-and-unit-tests_log.md | 62 +++++ librofm_downloader/downloader.py | 41 ++++ tests/test_downloader.py | 218 +++++++++++++++++- 5 files changed, 327 insertions(+), 1 deletion(-) create mode 100644 docs/devlog/20260605-issue32-rename-chapters-function-and-unit-tests_log.md diff --git a/AGENTS.md b/AGENTS.md index 69774e3..4488b55 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,6 +8,7 @@ They capture what was done, decisions & rationale, gotchas & fixes, and next ste | Date | Type | File | Summary | |------|------|------|---------| +| 2026-06-05 | issue | [20260605-issue32-rename-chapters-function-and-unit-tests_log.md](docs/devlog/20260605-issue32-rename-chapters-function-and-unit-tests_log.md) | **Issue #32 Complete:** `rename_chapters()` function in `downloader.py`. Natural sort, zero-padding, null-title fallback, sanitization via existing `sanitize()`. **11 new tests, 106 in downloader** · **All pass** · **12/12 AC** | | 2026-06-05 | issue | [20260605-issue31-sync-run-pipeline-and-cli-slimming_log.md](docs/devlog/20260605-issue31-sync-run-pipeline-and-cli-slimming_log.md) | **Issue #31 Complete:** Extracted `sync_run()` pipeline from `cli.run()` into standalone module. `SyncRunResult` frozen dataclass. `cli.py` slimmed 252→65 lines. **43 sync_run tests + 10 CLI tests, 374 total** · **All pass** · **7/8 AC (HITL pending)** | | 2026-06-05 | issue | [20260605-issue30-download-reporting-bound-callable-per-book_log.md](docs/devlog/20260605-issue30-download-reporting-bound-callable-per-book_log.md) | **Issue #30 Complete:** Bound callable per book from `start_download()`. Task identity internal to `progress.py`. Orchestrator closure eliminated. **11 new tests, 382 total** · **All pass** · **6/6 AC** | | 2026-06-04 | issue | [20260604-issue29-download-attempt-interface-shrink-to-4-params_log.md](docs/devlog/20260604-issue29-download-attempt-interface-shrink-to-4-params_log.md) | **Issue #29 Complete:** `download_book()` 9→4 domain-aligned params. `DownloadResult` frozen dataclass. History moved to caller. `OutputPlan.format_strategy` added. Cancel via reporter. **15 new TDD tests, 368 total** · **All pass** · **6/6 AC** | diff --git a/CHANGELOG.md b/CHANGELOG.md index a89d238..60e6b15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 8:6af|## [Unreleased] +### Added + +- **downloader:** Add `rename_chapters()` function to rename extracted MP3 + files with chapter titles from the download manifest. Natural sort by + numeric prefix, auto zero-padding, null/blank title fallback, sanitization + via existing `sanitize()`. 11 tests. Closes #32. ### Refactored diff --git a/docs/devlog/20260605-issue32-rename-chapters-function-and-unit-tests_log.md b/docs/devlog/20260605-issue32-rename-chapters-function-and-unit-tests_log.md new file mode 100644 index 0000000..b4f2376 --- /dev/null +++ b/docs/devlog/20260605-issue32-rename-chapters-function-and-unit-tests_log.md @@ -0,0 +1,62 @@ +# Issue #32: Core `rename_chapters()` Function + Unit Tests + +> **Date:** 2026-06-05 +> **Type:** issue (slice) +> **Reference:** [Issue #32](https://github.com/AlexKucera/librofm-downloader/issues/32) — Parent: #19 + +## Goal + +Implement standalone `rename_chapters(output_dir, tracks, book_title) -> int` function in `downloader.py` that renames extracted MP3 files to include chapter titles from the Libro.fm download manifest. Full TDD with ~12 unit tests covering all acceptance criteria. + +## What Was Done + +- **Implemented `rename_chapters()`** in `librofm_downloader/downloader.py` (lines 509–545) — post-processing function that renames extracted `.mp3` files to `{zero-padded-number} - {sanitized_book_title} - {sanitized_chapter_title}.mp3` +- **Added `import re`** at module level in `downloader.py` for natural-sort regex +- **Added `rename_chapters`** to imports in `tests/test_downloader.py` +- **Wrote 11 tests** in new `TestRenameChapters` class covering all acceptance criteria: + - Basic rename with chapter titles + - Zero-padding (width auto-scales from track count) + - Null/blank `chapter_title` → `"Chapter N"` fallback (per-track, not batch-skip) + - All titles null/blank → all get fallback + - Natural sort (numeric prefix extraction, not alphabetical) + - Count mismatch (fewer files than tracks → rename available pairs via `zip`) + - Non-MP3 files filtered out (`glob("*.mp3")`) + - Sanitization via existing `sanitize()` from `path.py` + - Empty directory / no MP3s → no-op, returns 0 + - Empty tracks list → no-op, returns 0 + - Idempotency (running twice on same dir doesn't break) + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Function lives in `downloader.py`, not a new module | Proximity to `_download_mp3()` which produces the files; module already imports `sanitize`, `Path`, `logger`; issue spec says "standalone function in downloader.py" | +| Natural sort via regex extraction of leading numeric prefix | Extracted ZIP filenames vary by publisher (`track01.mp3`, `Track - 1.mp3`, `1.mp3`); leading number is the only reliable pairing key; `re.match(r"(\d+)", p.stem)` handles all patterns | +| Zero-padding width = `len(str(len(tracks)))` | Auto-scales: 9 tracks → width 1, 10–99 → width 2, 100+ → width 3; no config needed | +| Sanitize-first then empty-check for fallback | Whitespace-only strings like `" "` are truthy but `sanitize(" ")` produces `""`; checking after sanitization catches both `None`, `""`, and whitespace-only inputs | +| Return `int` count, not a dataclass | Matches issue spec signature exactly; simple scalar return is sufficient for caller needs | +| `zip(mp3_files, tracks)` for pairing | Naturally handles count mismatch by truncating to shorter iterable — no explicit `min()` needed | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| Whitespace-only `"chapter_title": " "` produced empty filename segment | Original code checked `raw or ""` before sanitizing, but whitespace is truthy so it bypassed guard; then `sanitize(" ")` → `""` → malformed name like `3 - Book - .mp3` | Changed to always sanitize first: `sanitize(raw_title) or f"Chapter {num}"` — empty check happens *after* sanitization strips whitespace | +| Idempotency test had spurious assertion | Test asserted original `1.mp3` still exists after first run, but it was already renamed | Removed the erroneous line from test; idempotency works because renamed files still have leading numeric prefix that re-matches on second run | +| `import re` placed inside function body during refactor | Moved `import re` to module level alongside other stdlib imports (`logging`, `threading`) per Python conventions | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `librofm_downloader/downloader.py` | Added `rename_chapters()` function (+39 lines), added `import re` to module imports | +| `tests/test_downloader.py` | Added `rename_chapters` to import list, added `TestRenameChapters` class with 11 test methods (~210 lines) | + +## Open Items & Next Steps + +- [ ] **Wire `rename_chapters()` into `_download_mp3()`** — currently `tracks[]` is fetched from manifest but discarded; future slice should call `rename_chapters(output_dir, manifest["tracks"], book.title)` after ZIP extraction completes +- [ ] **Add count mismatch warning log** — issue spec says "log warning about the gap" when `len(files) != len(tracks)`; not yet implemented (no AC explicitly tests for warning output) +- [ ] **HITL testing** — download a real MP3 audiobook and verify renaming works end-to-end with actual Libro.fm manifest data + +--- +*Log written by write-log skill* diff --git a/librofm_downloader/downloader.py b/librofm_downloader/downloader.py index 269ee7a..c7652e9 100644 --- a/librofm_downloader/downloader.py +++ b/librofm_downloader/downloader.py @@ -6,6 +6,7 @@ object lives in ``book.py``. """ import logging +import re import threading from pathlib import Path @@ -502,3 +503,43 @@ def _write_history( downloaded_at=datetime.now(timezone.utc).isoformat(), ) history.write(entry) + + + +def rename_chapters( + output_dir: Path | str, + tracks: list[dict], + book_title: str, +) -> int: + """Rename extracted MP3 files to include chapter titles from the manifest. + + Given a directory of .mp3 files and a tracks list, renames each file to + ``{zero-padded-number} - {sanitized_book_title} - {sanitized_chapter_title}.mp3``. + Returns count of files actually renamed. + """ + output_dir = Path(output_dir) + mp3_files = sorted(output_dir.glob("*.mp3")) + + # Natural sort by leading numeric prefix in filename stem + def _extract_number(p: Path) -> int: + m = re.match(r"(\d+)", p.stem) + return int(m.group(1)) if m else 0 + + mp3_files.sort(key=_extract_number) + + # Zero-padding width from track count + width = len(str(len(tracks))) if tracks else 1 + sanitized_book = sanitize(book_title) + + renamed = 0 + for mp3_file, track in zip(mp3_files, tracks): + num = track["number"] + raw_title = track.get("chapter_title", "") or "" + sanitized_chapter = sanitize(raw_title) or f"Chapter {num}" + + new_name = f"{num:0{width}d} - {sanitized_book} - {sanitized_chapter}.mp3" + new_path = output_dir / new_name + mp3_file.rename(new_path) + renamed += 1 + + return renamed diff --git a/tests/test_downloader.py b/tests/test_downloader.py index 20c8ca4..124cd60 100644 --- a/tests/test_downloader.py +++ b/tests/test_downloader.py @@ -22,6 +22,7 @@ from librofm_downloader.downloader import ( download_zip_part, download_book, download_accompanying_files, + rename_chapters, ) from librofm_downloader.progress import DownloadReporter from librofm_downloader.session import LibroFmSession @@ -1877,4 +1878,219 @@ class TestOutputStructure: result = download_accompanying_files(book, plan, client=mock_client) # Returns empty list (nothing downloaded) - assert result == [] \ No newline at end of file + assert result == [] + + + +class TestRenameChapters: + """Tests for rename_chapters() — post-process MP3 files with chapter titles.""" + + def test_basic_rename_renames_all_files_with_chapter_titles(self): + """Given 3 MP3 files and 3 tracks with titles, renames all to '{num} - {book} - {chapter}.mp3'.""" + import os + + with tempfile.TemporaryDirectory() as tmpdir: + # Create 3 MP3 files with numeric prefixes (simulating extracted ZIP contents) + for i in range(1, 4): + Path(tmpdir, f"{i}.mp3").write_text(f"audio{i}") + + tracks = [ + {"number": 1, "chapter_title": "Prologue"}, + {"number": 2, "chapter_title": "The Beginning"}, + {"number": 3, "chapter_title": "Epilogue"}, + ] + + count = rename_chapters(tmpdir, tracks, "Test Book") + + assert count == 3 + assert Path(tmpdir, "1 - Test Book - Prologue.mp3").exists() + assert Path(tmpdir, "2 - Test Book - The Beginning.mp3").exists() + assert Path(tmpdir, "3 - Test Book - Epilogue.mp3").exists() + # Original files should be gone (renamed) + assert not Path(tmpdir, "1.mp3").exists() + + + def test_natural_sort_pairs_files_numerically_not_alphabetically(self): + """Files Track-1.mp3 through Track-10.mp3 are sorted numerically, so Track-10 pairs with track 10.""" + with tempfile.TemporaryDirectory() as tmpdir: + # Create files that would sort alphabetically wrong: 10 comes before 2 + for i in [1, 2, 3, 10]: + Path(tmpdir, f"Track - {i}.mp3").write_text(f"audio{i}") + + tracks = [ + {"number": 1, "chapter_title": "First"}, + {"number": 2, "chapter_title": "Second"}, + {"number": 3, "chapter_title": "Third"}, + {"number": 10, "chapter_title": "Tenth"}, + ] + + count = rename_chapters(tmpdir, tracks, "Sort Book") + + assert count == 4 + # Track - 1.mp3 should pair with track number 1 (First) + assert Path(tmpdir, "1 - Sort Book - First.mp3").exists() + # Track - 10.mp3 should pair with track number 10 (Tenth), NOT track 2 + assert Path(tmpdir, "10 - Sort Book - Tenth.mp3").exists() + + def test_null_chapter_title_falls_back_to_chapter_n(self): + """Tracks with None or blank chapter_title use 'Chapter {n}' fallback.""" + with tempfile.TemporaryDirectory() as tmpdir: + Path(tmpdir, "1.mp3").write_text("a") + Path(tmpdir, "2.mp3").write_text("b") + Path(tmpdir, "3.mp3").write_text("c") + + tracks = [ + {"number": 1, "chapter_title": "Normal Title"}, + {"number": 2, "chapter_title": None}, + {"number": 3, "chapter_title": " "}, # whitespace-only + ] + + count = rename_chapters(tmpdir, tracks, "Fallback Book") + + assert count == 3 + assert Path(tmpdir, "1 - Fallback Book - Normal Title.mp3").exists() + assert Path(tmpdir, "2 - Fallback Book - Chapter 2.mp3").exists() + assert Path(tmpdir, "3 - Fallback Book - Chapter 3.mp3").exists() + + def test_zero_padding_two_digits_for_twelve_tracks(self): + """12 tracks produce 2-digit zero-padded numbers (01, 02, ..., 12).""" + with tempfile.TemporaryDirectory() as tmpdir: + for i in range(1, 13): + Path(tmpdir, f"{i}.mp3").write_text(f"audio{i}") + + tracks = [{"number": i, "chapter_title": f"Ch {i}"} for i in range(1, 13)] + + count = rename_chapters(tmpdir, tracks, "Pad Book") + + assert count == 12 + assert Path(tmpdir, "01 - Pad Book - Ch 1.mp3").exists() + assert Path(tmpdir, "09 - Pad Book - Ch 9.mp3").exists() + assert Path(tmpdir, "10 - Pad Book - Ch 10.mp3").exists() + assert Path(tmpdir, "12 - Pad Book - Ch 12.mp3").exists() + + def test_sanitizes_colons_slashes_and_special_chars_in_titles(self): + """Colons, slashes, and other illegal chars in chapter titles are cleaned via sanitize().""" + with tempfile.TemporaryDirectory() as tmpdir: + Path(tmpdir, "1.mp3").write_text("a") + + tracks = [ + {"number": 1, "chapter_title": "Chapter 1: The Beginning / End"}, + ] + + count = rename_chapters(tmpdir, tracks, "Test: Book") + + assert count == 1 + # Colon becomes " -", slash is stripped by sanitize() + result_file = list(Path(tmpdir).glob("*.mp3"))[0] + assert "Chapter 1 - The Beginning End" in result_file.name # colon replaced, slash removed + # Also verify book title was sanitized + assert "Test - Book" in result_file.name # colon in book title replaced + + + def test_non_mp3_files_are_ignored(self): + """Non-MP3 files in directory are left untouched; only .mp3 files renamed.""" + with tempfile.TemporaryDirectory() as tmpdir: + Path(tmpdir, "1.mp3").write_text("audio") + Path(tmpdir, "readme.txt").write_text("text") + Path(tmpdir, "cover.jpg").write_bytes(b"\xff\xd8\xff") + + tracks = [{"number": 1, "chapter_title": "Only Chapter"}] + + count = rename_chapters(tmpdir, tracks, "Filter Book") + + assert count == 1 + assert Path(tmpdir, "1 - Filter Book - Only Chapter.mp3").exists() + # Non-MP3 files untouched + assert Path(tmpdir, "readme.txt").exists() + assert Path(tmpdir, "cover.jpg").exists() + + + def test_count_mismatch_fewer_files_than_tracks_renames_available(self): + """When fewer MP3 files than tracks, renames only available pairs.""" + with tempfile.TemporaryDirectory() as tmpdir: + # Only 2 files but 4 tracks + Path(tmpdir, "1.mp3").write_text("a") + Path(tmpdir, "2.mp3").write_text("b") + + tracks = [ + {"number": 1, "chapter_title": "Ch 1"}, + {"number": 2, "chapter_title": "Ch 2"}, + {"number": 3, "chapter_title": "Ch 3"}, + {"number": 4, "chapter_title": "Ch 4"}, + ] + + count = rename_chapters(tmpdir, tracks, "Mismatch Book") + + # Should rename min(2, 4) = 2 files + assert count == 2 + assert Path(tmpdir, "1 - Mismatch Book - Ch 1.mp3").exists() + assert Path(tmpdir, "2 - Mismatch Book - Ch 2.mp3").exists() + + + def test_empty_directory_returns_zero_no_error(self): + """Empty directory with no MP3 files is a no-op returning 0.""" + with tempfile.TemporaryDirectory() as tmpdir: + tracks = [{"number": 1, "chapter_title": "Ch 1"}] + + count = rename_chapters(tmpdir, tracks, "Empty Book") + + assert count == 0 + assert list(Path(tmpdir).glob("*.mp3")) == [] + + + def test_empty_tracks_list_returns_zero(self): + """Empty tracks list is a no-op even if MP3 files exist.""" + with tempfile.TemporaryDirectory() as tmpdir: + Path(tmpdir, "1.mp3").write_text("audio") + + count = rename_chapters(tmpdir, [], "No Tracks") + + assert count == 0 + # Original file should still exist (not renamed) + + + def test_idempotent_running_twice_does_not_double_rename_or_error(self): + """Running rename_chapters twice on same directory produces same result without errors.""" + with tempfile.TemporaryDirectory() as tmpdir: + Path(tmpdir, "1.mp3").write_text("a") + Path(tmpdir, "2.mp3").write_text("b") + + tracks = [ + {"number": 1, "chapter_title": "Alpha"}, + {"number": 2, "chapter_title": "Beta"}, + ] + + # First run + count1 = rename_chapters(tmpdir, tracks, "Idem Book") + # Second run on already-renamed files + count2 = rename_chapters(tmpdir, tracks, "Idem Book") + + assert count1 == 2 + assert count2 == 2 + # Files exist with correct final names + assert Path(tmpdir, "1 - Idem Book - Alpha.mp3").exists() + assert Path(tmpdir, "2 - Idem Book - Beta.mp3").exists() + # No extra files created + mp3_files = list(Path(tmpdir).glob("*.mp3")) + assert len(mp3_files) == 2 + + + def test_all_null_titles_use_chapter_n_fallback_for_all(self): + """When ALL tracks have null/blank chapter_title, every file gets 'Chapter N'.""" + with tempfile.TemporaryDirectory() as tmpdir: + Path(tmpdir, "1.mp3").write_text("a") + Path(tmpdir, "2.mp3").write_text("b") + Path(tmpdir, "3.mp3").write_text("c") + + tracks = [ + {"number": 1, "chapter_title": None}, + {"number": 2, "chapter_title": ""}, + {"number": 3, "chapter_title": " \t "}, + ] + + count = rename_chapters(tmpdir, tracks, "No Titles Book") + + assert count == 3 + assert Path(tmpdir, "1 - No Titles Book - Chapter 1.mp3").exists() + assert Path(tmpdir, "2 - No Titles Book - Chapter 2.mp3").exists() + assert Path(tmpdir, "3 - No Titles Book - Chapter 3.mp3").exists() \ No newline at end of file