diff --git a/AGENTS.md b/AGENTS.md index 7678fd0..7265ff0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,7 +11,8 @@ the other `docs/` files for architecture, decisions, workflows, and UI detail. - Python package: `juice_lyrics` - Distribution: `juice-wrld-lyrics` - XDG storage namespace: `juice-lyrics` (do not rename or duplicate it) -- Current beta release: `2.0.0b1` / tag `v2.0.0b1` +- Current beta release: `2.0.0b2` / tag `v2.0.0b2` +- Previous immutable fallback: `2.0.0b1` / tag `v2.0.0b1` - Active development branch: `main` - Purpose: a Linux CLI/TUI for a local Juice WRLD library, catalogue browsing, safe lyric maintenance, downloads, backups, and optional rmpc integration. @@ -36,6 +37,9 @@ the other `docs/` files for architecture, decisions, workflows, and UI detail. validation, checksums, resume safety, and atomic finalization. - Do not make normal Sync modify audio, lyrics, backups, downloads, or rmpc configuration. +- The local lyrics-search index is rebuildable cache data only. Search and + indexing stay offline and must never modify media, sidecars, state, backups, + downloads, catalogue identity, or rmpc configuration. ## Supported media and lyrics @@ -58,6 +62,7 @@ the other `docs/` files for architecture, decisions, workflows, and UI detail. - Read-only metadata proposals: `src/juice_lyrics/services/metadata_audit.py` - Transactional metadata writer foundation: `src/juice_lyrics/services/metadata_repair.py` - Read-only diagnostics/support reports: `src/juice_lyrics/services/doctor.py` +- Offline local lyrics search: `src/juice_lyrics/services/lyrics_search.py` - Shell completion generation: `src/juice_lyrics/services/shell_completion.py` - Matching/identity: `src/juice_lyrics/library/matching.py` and `src/juice_lyrics/services/library_identity.py` diff --git a/README.md b/README.md index 87833b9..c0a6969 100644 --- a/README.md +++ b/README.md @@ -1,231 +1,265 @@ # 999 -[![GitHub release](https://img.shields.io/github/v/release/NotAI-fr/juice-lyrics?include_prereleases&label=release)](https://github.com/NotAI-fr/juice-lyrics/releases/tag/v2.0.0b1) +![999 dashboard with synthetic demonstration data](docs/assets/screenshots/dashboard-synthetic.png) + +[![GitHub release](https://img.shields.io/github/v/release/NotAI-fr/juice-lyrics?include_prereleases&label=current%20beta)](https://github.com/NotAI-fr/juice-lyrics/releases/tag/v2.0.0b2) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) -`999` is a keyboard-first Linux CLI and TUI for managing a local Juice WRLD -music library. It combines catalogue browsing, conservative track matching, -lyrics maintenance, explicit downloads, backups, and optional rmpc integration -without trying to replace your music player. +A keyboard-first Linux app for browsing, understanding, and maintaining a +local Juice WRLD music library. -> **Current release:** [`2.0.0b1`](https://github.com/NotAI-fr/juice-lyrics/releases/tag/v2.0.0b1) -> is a beta. Keep an independent backup of valuable media and review every -> proposed metadata or lyric change before applying it. +## Quick Install -999 is an unofficial fan-made project. It is not affiliated with or endorsed -by Juice WRLD's estate, record labels, or the Juice WRLD API. This repository -contains no music or lyric collection. +Requires Linux, Python 3.11 or newer, and +[`pipx`](https://pipx.pypa.io/) on your `PATH`. -## Screenshots +### Recommended: 2.0.0b2 -![999 dashboard with synthetic demonstration data](docs/assets/screenshots/dashboard-synthetic.png) +Install the current recommended beta directly from its immutable Git tag: -_The image above was rendered by the real TUI using synthetic counts and a -generic path. Additional real screenshots will be added after manual capture; -the planned filenames are documented in -[`docs/assets/screenshots/README.md`](docs/assets/screenshots/README.md)._ +```bash +pipx install --force "git+https://github.com/NotAI-fr/juice-lyrics.git@v2.0.0b2" +``` -## Highlights +You do not need to clone the repository. Check the install, then launch 999: -- Browse and search the Juice WRLD catalogue without downloading anything. -- Sync a local library incrementally while leaving ambiguous matches Unknown. -- Review Issues, exact/probable Duplicates, and Missing Library recordings. -- Manually match and lock catalogue identities when automatic matching should - not decide. -- Preview selected metadata repairs before a cancel-first confirmation. -- Maintain embedded lyrics and adjacent timed `.lrc` files without converting - or re-encoding audio. -- Queue downloads explicitly; adding an item never starts a download. -- Create backups before media metadata changes and verify every result. -- Diagnose installation, configuration, storage, catalogue, and optional rmpc - integration with the read-only `999 doctor` command. +```bash +999 --version +999 doctor +999 +``` -## Supported media +### Previous stable fallback: 2.0.0b1 -| Format | Local metadata and lyrics | Synchronized lyrics | -|---|---|---| -| MP3 | ID3 metadata, USLT and SYLT | ID3 SYLT and adjacent `.lrc` | -| FLAC | Vorbis metadata and plain `LYRICS` | Adjacent `.lrc` | -| M4A | MP4 metadata and plain `©lyr` | Adjacent `.lrc` | +If `2.0.0b2` gives you trouble, switch to the previous known-good beta. The +published `v2.0.0b1` tag and release remain immutable: -999 never converts audio. A timed sidecar always uses the audio file's own -basename and directory, such as `song.flac` with `song.lrc`. +```bash +pipx install --force "git+https://github.com/NotAI-fr/juice-lyrics.git@v2.0.0b1" +``` -## Install +Use `pipx install --force` with either command to switch between versions. +See [Troubleshooting](#troubleshooting) or [Uninstall](#uninstall) for help. + +## Why 999? -Requirements: +999 brings catalogue discovery, downloads, local-library health, lyrics, +matching, careful repairs, and diagnostics into one terminal interface. It is +designed to replace a pile of one-off file and tagging scripts—not your music +player. -- a supported Linux system; -- Python 3.11 or newer; -- [`pipx`](https://pipx.pypa.io/) installed and on `PATH`. +## Features -After this repository is public, install the immutable beta wheel directly -from its GitHub release—no clone or GitHub account is required: +### 🔎 Find and discover -```bash -pipx install "https://github.com/NotAI-fr/juice-lyrics/releases/download/v2.0.0b1/juice_wrld_lyrics-2.0.0b1-py3-none-any.whl" -999 --version -999 doctor -``` +**Search by Lyrics** — Remember a line but not the title? Open **Library → +Search Lyrics** and type part of the lyric. 999 searches embedded MP3, FLAC, +and M4A lyrics plus adjacent plain or timed `.lrc` files; timed matches can +show their real timestamp. Search is local, offline, and does not rescan media +as you type. -To replace an older installation with this exact beta: +Lyrics Search is part of the current `2.0.0b2` beta. It is **not** included in +the previous `v2.0.0b1` fallback release. -```bash -pipx install --force "https://github.com/NotAI-fr/juice-lyrics/releases/download/v2.0.0b1/juice_wrld_lyrics-2.0.0b1-py3-none-any.whl" -``` +**Browse and Catalogue Search** — Search and filter the Juice WRLD catalogue, +inspect recording details, and connect local files with the correct catalogue +recording. Local-library features remain useful if the catalogue service is +offline; catalogue-backed results naturally require it to be available. -An immutable Git-tag install is also available: +**Missing Library** — Compare confirmed local catalogue identities with the +catalogue to see recordings that appear to be missing. Unknown local tracks +are kept separate, and a selected missing recording can be added to the normal +download queue without starting a download. -```bash -pipx install "git+https://github.com/NotAI-fr/juice-lyrics.git@v2.0.0b1" -``` +### 📚 Manage your library -The legacy `juice-lyrics` command remains available. Both commands use the -existing `juice-lyrics` XDG namespace so upgrades do not create a second state -tree. +**Local Library** — Scan and manage a local Juice WRLD collection from one +place. Library inspection, metadata, and lyric workflows support MP3, FLAC, +and M4A without converting the audio. -## Quick start +**Library Sync** — Detect new, changed, unchanged, and removed tracks, then +update 999's local view of the collection. Sync reuses what it already knows +about unchanged files and does not rewrite audio, embedded lyrics, sidecars, +backups, downloads, or rmpc configuration. -Launch the interface: +**Lyrics and LRC Management** — Inspect, verify, preview, and explicitly apply +supported lyric maintenance. 999 handles embedded plain and synchronized MP3 +lyrics, plain FLAC and M4A lyrics, and adjacent timed `.lrc` files where +supported. -```bash -999 -``` +**Downloads and Queue** — Add one or several catalogue selections to a durable +queue, review them, then explicitly start one download or the eligible queue. +Failed items remain visible for retry, and adding an item never starts a +download. Acquisition and download post-processing are currently MP3-focused. -The default library path can be changed with a starter configuration: +**Library Issues** — See catalogue identity, lyric, verification, metadata, +and state follow-ups together, with one combined entry per affected track. +Warnings and Unknown identities may simply need review; they do not +automatically mean the audio file is damaged. -```bash -999 config init -999 config show -``` +**Manual Catalogue Matching** — When automatic matching is uncertain, choose +the correct catalogue recording yourself and lock that identity to the current +file. Normal Sync preserves a valid manual choice until you explicitly unlock +it or the audio is replaced. -Or override it for one command: +**Duplicate Detection** — Review exact file copies and conservative probable +recording matches with the evidence and paths shown. Detection is read-only: +999 never automatically deletes, merges, moves, retags, or replaces files. -```bash -999 --path ~/Music/Juice-WRLD status -``` +### 🛡️ Repair and safety + +**Metadata Repair** — Preview supported title, artist, album, and track-number +proposals for a confirmed track, then select only the fields you want to +change. Applying a repair creates a full audio backup, writes and verifies a +temporary copy, and preserves unrelated media data. Replacement and state +updates use rollback safeguards; if automatic recovery cannot complete, the +retained backup is clearly surfaced for recovery. + +**Backups and Restore** — Important media-mutation workflows create timestamped +backups before changing a file. Browse valid backups in the Library and restore +one through an explicit confirmation; scripted recovery is also available with +`999 restore`. -Press `?` anywhere in the TUI for the complete key map. The normal routine is: +### 🩺 Diagnostics and integration + +**Doctor and Support Reports** — `999 doctor` performs bounded, read-only +checks of the installation, configuration, local storage, one small catalogue +request, backups, and optional player integration. It reports clear PASS, +WARN, and FAIL results. Support reports omit song lists and state contents and +redact home paths and common credential forms by default; always review one +before sharing it. + +**Optional rmpc Integration** — 999 can check rmpc and explicitly configure it +to use adjacent timed lyric sidecars. rmpc is not required, and normal startup +or Library Sync does not rewrite its configuration. Plain lyrics without +timestamps do not appear as synchronized lyrics in rmpc's Lyrics pane. + +### Supported local formats + +| Format | Embedded lyrics | Timed lyrics | +| --- | --- | --- | +| MP3 | ID3 USLT and SYLT | ID3 SYLT and adjacent `.lrc` | +| FLAC | Vorbis `LYRICS` | Adjacent `.lrc` | +| M4A | MP4 `©lyr` | Adjacent `.lrc` | + +An adjacent sidecar uses the audio file's basename and directory, such as +`song.flac` with `song.lrc`. + +## Screenshots + +The dashboard at the top of this page was rendered by the real TUI using +synthetic data and a generic path. It is the only screenshot currently checked +into the repository, so the planned real captures below are deliberately not +linked yet: + +- `dashboard.png` — overview and library health; +- `browse-search.png` — catalogue browsing and search; +- `library-health.png` — local collection status; +- `issues.png` — combined follow-ups; +- `downloads-queue.png` — explicit download queue; +- `metadata-repair-preview.png` — review before applying a repair; +- `lyrics-search.png` — offline lyric phrase search and timed results. + +Lyrics Search will be featured prominently when the real captures are added. +See the [screenshot plan](docs/assets/screenshots/README.md) for capture rules. + +## Usage + +Press `?` anywhere in the TUI for the complete key map. The usual Library +routine is: ```text Library → s Sync Library → a Issues ``` -Sync records new and changed paths, retires removed paths, and attempts only -conservative catalogue matches. It does **not** edit audio, lyrics, backups, -downloads, or rmpc configuration. +To find a local track from remembered words: -## Main TUI workflows - -| Area | Typical workflow | -|---|---| -| Browse | Search/filter → inspect details → Add to queue | -| Downloads | Review queue → confirm one item or the eligible queue → inspect result/retry | -| Library | Sync → filter/select → inspect health and identity | -| Issues | Review genuine errors, lyric follow-ups, stale state, and Unknown identities | -| Manual match | Search → select an exact recording → lock; unlock later if needed | -| Duplicates | Review evidence and paths only; 999 never deletes or merges files | -| Metadata repair | Preview → choose individual fields → confirm → verify backup/result | -| Missing Library | Compare confirmed catalogue IDs → optionally add one recording to the queue | +```text +Library → f Search Lyrics → type a phrase → Enter +``` -The command line remains useful for diagnostics and scripting: +Useful read-only command-line checks: ```bash +999 --version 999 status -999 search "Bandit" -999 info "10 Feet" +999 doctor 999 guide ``` -Acquisition is always explicit: +Catalogue search is also available from the command line when the service is +available: ```bash -999 acquire search "Rental" -999 acquire add "Rental" --index 1 -999 acquire jobs -999 acquire run +999 search "Bandit" +999 info "10 Feet" ``` -## Safety and backups +To inspect a different library for one command: -- Automatic matching prefers Unknown over a risky confident identity. -- Normal Library Sync never modifies media or starts downloads. -- Metadata repair changes only selected fields after a preview and confirmation. -- Before an in-place media metadata change, 999 creates a full backup under - `~/.local/share/juice-lyrics/backups/`. -- Post-write verification checks that encoded audio, artwork, lyrics, - unrelated tags, and adjacent sidecars were preserved. A failed write is - rolled back. -- State and `.lrc` writes are atomic, and state updates detect conflicting - concurrent changes. -- Duplicate results are evidence for review only—never an instruction to - delete, move, merge, or replace media. +```bash +999 --path ~/Music/Juice-WRLD status +``` + +The detailed [user guide](docs/USER_GUIDE.md) covers configuration, keyboard +controls, acquisition, recovery, and advanced commands. -## Doctor and support reports +## Troubleshooting -Run bounded, read-only diagnostics with: +Confirm which build is installed, then run the read-only diagnostic: ```bash +999 --version 999 doctor +pipx list ``` -If an issue needs more detail, generate a sanitized report and inspect it -before sharing: +To create a report you can inspect before sharing: ```bash +999 doctor --support-report 999 doctor --save-report ./999-support.json ``` -Doctor does not run Sync, enumerate the full catalogue, modify application -data, invoke rmpc/MPD, or inspect every audio file. Support reports redact home -paths and common credential forms and exclude song lists and state contents. +If the current beta is not working for you, use the `v2.0.0b1` fallback +command in [Quick Install](#previous-stable-fallback-200b1). -## Known beta limitations +Current limitations: -- Acquisition and download post-processing are currently MP3-focused; local - library inspection, metadata, lyrics, backup, and restore support MP3, FLAC, - and M4A. +- Acquisition and download post-processing are MP3-focused; local library, + metadata, lyrics, backup, and restore workflows support MP3, FLAC, and M4A. - Active download cancellation is not implemented. - Configuration editing is primarily command-line based. -- Visual polish has not been exhaustively reviewed across terminal emulators. -- Fish completion generation is tested, but this beta did not receive a local - Fish runtime syntax pass. -- Independent second-machine pipx acceptance and optional live rmpc - notification remain limited. - -See the [2.0.0b1 release notes](https://github.com/NotAI-fr/juice-lyrics/releases/tag/v2.0.0b1) -for the accepted beta scope. +- Appearance can vary between terminal emulators. -## Reporting issues +For deeper detail, see the [user guide](docs/USER_GUIDE.md), +[changelog](docs/CHANGELOG.md), and +[development guide](docs/DEVELOPMENT.md). -Use the [GitHub issue tracker](https://github.com/NotAI-fr/juice-lyrics/issues) -for reproducible bugs. Include the `999 --version` output, Linux distribution, -installation method, steps to reproduce, expected result, and actual result. +## Uninstall -Please do **not** attach music, lyric collections, credentials, tokens, private -configuration/state files, or unreviewed support reports. Use synthetic names -and paths where possible. - -## Documentation and development +```bash +pipx uninstall juice-wrld-lyrics +``` -- [User guide](docs/USER_GUIDE.md) -- [Changelog](docs/CHANGELOG.md) -- [Architecture](docs/ARCHITECTURE.md) -- [Development guide](docs/DEVELOPMENT.md) +Uninstalling the pipx app removes the command and its isolated environment. It +does not intentionally remove your music or normal `juice-lyrics` library, +configuration, state, cache, or backups. -For a development checkout: +## Reporting bugs -```bash -python -m venv .venv -. .venv/bin/activate -pip install -e . -pytest -q -``` +Use the [GitHub issue tracker](https://github.com/NotAI-fr/juice-lyrics/issues). +Include `999 --version`, your Linux distribution, installation method, steps +to reproduce, expected result, and actual result. -## License +Do not attach music, lyric collections, credentials, tokens, private +configuration/state files, or unreviewed support reports. Prefer synthetic +names and paths. -999 is available under the [MIT License](LICENSE). +999 is an unofficial fan-made project. It is not affiliated with or endorsed +by Juice WRLD's estate, record labels, or the Juice WRLD API. This repository +contains no music or lyric collection. -Users are responsible for the media, lyrics, and services they access and for -complying with applicable law and service terms. The project does not grant -rights to Juice WRLD recordings, artwork, or lyrics. +999 is available under the [MIT License](LICENSE). Users are responsible for +the media, lyrics, and services they access and for complying with applicable +law and service terms. diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 616832e..8aa50e9 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -4,6 +4,26 @@ This project follows [Semantic Versioning](https://semver.org/) and uses PEP 440-compatible Python versions. Dates are added only when a release is published. +## [2.0.0b2] - 2026-09-28 + +This beta promotes the offline Lyrics Search experiment into the main product. + +### Library and lyrics + +- Added local phrase search across embedded MP3, FLAC, and M4A lyrics and + adjacent plain or timed LRC files. Timed LRC matches retain their timestamps. +- Added a rebuildable incremental lyrics index so unchanged tracks are reused, + changed audio or sidecars are refreshed individually, and removed tracks + disappear from results. +- Kept Lyrics Search offline and read-only for media, lyrics, state, backups, + downloads, and player configuration. + +### Documentation and installation + +- Promoted `2.0.0b2` as the recommended beta with direct tag-based pipx install + and troubleshooting guidance. +- Kept `v2.0.0b1` available as the previous immutable fallback. + ## [2.0.0b1] - 2026-09-25 This is the first beta release of the redesigned `999` product. @@ -74,5 +94,6 @@ This is the first beta release of the redesigned `999` product. - Established the initial API, scanner, matching, lyrics, rmpc, backup, configuration, state, and acquisition service boundaries. +[2.0.0b2]: https://github.com/NotAI-fr/juice-lyrics/releases/tag/v2.0.0b2 [2.0.0b1]: https://github.com/NotAI-fr/juice-lyrics/releases/tag/v2.0.0b1 [1.4.0]: https://github.com/NotAI-fr/juice-lyrics/releases/tag/v1.4.0-backend-complete diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 1e0b455..8bd3320 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -2,8 +2,9 @@ ## Baseline -The `main` branch contains the current beta. `v1.4.0-backend-complete` remains -the previous stable tag, and `v2.0.0b1` is the current beta release tag. +The `main` branch contains the current product. `v2.0.0b2` is the current +recommended beta release; `v2.0.0b1` remains the previous immutable fallback. +`v1.4.0-backend-complete` is an older stable tag. Run: @@ -75,7 +76,7 @@ For a deterministic pipx installation that does not depend on the checkout after installation: ```bash -pipx install --force "https://github.com/NotAI-fr/juice-lyrics/releases/download/v2.0.0b1/juice_wrld_lyrics-2.0.0b1-py3-none-any.whl" +pipx install --force "git+https://github.com/NotAI-fr/juice-lyrics.git@v2.0.0b2" hash -r command -v 999 999 --version diff --git a/docs/PROJECT_STATE.md b/docs/PROJECT_STATE.md index 4942de0..bf4e04d 100644 --- a/docs/PROJECT_STATE.md +++ b/docs/PROJECT_STATE.md @@ -5,19 +5,55 @@ Sync, manual catalogue locking, snapshot-backed Library Issues, read-only duplicate review, and safe metadata repair are integrated. Read the code and tests if a later working tree disagrees with this document. +## Current release: 2.0.0b2 + +`main` is the current product line. Published beta `v2.0.0b2` includes +**Search Lyrics**, promoted from the accepted `feature/lyrics-search` +development branch. That branch may remain temporarily for history/reference. +The previous beta `v2.0.0b1` remains an immutable, published fallback. + +In Library, `f` opens **Search Lyrics**. Typing updates one logical result per +track; arrows navigate, Enter opens that track's Library details, and Escape +returns. Results include the first useful matching line, nearby context, a +compact hit count, and the real timestamp when the chosen representation is +timed. + +Search reads the existing MP3 ID3 USLT/SYLT, FLAC Vorbis `LYRICS`, M4A `©lyr`, +and authoritative adjacent-LRC sources through the shared lyric readers and LRC +parser. Matching is substring/phrase based after case, whitespace, apostrophe, +and ordinary punctuation normalization; it is deliberately not fuzzy or +semantic. Equivalent embedded and sidecar lines produce one track result, with +the adjacent LRC representation preferred so timing is retained. + +The rebuildable `lyrics-search-index-v1.json` lives under the existing XDG +cache namespace, never in authoritative state. It is built lazily on first +search from the current Library snapshot. Audio and sidecar replacement-aware +fingerprints reuse unchanged entries, re-read only new or changed tracks, +invalidate a track after either audio or LRC changes, and discard removed +paths. Corrupt, incompatible, or other-library cache data rebuilds safely. +Each query runs only against the loaded in-memory index and performs no media +read, scan, Sync, catalogue/API request, download, or mutation. + +Lyrics Search has no CLI command; it is available in the TUI and through the +shared search service. It is included in `v2.0.0b2` and is not part of the +previous `v2.0.0b1` fallback. + ## Repository checkpoint - Repository: the current `juice-lyrics` checkout -- Active development branch: `main`; `v2-redesign` is retained at the accepted - release-candidate history. +- Active product branch: `main`. +- Accepted Lyrics Search history: `feature/lyrics-search` remains available + temporarily as a reference branch. - Previous stable tag: `v1.4.0-backend-complete` - Product/primary executable: `999` - Compatibility executable: `juice-lyrics` - Python package: `juice_lyrics` - Distribution: `juice-wrld-lyrics` - XDG storage namespace: `juice-lyrics` -- Released beta: `2.0.0b1`, annotated tag `v2.0.0b1`, release commit - `1d56661`, published as a GitHub pre-release on 2026-09-25. +- Current recommended beta: `2.0.0b2`, annotated tag `v2.0.0b2` on the + accepted `main` release commit, published as a GitHub pre-release. +- Previous immutable fallback: `2.0.0b1`, annotated tag `v2.0.0b1`, release + commit `1d56661`, published as a GitHub pre-release on 2026-09-25. - Public-launch preparation on 2026-09-26 audited the current tree and all reachable Git history for credential signatures, private URLs, host-specific paths, application data, media, and generated artifacts. No credential, @@ -443,8 +479,9 @@ The installable distribution remains `juice-wrld-lyrics`; its primary console script is `999`, the `juice-lyrics` console script remains a compatibility alias, and the import/XDG namespaces remain `juice_lyrics` and `juice-lyrics`. The package version has one code authority (`juice_lyrics.__version__`) and is -resolved dynamically into wheel/sdist metadata. The current PEP 440 beta -version is `2.0.0b1`, published from the immutable `v2.0.0b1` tag. +resolved dynamically into wheel/sdist metadata. Current version `2.0.0b2` is +published from `main` at tag `v2.0.0b2`; `2.0.0b1` remains the immutable +fallback at tag `v2.0.0b1`. `python -m build` produces a platform-independent wheel and a source distribution containing the runtime Python packages, README, license, and @@ -453,11 +490,11 @@ generated bytecode are excluded. Runtime UI styling and completion templates are Python resources, so there are no separate package-data files or checkout paths required after installation. -The normal beta pipx install uses the immutable GitHub release wheel or -`v2.0.0b1` tag; repeat the same command with `--force` to replace a stale -installed snapshot. Editable installation is documented as a development -workflow only. Installing or uninstalling the distribution does not rename or -delete existing `juice-lyrics` XDG data. +The recommended beta pipx install uses the immutable `v2.0.0b2` Git tag; the +previous `v2.0.0b1` tag remains available as fallback. Repeat either command +with `--force` to switch an installed snapshot. Editable installation is a +development workflow only. Installing or uninstalling the distribution does +not rename or intentionally delete existing `juice-lyrics` XDG user data. Acceptance also corrected Doctor's executable-location probe: an explicitly invoked isolated `999`/`juice-lyrics` script is now reported instead of a stale @@ -467,33 +504,29 @@ the acceptance host does not have Fish installed for an external syntax pass. ## GitHub and beta readiness -The branch README now leads with beta status, the normal user workflow, an -actual TUI screenshot rendered from synthetic data, safety boundaries, and -source-independent installation guidance. It clearly identifies the project as -unofficial and states that no music or lyrics are distributed. The screenshot -contains only generic paths/counts and no real user data. +The main README now recommends `2.0.0b2` by immutable tag, identifies +`v2.0.0b1` as the previous fallback, explains the major user-facing features, +and includes troubleshooting, uninstall, reporting, and screenshot guidance. +Its linked TUI image uses synthetic data and contains no real user information. -`docs/CHANGELOG.md` has one coherent `2.0.0b1` prerelease section instead of -several competing Unreleased milestone headings. The executable release gate is +`docs/CHANGELOG.md` records both published beta releases. The executable release gate is `docs/BETA_RELEASE_CHECKLIST.md`: it covers version/date consistency, clean artifacts, isolated installs, manual media safety acceptance, privacy review, release notes/checksums, and explicit stop conditions. -GitHub's default branch is `main`, now containing the reviewed v2 history from -PR #1. The annotated `v2.0.0b1` tag points to merge commit `1d56661`, and the -GitHub release is an explicit pre-release with the wheel, sdist, and -`SHA256SUMS` attached. Downloaded release assets matched the published hashes. -The `v2-redesign` branch remains available. The repository description/topics -are populated, Issues are enabled, and GitHub detects the MIT license. The -repository remains private by explicit release decision; no package-index -publication occurred. - -The public-facing README now installs the immutable release wheel directly, -so a future public user needs neither a clone nor a GitHub account. It includes -the beta scope, supported formats, core workflows, safety model, Doctor, -limitations, reporting guidance, license, and disclaimer without duplicating -the detailed manuals. A privacy-conscious bug-report form and a sanitized -screenshot capture plan are present. Visibility has not been changed. +GitHub's default branch is `main`, which contains the accepted Lyrics Search +product and the `v2.0.0b2` release. Both beta releases are pre-releases with +their wheel, sdist, and `SHA256SUMS` attached. The `v2.0.0b1` tag and release +remain unchanged. The repository description/topics are populated, Issues are +enabled, and GitHub detects the MIT license. No package-index publication +occurred. + +The public-facing README installs directly from immutable beta tags through +pipx, so users do not need to clone the repository. It includes the beta +status, supported formats, core workflows, safety model, Doctor, limitations, +reporting guidance, license, and disclaimer without duplicating detailed +manuals. A privacy-conscious bug-report form and a sanitized screenshot plan +are present. ## Final performance and reliability acceptance diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index e92543a..57dc3f0 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -15,9 +15,17 @@ Advanced repair and recovery remain available without crowding routine use. ## Current sequence -1. Make the repository public only after the explicit final visibility action. -2. Collect beta feedback without weakening safety or conservative matching. -3. Prioritize demonstrated reliability and usability defects. +1. Collect `2.0.0b2` beta feedback without weakening safety or conservative + matching. +2. Prioritize demonstrated reliability and usability defects. + +## Released beta: local lyrics search + +`2.0.0b2` adds Library → `f` → **Search Lyrics** over existing embedded +MP3/FLAC/M4A lyrics and adjacent LRC files. It uses a rebuildable XDG cache +with incremental audio/sidecar fingerprint invalidation; query typing is +in-memory and offline. The previous `v2.0.0b1` release remains immutable and +available as the fallback. Do not force ambiguous tracks into identities. Do not combine these milestones into a broad rewrite. Each milestone should preserve the safety invariants in diff --git a/docs/UI_DESIGN.md b/docs/UI_DESIGN.md index 9f63bc3..cdbcc48 100644 --- a/docs/UI_DESIGN.md +++ b/docs/UI_DESIGN.md @@ -280,6 +280,7 @@ Actions: s Sync Library +f Search Lyrics a Issues g Missing Library d Duplicates @@ -388,7 +389,7 @@ movement, details, and the main action for each section. Core bindings: | --- | --- | | Global | `1`–`5` sections, `?` Help, `q` Quit, `Esc` back/close, `r` refresh | | Browse | `↑`/`↓` move, `Enter` details, `/` search, `Space` mark, `a` add, `M` mark page, `u` clear marks | -| Library | `↑`/`↓` move, `Enter` details, `s` Sync Library, `a` Issues, `g` Missing Library, `d` Duplicates, `e` metadata repair, `c` manual match; `u` unlock, `m`, `r`, `v`, `b`, `p` are secondary | +| Library | `↑`/`↓` move, `Enter` details, `s` Sync Library, `f` Search Lyrics, `a` Issues, `g` Missing Library, `d` Duplicates, `e` metadata repair, `c` manual match; `u` unlock, `m`, `r`, `v`, `b`, `p` are secondary | | Downloads | `↑`/`↓` move, `Enter` details, `d` selected download, `t` retry, `A` whole queue | | Settings | `↑`/`↓` inspect, `PgUp`/`PgDn` scroll, `r` refresh | diff --git a/docs/USER_FLOWS.md b/docs/USER_FLOWS.md index 65643ad..dacb9a1 100644 --- a/docs/USER_FLOWS.md +++ b/docs/USER_FLOWS.md @@ -361,6 +361,8 @@ Actions: s Sync Library +f Search Lyrics (offline, unreleased) + a Issues g Missing Library @@ -381,6 +383,11 @@ enter Details; l refresh selected lyrics c Match manually; u unlock manual match +Search Lyrics accepts remembered words or a phrase, updates from the in-memory +local index while typing, uses arrows to navigate, opens the corresponding +Library track with Enter, and returns with Escape. It never contacts the +catalogue or changes media, lyrics, sidecars, or state. + --- diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md index f446366..2a78d9d 100644 --- a/docs/USER_GUIDE.md +++ b/docs/USER_GUIDE.md @@ -58,6 +58,7 @@ adjacent `.lrc`. Open `999`, choose **Library**, and use: * **Sync Library** (`s`) for the normal update: discover MP3, FLAC, and M4A changes, retire known removed entries, and identify safe catalogue matches without changing audio or lyrics; +* **Search Lyrics** (`f`) to find a local track from remembered lyric words, entirely offline; * **Issues** (`a`) to see only tracks still needing a decision or repair; * **Duplicates** (`d`) to review exact file copies and conservative probable recordings without changing anything; * **Missing Library** (`g`) to compare confirmed local recording IDs with the paginated catalogue and optionally queue one exact recording; @@ -80,6 +81,26 @@ Audio, embedded lyrics, sidecars, audio backups, and rmpc configuration are not changed. If the catalogue is unavailable, local health remains usable and the track stays **Unknown**. +### Search local lyrics (2.0.0b2) + +Press `f` in Library and type remembered words or a +phrase. Results update as you type. Use ↑/↓ to choose a track, Enter to return +to that track's Library details, or Escape to return without selecting. + +Search covers embedded MP3, FLAC, and M4A lyrics plus adjacent plain or timed +`.lrc` text. It ignores case, repeated whitespace, apostrophe differences, and +ordinary punctuation, then performs a predictable substring match. It does not +guess similar wording. One row is shown per track even when a chorus matches +several times. If embedded text duplicates an adjacent LRC line, the LRC form +is shown so its real timestamp is retained. + +The first search lazily refreshes a rebuildable cache. Later openings reuse +unchanged tracks; changed audio or LRC files are re-read individually and +removed tracks disappear. Typing never rescans media. Search makes no catalogue +or API request and does not run Sync or modify audio, lyrics, state, backups, +downloads, or rmpc configuration. This feature is included in `v2.0.0b2`; it +is not part of the previous `v2.0.0b1` fallback. + Duplicates opens immediately from the current Library snapshot. Exact groups share the same recorded whole-file SHA-256. Probable groups use compatible catalogue identity, duration, title, artist, and recording-version evidence. diff --git a/docs/assets/screenshots/README.md b/docs/assets/screenshots/README.md index 7fc7cf3..ac1e469 100644 --- a/docs/assets/screenshots/README.md +++ b/docs/assets/screenshots/README.md @@ -20,6 +20,8 @@ using synthetic data. The following manually captured images are still wanted: private download URL visible. 6. `metadata-repair-preview.png` — A preview before confirmation, using a disposable file and generic metadata. +7. `lyrics-search.png` — Offline local lyric phrase results, including a timed + LRC match with its real timestamp, using disposable media. Use a consistent terminal theme and crop away unrelated desktop content. Check each image visually and search its metadata before linking it from the main diff --git a/src/juice_lyrics/__init__.py b/src/juice_lyrics/__init__.py index 9b8d3ee..cb3c238 100644 --- a/src/juice_lyrics/__init__.py +++ b/src/juice_lyrics/__init__.py @@ -1 +1 @@ -__version__ = "2.0.0b1" +__version__ = "2.0.0b2" diff --git a/src/juice_lyrics/config/settings.py b/src/juice_lyrics/config/settings.py index 409b766..0b709c8 100644 --- a/src/juice_lyrics/config/settings.py +++ b/src/juice_lyrics/config/settings.py @@ -29,6 +29,7 @@ def xdg_dir(name: str, fallback: Path) -> Path: DATA_HOME = xdg_dir("XDG_DATA_HOME", Path.home() / ".local" / "share") CONFIG_FILE = CONFIG_HOME / STORAGE_NAMESPACE / "config.toml" CACHE_DIR = CACHE_HOME / STORAGE_NAMESPACE +LYRICS_SEARCH_INDEX = CACHE_DIR / "lyrics-search-index-v1.json" DATA_DIR = DATA_HOME / STORAGE_NAMESPACE BACKUP_DIR = DATA_DIR / "backups" STATE_FILE = DATA_DIR / "state.json" diff --git a/src/juice_lyrics/lyrics/engine.py b/src/juice_lyrics/lyrics/engine.py index 613f5d6..324fe0c 100644 --- a/src/juice_lyrics/lyrics/engine.py +++ b/src/juice_lyrics/lyrics/engine.py @@ -3,6 +3,7 @@ import os import re import tempfile +from dataclasses import dataclass from pathlib import Path from typing import Any from mutagen.flac import FLAC @@ -16,6 +17,16 @@ LANGUAGE = "eng" LRC_RE = re.compile(r"\[(?P\d+):(?P\d{2})(?:[.:](?P\d{1,3}))?\]\s*(?P.*)") + +@dataclass(frozen=True, slots=True) +class LocalLyricLine: + """One searchable local lyric line read from an existing supported source.""" + + text: str + timestamp_ms: int | None + source: str + + def parse_synced_lyrics(raw: str) -> list[tuple[str, int]]: entries = [] for line in raw.splitlines(): @@ -30,6 +41,86 @@ def parse_synced_lyrics(raw: str) -> list[tuple[str, int]]: entries.sort(key=lambda x: x[1]) return list(dict.fromkeys(entries)) + +def _plain_lines(raw: str) -> list[str]: + lines: list[str] = [] + for value in raw.splitlines(): + text = value.strip() + if not text or LRC_RE.match(text) or re.match(r"^\[[A-Za-z][^]]*:.*\]$", text): + continue + lines.append(text) + return lines + + +def read_local_lyrics(path: Path) -> tuple[LocalLyricLine, ...]: + """Read lyrics from the same local containers and sidecar parser used by 999. + + Adjacent LRC is considered first so equivalent embedded text can be omitted + while preserving the timestamped representation. The operation is read-only. + """ + + path = Path(path) + sidecar_lines: list[LocalLyricLine] = [] + sidecar = sidecar_lrc_path(path) + try: + raw_lrc = sidecar.read_text(encoding="utf-8") + except (FileNotFoundError, OSError, UnicodeError): + raw_lrc = "" + if raw_lrc: + sidecar_lines.extend( + LocalLyricLine(text, timestamp, "lrc") + for text, timestamp in parse_synced_lyrics(raw_lrc) + ) + sidecar_lines.extend( + LocalLyricLine(text, None, "lrc") for text in _plain_lines(raw_lrc) + ) + + embedded: list[LocalLyricLine] = [] + try: + if is_flac(path): + audio = FLAC(path) + for key in ("lyrics", "unsyncedlyrics"): + for value in audio.get(key, []): + embedded.extend( + LocalLyricLine(text.strip(), None, "embedded") + for text in str(value).splitlines() if text.strip() + ) + elif is_m4a(path): + audio = MP4(path) + for value in audio.get("\xa9lyr", []): + embedded.extend( + LocalLyricLine(text.strip(), None, "embedded") + for text in str(value).splitlines() if text.strip() + ) + else: + tag = ID3(path) + for frame in tag.getall("SYLT"): + embedded.extend( + LocalLyricLine(str(text).strip(), int(timestamp), "embedded") + for text, timestamp in getattr(frame, "text", ()) + if str(text).strip() + ) + for frame in tag.getall("USLT"): + embedded.extend( + LocalLyricLine(text.strip(), None, "embedded") + for text in str(getattr(frame, "text", "") or "").splitlines() + if text.strip() + ) + except Exception: + # A damaged/unreadable embedded source must not hide a readable + # adjacent sidecar from the local search index. + embedded = [] + + # The search service applies its broader punctuation normalization. A + # conservative local comparison is enough to suppress copies of sidecar + # lines while retaining repeated chorus occurrences inside one source. + sidecar_text = {" ".join(line.text.casefold().split()) for line in sidecar_lines} + embedded = [ + line for line in embedded + if " ".join(line.text.casefold().split()) not in sidecar_text + ] + return tuple(sidecar_lines + embedded) + def load_id3(path: Path) -> ID3: try: return ID3(path) except ID3NoHeaderError: return ID3() diff --git a/src/juice_lyrics/services/__init__.py b/src/juice_lyrics/services/__init__.py index bb42472..e596a60 100644 --- a/src/juice_lyrics/services/__init__.py +++ b/src/juice_lyrics/services/__init__.py @@ -81,6 +81,12 @@ get_library_snapshot, get_library_status, ) +from .lyrics_search import ( + LyricsSearchIndex, + LyricsSearchResult, + build_lyrics_search_index, + normalize_lyric_text, +) from .library_identity import ( IdentityBackfillDependencies, IdentityBackfillResult, diff --git a/src/juice_lyrics/services/lyrics_search.py b/src/juice_lyrics/services/lyrics_search.py new file mode 100644 index 0000000..4e0705f --- /dev/null +++ b/src/juice_lyrics/services/lyrics_search.py @@ -0,0 +1,290 @@ +"""Offline incremental index and predictable phrase search for local lyrics.""" + +from __future__ import annotations + +import json +import os +import tempfile +import unicodedata +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path + +from ..config.settings import LYRICS_SEARCH_INDEX, Settings +from ..lyrics.engine import LocalLyricLine, read_local_lyrics +from ..lyrics.sidecar import sidecar_lrc_path +from ..state import file_fingerprint +from .library_status import LibrarySnapshot + + +INDEX_VERSION = 1 +LyricsReader = Callable[[Path], tuple[LocalLyricLine, ...]] +Fingerprint = tuple[int, int, int, int, int] + + +def normalize_lyric_text(value: str) -> str: + """Normalize case, spacing, and punctuation without fuzzy matching.""" + + normalized = unicodedata.normalize("NFKC", value).casefold() + pieces: list[str] = [] + for character in normalized: + if character in {"'", "’", "‘", "ʼ"}: + continue + if unicodedata.category(character).startswith(("P", "S")): + pieces.append(" ") + else: + pieces.append(character) + return " ".join("".join(pieces).split()) + + +def _prefer_sidecar_lines(lines: tuple[LocalLyricLine, ...]) -> tuple[LocalLyricLine, ...]: + sidecar_text = { + normalize_lyric_text(line.text) for line in lines if line.source == "lrc" + } + return tuple( + line for line in lines + if line.source == "lrc" or normalize_lyric_text(line.text) not in sidecar_text + ) + + +@dataclass(frozen=True, slots=True) +class LyricsIndexEntry: + reference: str + path: Path + title: str + audio_fingerprint: Fingerprint + sidecar_fingerprint: Fingerprint | None + lines: tuple[LocalLyricLine, ...] + + +@dataclass(frozen=True, slots=True) +class LyricsSearchResult: + reference: str + path: Path + title: str + matching_line: str + timestamp_ms: int | None + source: str + context_before: str | None + context_after: str | None + hit_count: int + + +@dataclass(frozen=True, slots=True) +class LyricsSearchIndex: + library_path: Path + entries: tuple[LyricsIndexEntry, ...] + indexed_count: int = 0 + reused_count: int = 0 + removed_count: int = 0 + rebuilt: bool = False + persistence_warning: str | None = None + + def search(self, query: str) -> tuple[LyricsSearchResult, ...]: + needle = normalize_lyric_text(query) + if not needle: + return () + results: list[LyricsSearchResult] = [] + for entry in self.entries: + hit_indexes = [ + index for index, line in enumerate(entry.lines) + if needle in normalize_lyric_text(line.text) + ] + if not hit_indexes: + continue + first = hit_indexes[0] + line = entry.lines[first] + before = ( + entry.lines[first - 1].text + if first and entry.lines[first - 1].source == line.source + else None + ) + after = ( + entry.lines[first + 1].text + if first + 1 < len(entry.lines) + and entry.lines[first + 1].source == line.source + else None + ) + results.append( + LyricsSearchResult( + reference=entry.reference, + path=entry.path, + title=entry.title, + matching_line=line.text, + timestamp_ms=line.timestamp_ms, + source=line.source, + context_before=before, + context_after=after, + hit_count=len(hit_indexes), + ) + ) + return tuple(results) + + +def _fingerprint(path: Path) -> Fingerprint | None: + try: + return file_fingerprint(path) + except OSError: + return None + + +def _decode_fingerprint(value: object) -> Fingerprint | None: + if value is None: + return None + if not isinstance(value, list) or len(value) != 5 or not all(isinstance(item, int) for item in value): + raise ValueError("invalid fingerprint") + return value[0], value[1], value[2], value[3], value[4] + + +def _load_cache(cache_file: Path, library_path: Path) -> tuple[dict[str, LyricsIndexEntry], bool]: + if not cache_file.is_file(): + return {}, False + try: + raw = json.loads(cache_file.read_text(encoding="utf-8")) + if not isinstance(raw, dict) or raw.get("version") != INDEX_VERSION: + raise ValueError("unsupported index") + if raw.get("library_path") != str(library_path): + return {}, False + raw_entries = raw.get("entries") + if not isinstance(raw_entries, dict): + raise ValueError("invalid entries") + entries: dict[str, LyricsIndexEntry] = {} + for reference, value in raw_entries.items(): + if not isinstance(reference, str) or not isinstance(value, dict): + raise ValueError("invalid entry") + title = value.get("title") + raw_lines = value.get("lines") + if not isinstance(title, str) or not isinstance(raw_lines, list): + raise ValueError("invalid entry contents") + lines: list[LocalLyricLine] = [] + for raw_line in raw_lines: + if not isinstance(raw_line, dict) or not isinstance(raw_line.get("text"), str): + raise ValueError("invalid lyric line") + timestamp = raw_line.get("timestamp_ms") + source = raw_line.get("source") + if timestamp is not None and not isinstance(timestamp, int): + raise ValueError("invalid timestamp") + if source not in {"lrc", "embedded"}: + raise ValueError("invalid lyric source") + lines.append(LocalLyricLine(raw_line["text"], timestamp, source)) + audio_fingerprint = _decode_fingerprint(value.get("audio_fingerprint")) + if audio_fingerprint is None: + raise ValueError("missing audio fingerprint") + entries[reference] = LyricsIndexEntry( + reference=reference, + path=library_path / reference, + title=title, + audio_fingerprint=audio_fingerprint, + sidecar_fingerprint=_decode_fingerprint(value.get("sidecar_fingerprint")), + lines=tuple(lines), + ) + return entries, False + except (OSError, UnicodeError, ValueError, json.JSONDecodeError, TypeError): + return {}, True + + +def _write_cache(cache_file: Path, index: LyricsSearchIndex) -> str | None: + payload = { + "version": INDEX_VERSION, + "library_path": str(index.library_path), + "entries": { + entry.reference: { + "title": entry.title, + "audio_fingerprint": list(entry.audio_fingerprint), + "sidecar_fingerprint": list(entry.sidecar_fingerprint) if entry.sidecar_fingerprint else None, + "lines": [ + {"text": line.text, "timestamp_ms": line.timestamp_ms, "source": line.source} + for line in entry.lines + ], + } + for entry in index.entries + }, + } + temporary: Path | None = None + try: + cache_file.parent.mkdir(parents=True, exist_ok=True) + descriptor, name = tempfile.mkstemp( + dir=cache_file.parent, prefix=f".{cache_file.name}.", suffix=".tmp" + ) + temporary = Path(name) + with os.fdopen(descriptor, "w", encoding="utf-8") as handle: + json.dump(payload, handle, ensure_ascii=False, separators=(",", ":")) + handle.flush() + os.fsync(handle.fileno()) + temporary.replace(cache_file) + return None + except OSError as exc: + return str(exc) + finally: + if temporary is not None: + temporary.unlink(missing_ok=True) + + +def build_lyrics_search_index( + settings: Settings, + snapshot: LibrarySnapshot, + *, + cache_file: Path = LYRICS_SEARCH_INDEX, + lyrics_reader: LyricsReader = read_local_lyrics, +) -> LyricsSearchIndex: + """Incrementally refresh the rebuildable cache using local fingerprints only.""" + + library_path = Path(settings.music_dir) + cached, rebuilt = _load_cache(Path(cache_file), library_path) + entries: list[LyricsIndexEntry] = [] + indexed = reused = 0 + current_references: set[str] = set() + for track in snapshot.tracks: + reference = str(track.relative_path) + current_references.add(reference) + audio_fingerprint = _fingerprint(track.path) + if audio_fingerprint is None: + continue + sidecar_fingerprint = _fingerprint(sidecar_lrc_path(track.path)) + previous = cached.get(reference) + if ( + previous is not None + and previous.audio_fingerprint == audio_fingerprint + and previous.sidecar_fingerprint == sidecar_fingerprint + ): + entries.append(previous) + reused += 1 + continue + try: + lines = _prefer_sidecar_lines(lyrics_reader(track.path)) + except Exception: + # Do not persist a transient read failure as an apparently valid + # empty track; retry it the next time the index is opened. + continue + entries.append( + LyricsIndexEntry( + reference=reference, + path=track.path, + title=track.title, + audio_fingerprint=audio_fingerprint, + sidecar_fingerprint=sidecar_fingerprint, + lines=tuple(lines), + ) + ) + indexed += 1 + removed = len(set(cached) - current_references) + index = LyricsSearchIndex( + library_path=library_path, + entries=tuple(entries), + indexed_count=indexed, + reused_count=reused, + removed_count=removed, + rebuilt=rebuilt, + ) + warning = _write_cache(Path(cache_file), index) + if warning: + index = LyricsSearchIndex( + library_path=index.library_path, + entries=index.entries, + indexed_count=index.indexed_count, + reused_count=index.reused_count, + removed_count=index.removed_count, + rebuilt=index.rebuilt, + persistence_warning=warning, + ) + return index diff --git a/src/juice_lyrics/tui/app.py b/src/juice_lyrics/tui/app.py index 49e3f91..2dad1e5 100644 --- a/src/juice_lyrics/tui/app.py +++ b/src/juice_lyrics/tui/app.py @@ -39,6 +39,7 @@ from ..services.library_status import LibrarySnapshot, LibraryStatus, get_library_snapshot, get_library_status from ..services.library_identity import IdentityBackfillResult, backfill_catalogue_identities from ..services.library_index_sync import LibraryIndexSyncResult, sync_library_index +from ..services.lyrics_search import LyricsSearchIndex, build_lyrics_search_index from ..services.metadata_audit import MetadataAudit, audit_track_metadata from ..services.metadata_repair import ( MetadataRepairPlan, @@ -73,6 +74,7 @@ LibraryDuplicatesDialog, LibraryIssuesDialog, LibraryScreen, + LyricsSearchDialog, ManualMatchDialog, MissingLibraryDialog, MetadataAuditDialog, @@ -94,6 +96,7 @@ LibrarySnapshotProvider = Callable[[Any], LibrarySnapshot] LibraryIdentityProvider = Callable[..., IdentityBackfillResult] LibraryIndexSyncProvider = Callable[..., LibraryIndexSyncResult] +LyricsSearchProvider = Callable[..., LyricsSearchIndex] ManualIdentityProvider = Callable[..., ManualIdentityResult] IdentityRebuildPlanProvider = Callable[..., IdentityRebuildPlan] IdentityRebuildExecutionProvider = Callable[..., IdentityRebuildResult] @@ -489,6 +492,7 @@ def _get_dom_base(self): ManualMatchDialog, LibraryIssuesDialog, LibraryDuplicatesDialog, + LyricsSearchDialog, MissingLibraryDialog, MetadataAuditDialog, MetadataRepairConfirmationDialog { @@ -506,6 +510,61 @@ def _get_dom_base(self): background: transparent; } + #lyrics-search-dialog { + width: 96; + max-width: 96%; + height: 84%; + padding: 1 2; + border: round ansi_cyan; + background: transparent; + } + + #lyrics-search-title { + height: 2; + text-style: bold; + color: ansi_blue; + } + + #lyrics-search-status, + #lyrics-search-help { + height: 2; + text-style: dim; + } + + #lyrics-search-query { + height: 3; + background: transparent; + border: tall ansi_cyan; + } + + #lyrics-search-query:focus { + border: tall ansi_blue; + } + + #lyrics-search-main { + height: 1fr; + layout: grid; + grid-size: 2 1; + grid-columns: 3fr 2fr; + grid-gutter: 0 1; + } + + #lyrics-search-results-scroll, + #lyrics-search-detail-scroll { + height: 1fr; + border: round ansi_cyan; + padding: 0 1; + background: transparent; + scrollbar-color: ansi_blue; + scrollbar-background: transparent; + } + + #lyrics-search-results, + #lyrics-search-detail { + height: auto; + background: transparent; + } + #manual-match-dialog { width: 82; max-width: 94%; @@ -1105,6 +1164,7 @@ def __init__( download_all_execution_provider: Callable[..., Any] = execute_download_all, library_snapshot_provider: LibrarySnapshotProvider = get_library_snapshot, library_index_sync_provider: LibraryIndexSyncProvider = sync_library_index, + lyrics_search_provider: LyricsSearchProvider = build_lyrics_search_index, library_identity_provider: LibraryIdentityProvider = backfill_catalogue_identities, identity_rebuild_plan_provider: IdentityRebuildPlanProvider = plan_catalogue_identity_rebuild, identity_rebuild_execution_provider: IdentityRebuildExecutionProvider = execute_catalogue_identity_rebuild, @@ -1150,6 +1210,7 @@ def normalized_downloads_provider() -> DownloadQueueSnapshot: self.download_all_execution_provider = download_all_execution_provider self.library_snapshot_provider = library_snapshot_provider self.library_index_sync_provider = library_index_sync_provider + self.lyrics_search_provider = lyrics_search_provider self.library_identity_provider = library_identity_provider self.identity_rebuild_plan_provider = identity_rebuild_plan_provider self.identity_rebuild_execution_provider = identity_rebuild_execution_provider @@ -1210,6 +1271,7 @@ def on_mount(self) -> None: missing_library_provider=self.missing_library_provider, queue_plan_provider=self.queue_plan_provider, queue_add_provider=self.queue_add_provider, + lyrics_search_provider=self.lyrics_search_provider, ), "library", ) diff --git a/src/juice_lyrics/tui/help.py b/src/juice_lyrics/tui/help.py index 1af1080..129372d 100644 --- a/src/juice_lyrics/tui/help.py +++ b/src/juice_lyrics/tui/help.py @@ -21,6 +21,7 @@ ("PgUp/PgDn", "Scroll loaded results"), ("Home/End", "First / last result"))), ("Library", (("↑/↓ or j/k", "Select track"), ("Enter", "Track details"), ("/", "Focus track search; Enter filters"), + ("f", "Search local lyrics offline"), ("s", "Sync paths and catalogue identity (no media edits)"), ("a", "Open Library Issues"), ("g", "Show catalogue recordings missing locally"), @@ -34,6 +35,10 @@ ("u", "Unlock and clear a manual match"), ("i", "Preview catalogue identity rebuild"), ("PgUp/PgDn", "Scroll tracks or details"), ("Home/End", "First / last track"))), + ("Search Lyrics", (("Type", "Search normalized local lyric text"), + ("↑/↓", "Move through matching tracks"), + ("Enter", "Open the selected Library track"), + ("Esc", "Return to Library"))), ("Missing Library", (("↑/↓ or j/k", "Select missing recording"), ("/", "Filter loaded catalogue recordings"), ("a", "Add selected recording to Downloads"), diff --git a/src/juice_lyrics/tui/screens/library.py b/src/juice_lyrics/tui/screens/library.py index bd40d47..0741dbc 100644 --- a/src/juice_lyrics/tui/screens/library.py +++ b/src/juice_lyrics/tui/screens/library.py @@ -28,6 +28,11 @@ ) from ...services.library_identity import IdentityBackfillResult from ...services.library_index_sync import LibraryIndexSyncResult +from ...services.lyrics_search import ( + LyricsSearchIndex, + LyricsSearchResult, + build_lyrics_search_index, +) from ...services.library_issues import ( LibraryHealth, LibraryIssue, @@ -89,6 +94,7 @@ SnapshotProvider = Callable[[Any], LibrarySnapshot] IdentityProvider = Callable[..., IdentityBackfillResult] IndexSyncProvider = Callable[..., LibraryIndexSyncResult] +LyricsSearchProvider = Callable[..., LyricsSearchIndex] IdentityRebuildPlanProvider = Callable[..., IdentityRebuildPlan] IdentityRebuildExecutionProvider = Callable[..., IdentityRebuildResult] ManualSearchProvider = Callable[..., CataloguePage] @@ -150,6 +156,27 @@ def on_key(self, event: Key) -> None: return +class LyricsSearchInput(Input): + """Query entry that keeps result navigation available while typing.""" + + def on_key(self, event: Key) -> None: + dialog = self.screen + if not isinstance(dialog, LyricsSearchDialog): + return + if event.key == "escape": + dialog.dismiss(None) + elif event.key == "down": + dialog.move_selection(1) + elif event.key == "up": + dialog.move_selection(-1) + elif event.key == "enter": + dialog.select_result() + else: + return + event.prevent_default() + event.stop() + + class LibrarySelect(Select[str]): """Local status selector that preserves global section shortcuts.""" @@ -267,6 +294,156 @@ def on_click(self, event: Click) -> None: self.post_message(self.Activated(self.action)) +class LyricsSearchDialog(ModalScreen[str | None]): + """Offline, incrementally indexed lyric phrase search.""" + + def __init__( + self, + settings: Any, + snapshot: LibrarySnapshot, + *, + index_provider: LyricsSearchProvider = build_lyrics_search_index, + ) -> None: + super().__init__() + self.settings = settings + self.snapshot = snapshot + self._index_provider = index_provider + self.index: LyricsSearchIndex | None = None + self.results: tuple[LyricsSearchResult, ...] = () + self.selected_index = 0 + self._worker: Worker[LyricsSearchIndex] | None = None + + def compose(self) -> Iterable[Widget]: + with Container(id="lyrics-search-dialog"): + yield Static("Search Lyrics", id="lyrics-search-title") + yield Static("Building local lyrics index…", id="lyrics-search-status", markup=False) + yield LyricsSearchInput( + placeholder="Type remembered words or a phrase", + id="lyrics-search-query", + ) + with Grid(id="lyrics-search-main"): + with VerticalScroll(id="lyrics-search-results-scroll"): + yield Static("Indexing local lyrics…", id="lyrics-search-results", markup=False) + with VerticalScroll(id="lyrics-search-detail-scroll"): + yield Static("Matches stay entirely on this device.", id="lyrics-search-detail", markup=False) + yield Static( + "Type to search · ↑/↓ navigate · Enter open track · Esc return", + id="lyrics-search-help", + markup=False, + ) + + def on_mount(self) -> None: + self.query_one("#lyrics-search-query", Input).focus() + self._worker = self._build_index() + + @work(thread=True, exclusive=True, group="lyrics-search-index", exit_on_error=False) + def _build_index(self) -> LyricsSearchIndex: + return self._index_provider(self.settings, self.snapshot) + + def on_worker_state_changed(self, event: Worker.StateChanged) -> None: + if event.worker is not self._worker: + return + if event.state is WorkerState.SUCCESS: + self.index = event.worker.result + index = self.index + message = ( + f"Ready · {len(index.entries)} tracks · {index.indexed_count} indexed · " + f"{index.reused_count} reused" + ) + if index.removed_count: + message += f" · {index.removed_count} removed" + if index.rebuilt: + message += " · cache rebuilt" + if index.persistence_warning: + message += " · cache could not be saved" + self.query_one("#lyrics-search-status", Static).update(message) + self._update_results() + elif event.state is WorkerState.ERROR: + self.query_one("#lyrics-search-status", Static).update( + "Lyrics index could not be loaded. No files were changed." + ) + self.query_one("#lyrics-search-results", Static).update("Search unavailable.") + + def on_input_changed(self, event: Input.Changed) -> None: + if event.input.id == "lyrics-search-query": + self._update_results() + + def _update_results(self) -> None: + query = self.query_one("#lyrics-search-query", Input).value + self.results = self.index.search(query) if self.index is not None else () + self.selected_index = 0 + self._render_results() + + def _render_results(self) -> None: + query = self.query_one("#lyrics-search-query", Input).value.strip() + listing = self.query_one("#lyrics-search-results", Static) + detail = self.query_one("#lyrics-search-detail", Static) + if self.index is None: + return + if not query: + listing.update("Type words from a lyric to search your local library.") + detail.update("Case, ordinary punctuation, and repeated whitespace are ignored.") + return + if not self.results: + listing.update("No local lyric matches.") + detail.update("Try a shorter exact phrase.") + return + lines = [] + for index, result in enumerate(self.results): + marker = ">" if index == self.selected_index else " " + timestamp = _lyrics_timestamp(result.timestamp_ms) + count = f" · {result.hit_count} hits" if result.hit_count > 1 else "" + lines.append( + f"{marker} {result.title[:28]:28} · {timestamp:5} · “{result.matching_line}”{count}" + ) + listing.update(Text("\n".join(lines), no_wrap=True, overflow="ellipsis")) + selected = self.results[self.selected_index] + context = [] + if selected.context_before: + context.append(f" {selected.context_before}") + context.append(f"> {_lyrics_timestamp(selected.timestamp_ms)} {selected.matching_line}") + if selected.context_after: + context.append(f" {selected.context_after}") + detail.update( + "\n".join( + [ + selected.title, + str(selected.path), + f"Source: {'adjacent LRC' if selected.source == 'lrc' else 'embedded lyrics'}", + f"Matches in track: {selected.hit_count}", + "", + *context, + ] + ) + ) + + def move_selection(self, amount: int) -> None: + if not self.results: + return + self.selected_index = max(0, min(len(self.results) - 1, self.selected_index + amount)) + self._render_results() + + def select_result(self) -> None: + if self.results: + self.dismiss(self.results[self.selected_index].reference) + + def on_key(self, event: Key) -> None: + if isinstance(self.app.focused, Input): + return + if event.key == "escape": + self.dismiss(None) + elif event.key in {"down", "j"}: + self.move_selection(1) + elif event.key in {"up", "k"}: + self.move_selection(-1) + elif event.key == "enter": + self.select_result() + else: + return + event.prevent_default() + event.stop() + + class ManualMatchInput(Input): """Search field for the state-only manual catalogue chooser.""" @@ -1413,6 +1590,7 @@ def __init__( missing_library_provider: MissingLibraryProvider = get_missing_library, queue_plan_provider: QueuePlanProvider = plan_queue_batch_additions, queue_add_provider: QueueAddProvider = add_batch_to_download_queue, + lyrics_search_provider: LyricsSearchProvider = build_lyrics_search_index, ) -> None: super().__init__("library", "Library") self.settings = settings @@ -1437,6 +1615,7 @@ def __init__( self._missing_library_provider = missing_library_provider self._queue_plan_provider = queue_plan_provider self._queue_add_provider = queue_add_provider + self._lyrics_search_provider = lyrics_search_provider self.snapshot: LibrarySnapshot | None = None self.filtered_tracks: tuple[LibraryTrack, ...] = () self.selected_index = 0 @@ -1498,7 +1677,7 @@ def compose_content(self) -> Iterable[Widget]: with VerticalScroll(id="library-details-scroll"): yield Static("Select a track to inspect it.", id="library-details", markup=False) yield Static("Sync Library updates the catalogue view without changing audio or lyrics.", id="library-preview", markup=False) - yield Static("s Sync Library · a Issues · g Missing · d Duplicates · ↑↓ Move · Enter Details · ? Help", id="library-position", markup=False) + yield Static("s Sync Library · a Issues · f Search Lyrics · g Missing · d Duplicates · ↑↓ Move · Enter Details · ? Help", id="library-position", markup=False) def action_focus_search(self) -> None: self.query_one("#library-query", Input).focus() @@ -2035,9 +2214,9 @@ def _render_details(self) -> None: def _update_position(self) -> None: if not self.filtered_tracks: - self.query_one("#library-position", Static).update("s Sync Library · a Issues · g Missing · d Duplicates · ? Help") + self.query_one("#library-position", Static).update("s Sync Library · a Issues · f Search Lyrics · g Missing · d Duplicates · ? Help") return - suffix = "Esc Back · e Metadata · c Match · l Refresh · ? Help" if self._details_mode else "s Sync Library · a Issues · g Missing · d Duplicates · e Metadata · ↑↓ Move · ? Help" + suffix = "Esc Back · f Search Lyrics · e Metadata · c Match · l Refresh · ? Help" if self._details_mode else "s Sync Library · a Issues · f Search Lyrics · g Missing · d Duplicates · e Metadata · ↑↓ Move · ? Help" self.query_one("#library-position", Static).update( f"Track {self.selected_index + 1} of {len(self.filtered_tracks)} · {suffix}" ) @@ -2049,6 +2228,8 @@ def on_key(self, event: Key) -> None: return if event.key == "s": self.sync_library() + elif event.key == "f": + self._open_lyrics_search() elif event.key == "a": self._open_issues() elif event.key == "d": @@ -2103,6 +2284,35 @@ def on_key(self, event: Key) -> None: event.prevent_default() event.stop() + def _open_lyrics_search(self) -> None: + if self.snapshot is None: + self._set_status("Load the library before searching lyrics.", error=True) + return + self.app.push_screen( + LyricsSearchDialog( + self.settings, + self.snapshot, + index_provider=self._lyrics_search_provider, + ), + self._lyrics_search_closed, + ) + + def _lyrics_search_closed(self, reference: str | None) -> None: + if reference is None: + self._set_status("Lyrics Search closed. No files were changed.") + return + self.query_one("#library-query", Input).value = "" + self.query_one("#library-filter", Select).value = LibraryFilter.ALL.value + self._apply_local_filter(preferred_reference=reference) + if self.selected_track is None or self.selected_track.reference != reference: + self._set_status("That track is no longer in the current Library view.", error=True) + return + self._details_mode = True + self.add_class("-details-mode") + self._render_details() + self._update_position() + self._set_status(f"Opened {self.selected_track.title} from Lyrics Search.") + def _open_issues(self) -> None: if self.snapshot is None: self._set_status("Load the library before viewing Issues.", error=True) @@ -2705,6 +2915,14 @@ def _duration(seconds: float | None) -> str: return f"{minutes}:{remainder:02d}" +def _lyrics_timestamp(milliseconds: int | None) -> str: + if milliseconds is None: + return "" + minutes, remainder = divmod(max(0, milliseconds), 60_000) + seconds = remainder // 1_000 + return f"{minutes:02d}:{seconds:02d}" + + def _track_preview_text(plan: LibrarySyncPlan | None, path: Path) -> str: if plan is None: return " Not generated. Press l for this song or m for the library." diff --git a/tests/test_lyrics_search.py b/tests/test_lyrics_search.py new file mode 100644 index 0000000..659c411 --- /dev/null +++ b/tests/test_lyrics_search.py @@ -0,0 +1,236 @@ +from __future__ import annotations + +import json +import struct +from dataclasses import replace +from pathlib import Path + +from mutagen.flac import FLAC +from mutagen.id3 import ID3, SYLT, USLT +from mutagen.mp4 import MP4 + +from juice_lyrics.config.settings import LYRICS_SEARCH_INDEX, Settings +from juice_lyrics.lyrics.engine import DESCRIPTION, LocalLyricLine, read_local_lyrics +from juice_lyrics.services.library_status import ( + LibraryLrcStatus, + LibraryLyricStatus, + LibraryMatchStatus, + LibrarySnapshot, + LibraryStateStatus, + LibraryTrack, +) +from juice_lyrics.services.lyrics_search import ( + build_lyrics_search_index, + normalize_lyric_text, +) + + +def _atom(name: bytes, payload: bytes) -> bytes: + return struct.pack(">I4s", len(payload) + 8, name) + payload + + +def _make_mp3(path: Path, lyrics: str) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"") + tags = ID3() + tags.add(USLT(encoding=3, lang="eng", desc=DESCRIPTION, text=lyrics)) + tags.save(path) + return path + + +def _make_flac(path: Path, lyrics: str) -> Path: + sample_rate = 44_100 + packed = (sample_rate << 44) | ((2 - 1) << 41) | ((16 - 1) << 36) | sample_rate + stream_info = struct.pack(">HH", 4096, 4096) + b"\0" * 6 + packed.to_bytes(8, "big") + b"\0" * 16 + path.write_bytes(b"fLaC" + b"\x80" + len(stream_info).to_bytes(3, "big") + stream_info) + audio = FLAC(path) + audio["TITLE"] = [path.stem] + audio["ARTIST"] = ["Juice WRLD"] + audio["LYRICS"] = [lyrics] + audio.save() + return path + + +def _make_m4a(path: Path, lyrics: str) -> Path: + timescale = 44_100 + movie_header = _atom( + b"mvhd", b"\0\0\0\0" + struct.pack(">IIII", 0, 0, timescale, timescale) + ) + path.write_bytes( + _atom(b"ftyp", b"M4A \0\0\0\0M4A mp42") + + _atom(b"moov", movie_header) + + _atom(b"mdat", b"synthetic payload") + ) + audio = MP4(path) + audio.add_tags() + audio["\xa9nam"] = [path.stem] + audio["\xa9ART"] = ["Juice WRLD"] + audio["\xa9lyr"] = [lyrics] + audio.save() + return path + + +def _track(path: Path, root: Path) -> LibraryTrack: + return LibraryTrack( + reference=str(path.relative_to(root)), + path=path, + relative_path=path.relative_to(root), + filename=path.name, + title=path.stem, + duration_seconds=1.0, + match_status=LibraryMatchStatus.UNMATCHED, + matched_title=None, + lyric_status=LibraryLyricStatus.PLAIN, + lrc_status=LibraryLrcStatus.PRESENT if path.with_suffix(".lrc").is_file() else LibraryLrcStatus.NONE, + lrc_path=path.with_suffix(".lrc") if path.with_suffix(".lrc").is_file() else None, + state_status=LibraryStateStatus.NEW, + ) + + +def _snapshot(root: Path, *paths: Path) -> LibrarySnapshot: + return LibrarySnapshot(root, True, tuple(_track(path, root) for path in paths)) + + +def test_native_reader_covers_mp3_flac_m4a_plain_and_timed_lrc(tmp_path): + mp3 = _make_mp3(tmp_path / "Lucid Dreams.mp3", "I still see your shadows\nin my room") + flac = _make_flac(tmp_path / "Rental.flac", "I don't know why\nplain FLAC line") + m4a = _make_m4a(tmp_path / "All Life Long.m4a", "M4A embedded lyric") + mp3.with_suffix(".lrc").write_text( + "[ar:Juice WRLD]\n[01:42.25] I still see your shadows\nplain sidecar line\n", + encoding="utf-8", + ) + + mp3_lines = read_local_lyrics(mp3) + assert LocalLyricLine("I still see your shadows", 102250, "lrc") in mp3_lines + assert LocalLyricLine("plain sidecar line", None, "lrc") in mp3_lines + assert any(line.text == "in my room" and line.source == "embedded" for line in mp3_lines) + assert [line.text for line in read_local_lyrics(flac)] == ["I don't know why", "plain FLAC line"] + assert [line.text for line in read_local_lyrics(m4a)] == ["M4A embedded lyric"] + + +def test_mp3_synced_embedded_lyrics_remain_searchable(tmp_path): + path = tmp_path / "Synced.mp3" + path.write_bytes(b"") + tags = ID3() + tags.add(SYLT(encoding=3, lang="eng", format=2, type=1, desc=DESCRIPTION, text=[("timed embedded line", 1200)])) + tags.save(path) + + assert read_local_lyrics(path) == (LocalLyricLine("timed embedded line", 1200, "embedded"),) + + +def test_normalization_and_phrase_matching_are_predictable(tmp_path): + assert normalize_lyric_text(" DON'T know?! ") == "dont know" + path = _make_mp3(tmp_path / "Song.mp3", "Baby, I DON'T know why\nnext line") + index = build_lyrics_search_index( + Settings(music_dir=tmp_path), _snapshot(tmp_path, path), cache_file=tmp_path / "index.json" + ) + + for query in ("dont know", "don't know", "DON'T KNOW", "i dont"): + result = index.search(query) + assert len(result) == 1 + assert result[0].matching_line == "Baby, I DON'T know why" + assert index.search("not present") == () + + +def test_one_result_per_track_preserves_lrc_timestamp_and_hit_count(tmp_path): + path = _make_mp3(tmp_path / "Lucid Dreams.mp3", "I still see your shadows!\nI still see your shadows!") + path.with_suffix(".lrc").write_text( + "[01:42.00] I still see your shadows\n[02:10.00] I still see your shadows\n", + encoding="utf-8", + ) + index = build_lyrics_search_index( + Settings(music_dir=tmp_path), _snapshot(tmp_path, path), cache_file=tmp_path / "index.json" + ) + + results = index.search("still see your shadows") + assert len(results) == 1 + assert results[0].timestamp_ms == 102000 + assert results[0].source == "lrc" + assert results[0].hit_count == 2 + + +def test_default_index_path_uses_isolated_xdg_cache(): + assert LYRICS_SEARCH_INDEX == Path.home() / ".cache" / "juice-lyrics" / "lyrics-search-index-v1.json" + + +def test_incremental_index_new_changed_removed_and_repeated_queries(tmp_path): + first = _make_mp3(tmp_path / "First.mp3", "first lyric") + second = _make_mp3(tmp_path / "Second.mp3", "second lyric") + cache = tmp_path / "cache" / "index.json" + reads: list[Path] = [] + + def reader(path: Path): + reads.append(path) + return read_local_lyrics(path) + + initial = build_lyrics_search_index( + Settings(music_dir=tmp_path), _snapshot(tmp_path, first), cache_file=cache, lyrics_reader=reader + ) + assert initial.indexed_count == 1 and reads == [first] + reads.clear() + added = build_lyrics_search_index( + Settings(music_dir=tmp_path), _snapshot(tmp_path, first, second), cache_file=cache, lyrics_reader=reader + ) + assert added.indexed_count == 1 and added.reused_count == 1 and reads == [second] + + _make_mp3(first, "changed embedded lyric") + reads.clear() + changed = build_lyrics_search_index( + Settings(music_dir=tmp_path), _snapshot(tmp_path, first, second), cache_file=cache, lyrics_reader=reader + ) + assert changed.indexed_count == 1 and changed.reused_count == 1 and reads == [first] + reads.clear() + for query in ("changed", "changed e", "changed embedded", "missing"): + changed.search(query) + assert reads == [] + + removed = build_lyrics_search_index( + Settings(music_dir=tmp_path), _snapshot(tmp_path, first), cache_file=cache, lyrics_reader=reader + ) + assert removed.removed_count == 1 + assert removed.search("second lyric") == () + + +def test_changed_lrc_reindexes_only_its_track(tmp_path): + first = _make_mp3(tmp_path / "First.mp3", "embedded one") + second = _make_mp3(tmp_path / "Second.mp3", "embedded two") + first.with_suffix(".lrc").write_text("[00:01.00] old sidecar\n", encoding="utf-8") + cache = tmp_path / "index.json" + snapshot = _snapshot(tmp_path, first, second) + build_lyrics_search_index(Settings(music_dir=tmp_path), snapshot, cache_file=cache) + first.with_suffix(".lrc").write_text("[00:02.00] replacement sidecar text\n", encoding="utf-8") + reads: list[Path] = [] + index = build_lyrics_search_index( + Settings(music_dir=tmp_path), snapshot, cache_file=cache, + lyrics_reader=lambda path: reads.append(path) or read_local_lyrics(path), + ) + + assert reads == [first] + assert index.search("replacement sidecar")[0].timestamp_ms == 2000 + + +def test_corrupt_index_rebuilds_offline_without_mutating_media_or_state(tmp_path, monkeypatch): + import juice_lyrics.api.client as api_client + + path = _make_mp3(tmp_path / "Offline.mp3", "works with no catalogue") + state = tmp_path / "state.json" + state.write_text(json.dumps({"files": {"keep": {"custom": True}}}), encoding="utf-8") + before_audio = path.read_bytes() + before_state = state.read_bytes() + cache = tmp_path / "cache" / "index.json" + cache.parent.mkdir() + cache.write_text("not json", encoding="utf-8") + monkeypatch.setattr( + api_client, "api_get", + lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("API called")), + ) + + index = build_lyrics_search_index( + Settings(music_dir=tmp_path), _snapshot(tmp_path, path), cache_file=cache + ) + + assert index.rebuilt is True + assert index.search("no catalogue") + assert path.read_bytes() == before_audio + assert state.read_bytes() == before_state + assert json.loads(cache.read_text(encoding="utf-8"))["version"] == 1 diff --git a/tests/test_packaging.py b/tests/test_packaging.py index 91d3370..4171fc9 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -25,7 +25,7 @@ def test_distribution_metadata_has_one_version_authority_and_current_entry_point assert project["tool"]["setuptools"]["dynamic"]["version"] == { "attr": "juice_lyrics.__version__" } - assert __version__ == "2.0.0b1" + assert __version__ == "2.0.0b2" assert project["project"]["scripts"] == { "999": "juice_lyrics.cli:main", "juice-lyrics": "juice_lyrics.cli:main", diff --git a/tests/test_tui_library.py b/tests/test_tui_library.py index 83a848c..0f5af28 100644 --- a/tests/test_tui_library.py +++ b/tests/test_tui_library.py @@ -51,12 +51,80 @@ ) from juice_lyrics.backup.manager import BackupRecord from juice_lyrics.services.library_index_sync import LibraryIndexSyncResult +from juice_lyrics.lyrics.engine import LocalLyricLine +from juice_lyrics.services.lyrics_search import LyricsIndexEntry, LyricsSearchIndex from juice_lyrics.services.settings_snapshot import ( IntegrationSnapshot, IntegrationStatus, SettingsSnapshot, ) from juice_lyrics.tui import JuiceLyricsApp +from juice_lyrics.tui.help import guide_text + + +def test_help_documents_offline_lyrics_search_key(): + text = guide_text() + assert "f Search local lyrics offline" in text + assert "Search Lyrics" in text + + +def test_lyrics_search_updates_navigates_selects_and_cancels(tmp_path): + root = tmp_path / "music" + root.mkdir() + first_path = root / "Lucid Dreams.mp3" + second_path = root / "Shadows Again.mp3" + first_path.write_bytes(b"first") + second_path.write_bytes(b"second") + first = _track(root, first_path.name) + second = _track(root, second_path.name) + fingerprint = (1, 2, 3, 4, 5) + index = LyricsSearchIndex( + root, + ( + LyricsIndexEntry( + first.reference, first.path, first.title, fingerprint, None, + (LocalLyricLine("I still see your shadows in my room", 102000, "lrc"),), + ), + LyricsIndexEntry( + second.reference, second.path, second.title, fingerprint, None, + (LocalLyricLine("Your shadows follow me", None, "embedded"),), + ), + ), + reused_count=2, + ) + + async def scenario(): + app = _app( + tmp_path, + lambda settings: _snapshot(root, first, second), + lyrics_search_provider=lambda settings, snapshot: index, + ) + async with app.run_test() as pilot: + screen = await _open_library(app, pilot) + assert "f Search Lyrics" in _text(app, "#library-position") + await pilot.press("f") + dialog = app.screen + await dialog._worker.wait() + await pilot.press("escape") + await pilot.pause() + assert app.screen is screen + assert "No files were changed" in _text(app, "#library-status") + + await pilot.press("f") + dialog = app.screen + await dialog._worker.wait() + dialog.query_one("#lyrics-search-query", Input).value = "SHADOWS" + await pilot.pause() + assert "01:42" in _text(app, "#lyrics-search-results") + assert "I still see your shadows" in _text(app, "#lyrics-search-detail") + await pilot.press("down", "enter") + await pilot.pause() + assert app.screen is screen + assert screen.selected_track.reference == second.reference + assert screen._details_mode is True + assert "Opened Shadows Again" in _text(app, "#library-status") + + asyncio.run(scenario()) def test_sync_library_is_immediate_single_worker_and_navigation_stays_live(tmp_path):