Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/).
## [Unreleased]

### Added
- Optional lyrics embedding for MP3: plain lyrics from LRCLIB are written to the `USLT` ID3 frame and synchronized lyrics to `SYLT`. Both frames are written when timed lyrics exist, so players without `SYLT` support still show the words. Missing lyrics never fail the download.
- `--lyrics`/`--no-lyrics` and the `lyrics_enabled` config key. Embedding is enabled by default for MP3 and does not affect the audio data or existing non-lyrics tags.
- Configurable free metadata providers: iTunes (the new default), Deezer, MusicBrainz with Cover Art Archive, VocaDB and optional Spotify. No API key is needed except for Spotify.
- `-s`/`--metadata-sources` with priority ordering, `none`, duplicate removal and unknown-name validation. YouTube stays a separate artwork fallback and is not part of the metadata ordering.
- `--disable-sources`, `--provider-opt NAME.KEY=VALUE`, `--match-threshold`, `--title-threshold` and `--list-sources`.
Expand Down
40 changes: 38 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ trackfetch "My Playlist.txt" -o ~/Music/"My Playlist"
## Usage

```text
trackfetch [-h] [--track ARTIST - TITLE ...] [-o OUTPUT] [--config CONFIG] [-f {mp3,m4a,opus}] [--title-only] [--delay DELAY] [-s SOURCES] [--disable-sources SOURCES] [--provider-opt NAME.KEY=VALUE] [--match-threshold SCORE] [--title-threshold SCORE] [--list-sources] [--spotify-client-id ID] [--spotify-client-secret SECRET] [--no-logs] [INPUT ...]
trackfetch [-h] [--track ARTIST - TITLE ...] [-o OUTPUT] [--config CONFIG] [-f {mp3,m4a,opus}] [--title-only] [--delay DELAY] [-s SOURCES] [--disable-sources SOURCES] [--provider-opt NAME.KEY=VALUE] [--match-threshold SCORE] [--title-threshold SCORE] [--list-sources] [--spotify-client-id ID] [--spotify-client-secret SECRET] [--no-logs] [--lyrics | --no-lyrics] [INPUT ...]
```

| Option | Default | What it does |
Expand All @@ -203,6 +203,7 @@ trackfetch [-h] [--track ARTIST - TITLE ...] [-o OUTPUT] [--config CONFIG] [-f {
| `--spotify-client-id` | `$SPOTIFY_CLIENT_ID` | Spotify API client ID. See [Spotify credentials](#spotify-credentials). |
| `--spotify-client-secret` | `$SPOTIFY_CLIENT_SECRET` | Spotify API client secret. |
| `--no-logs` | off | Do not read `done.txt` and do not write `done.txt` or `failed.txt`. Progress from earlier runs is ignored, so finished songs are not skipped. |
| `--lyrics` / `--no-lyrics` | on | Embed lyrics fetched from LRCLIB into MP3 tags. Plain text goes to `USLT`; timed lyrics also go to `SYLT`. Missing lyrics never fail the download. |

```bash
trackfetch songs.txt -o ~/Music/RoadTrip # save to a specific folder
Expand Down Expand Up @@ -268,6 +269,38 @@ MIME type. MP3 and Opus can embed all four; M4A supports JPEG and PNG, so GIF or
WebP artwork is skipped for that container instead of being mislabelled as
JPEG.

### Lyrics

For MP3 output trackfetch also looks up lyrics on [LRCLIB](https://lrclib.net/)
and embeds them in the ID3 tag, so players can show the words offline without
sidecar `.lrc` or `.txt` files.

| Frame | Contents |
| --- | --- |
| `USLT` | The full plain text, without timestamps. |
| `SYLT` | Timed lines, only when the source returns synchronized lyrics. |

When timed lyrics are available, both frames are written: `USLT` keeps the
full text for players without `SYLT` support. When only plain lyrics are
available, only `USLT` is written. Timestamps are never invented.

The source is LRCLIB, which needs no API key. Lyrics embedding is enabled by
default for MP3 and can be turned off with `--no-lyrics` or
`lyrics_enabled = false` in the config file. The other formats (`m4a`, `opus`)
are not changed by this option.

Missing lyrics, a timeout or an HTTP error never fails the download. The MP3
is still saved with its usual metadata. If an MP3 already contains lyrics and
no new lyrics are found, the existing frames are left untouched. When new
lyrics are found, the old `USLT`/`SYLT` frames are replaced instead of
duplicated. Existing tags and cover art, and the audio data itself, are never
rewritten or re-encoded.

```bash
trackfetch songs.txt --format mp3 # embed lyrics (default)
trackfetch songs.txt --format mp3 --no-lyrics # keep MP3 tags lyrics-free
```

### Inline tracks

Skip the file and name the tracks right on the command line:
Expand Down Expand Up @@ -322,6 +355,9 @@ vocadb_min_interval = 0.5
# YouTube artwork fallback
youtube_enabled = true

# Lyrics embedding into MP3 tags
lyrics_enabled = true

# Matching thresholds
match_threshold = 0.6
title_threshold = 0.8
Expand Down Expand Up @@ -386,7 +422,7 @@ environment variable.
| `opus` | YouTube's **original** Opus audio, copied without re-encoding. The best quality you can get | most modern players, Android, browsers; not iTunes or older devices |
| `mp3` | YouTube's audio **re-encoded** to the best VBR MP3. A second lossy encode, so slightly below the source | everything, including old players and car stereos |

All three get the same tags and embedded cover art. `done.txt` doesn't track the format, so use a separate `-o` folder for each format.
All three get the same metadata tags and embedded cover art. Embedded lyrics are written to MP3 only. `done.txt` doesn't track the format, so use a separate `-o` folder for each format.

### Input file

Expand Down
39 changes: 37 additions & 2 deletions README.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ trackfetch "My Playlist.txt" -o ~/Music/"My Playlist"
## Использование

```text
trackfetch [-h] [--track ARTIST - TITLE ...] [-o OUTPUT] [--config CONFIG] [-f {mp3,m4a,opus}] [--title-only] [--delay DELAY] [-s SOURCES] [--disable-sources SOURCES] [--provider-opt NAME.KEY=VALUE] [--match-threshold SCORE] [--title-threshold SCORE] [--list-sources] [--spotify-client-id ID] [--spotify-client-secret SECRET] [--no-logs] [INPUT ...]
trackfetch [-h] [--track ARTIST - TITLE ...] [-o OUTPUT] [--config CONFIG] [-f {mp3,m4a,opus}] [--title-only] [--delay DELAY] [-s SOURCES] [--disable-sources SOURCES] [--provider-opt NAME.KEY=VALUE] [--match-threshold SCORE] [--title-threshold SCORE] [--list-sources] [--spotify-client-id ID] [--spotify-client-secret SECRET] [--no-logs] [--lyrics | --no-lyrics] [INPUT ...]
```

| Параметр | По умолчанию | Что делает |
Expand All @@ -203,6 +203,7 @@ trackfetch [-h] [--track ARTIST - TITLE ...] [-o OUTPUT] [--config CONFIG] [-f {
| `--spotify-client-id` | `$SPOTIFY_CLIENT_ID` | Client ID для Spotify API. См. [Данные Spotify](#данные-spotify). |
| `--spotify-client-secret` | `$SPOTIFY_CLIENT_SECRET` | Client secret для Spotify API. |
| `--no-logs` | выключен | Не читать `done.txt` и не писать `done.txt` и `failed.txt`. Прогресс прошлых запусков не учитывается, поэтому готовые песни не пропускаются. |
| `--lyrics` / `--no-lyrics` | включён | Встраивать текст из LRCLIB в теги MP3. Обычный текст пишется в `USLT`, синхронизированный — ещё и в `SYLT`. Если текста нет, загрузка не считается ошибкой. |

```bash
trackfetch songs.txt -o ~/Music/RoadTrip # сохранить в конкретную папку
Expand Down Expand Up @@ -269,6 +270,37 @@ PNG, поэтому GIF или WebP для этого контейнера пр
как JPEG.
```

### Текст песни

Для MP3 trackfetch также ищет текст на [LRCLIB](https://lrclib.net/) и
встраивает его в ID3-теги, чтобы плеер показывал слова без интернета и
отдельных файлов `.lrc` или `.txt`.

| Фрейм | Содержимое |
| --- | --- |
| `USLT` | Полный обычный текст без таймкодов. |
| `SYLT` | Строки с временными метками, только если источник вернул синхронизированный текст. |

Если синхронизированный текст есть, записываются оба фрейма: `USLT` нужен
плеерам без поддержки `SYLT`. Если есть только обычный текст, записывается
только `USLT`. Искусственные таймкоды не создаются.

Источник — LRCLIB, ключ API не нужен. По умолчанию встраивание включено для
MP3; отключить можно флагом `--no-lyrics` или строкой
`lyrics_enabled = false` в конфиге. На форматы `m4a` и `opus` эта настройка
не влияет.

Если текст не найден, произошла ошибка сети или сервер вернул ошибку, загрузка
не прерывается: MP3 сохраняется с обычными метаданными. Если в файле уже была
лирика, а новая не найдена, старые фреймы остаются. При новой лирике прежние
`USLT`/`SYLT` заменяются, а не дублируются. Остальные теги, обложка и сами
аудиоданные не перекодируются и не повреждаются.

```bash
trackfetch songs.txt --format mp3 # встроить текст (по умолчанию)
trackfetch songs.txt --format mp3 --no-lyrics # не добавлять текст в MP3
```

### Треки прямо в аргументах

Можно не заводить файл, а назвать треки прямо в командной строке:
Expand Down Expand Up @@ -324,6 +356,9 @@ vocadb_min_interval = 0.5
# Запасная обложка YouTube
youtube_enabled = true

# Встраивание текста песни в теги MP3
lyrics_enabled = true

# Пороги совпадения
match_threshold = 0.6
title_threshold = 0.8
Expand Down Expand Up @@ -387,7 +422,7 @@ trackfetch songs.txt --spotify-client-id твой-id --spotify-client-secret т
| `opus` | **Оригинальный** звук YouTube в Opus, скопированный без перекодирования. Лучшее доступное качество | большинство современных плееров, Android, браузеры; не iTunes и не старые устройства |
| `mp3` | Звук YouTube, **перекодированный** в MP3 VBR максимального качества. Это повторное сжатие с потерями, поэтому чуть хуже исходника | везде, включая старые плееры и автомагнитолы |

Во всех трёх форматах одинаковые теги и встроенная обложка. `done.txt` не учитывает формат, поэтому для каждого формата указывай отдельную папку `-o`.
Во всех трёх форматах одинаковые метаданные и встроенная обложка. Текст песни встраивается только в MP3. `done.txt` не учитывает формат, поэтому для каждого формата указывай отдельную папку `-o`.

### Входной файл

Expand Down
39 changes: 37 additions & 2 deletions README.uk.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ trackfetch "My Playlist.txt" -o ~/Music/"My Playlist"
## Використання

```text
trackfetch [-h] [--track ARTIST - TITLE ...] [-o OUTPUT] [--config CONFIG] [-f {mp3,m4a,opus}] [--title-only] [--delay DELAY] [-s SOURCES] [--disable-sources SOURCES] [--provider-opt NAME.KEY=VALUE] [--match-threshold SCORE] [--title-threshold SCORE] [--list-sources] [--spotify-client-id ID] [--spotify-client-secret SECRET] [--no-logs] [INPUT ...]
trackfetch [-h] [--track ARTIST - TITLE ...] [-o OUTPUT] [--config CONFIG] [-f {mp3,m4a,opus}] [--title-only] [--delay DELAY] [-s SOURCES] [--disable-sources SOURCES] [--provider-opt NAME.KEY=VALUE] [--match-threshold SCORE] [--title-threshold SCORE] [--list-sources] [--spotify-client-id ID] [--spotify-client-secret SECRET] [--no-logs] [--lyrics | --no-lyrics] [INPUT ...]
```

| Параметр | За замовчуванням | Що робить |
Expand All @@ -203,6 +203,7 @@ trackfetch [-h] [--track ARTIST - TITLE ...] [-o OUTPUT] [--config CONFIG] [-f {
| `--spotify-client-id` | `$SPOTIFY_CLIENT_ID` | Client ID для Spotify API. Див. [Дані Spotify](#дані-spotify). |
| `--spotify-client-secret` | `$SPOTIFY_CLIENT_SECRET` | Client secret для Spotify API. |
| `--no-logs` | вимкнено | Не читати `done.txt` і не писати `done.txt` та `failed.txt`. Прогрес минулих запусків не враховується, тому готові пісні не пропускаються. |
| `--lyrics` / `--no-lyrics` | увімкнено | Вбудовувати текст із LRCLIB у теги MP3. Звичайний текст пишеться в `USLT`, синхронізований — ще й у `SYLT`. Якщо тексту немає, завантаження не вважається помилкою. |

```bash
trackfetch songs.txt -o ~/Music/RoadTrip # зберегти в конкретну теку
Expand Down Expand Up @@ -269,6 +270,37 @@ MIME тип. MP3 і Opus можуть вбудовувати всі чотири
як JPEG.
```

### Текст пісні

Для MP3 trackfetch також шукає текст на [LRCLIB](https://lrclib.net/) і
вбудовує його в ID3-теги, щоб плеєр показував слова без інтернету та окремих
файлів `.lrc` чи `.txt`.

| Фрейм | Вміст |
| --- | --- |
| `USLT` | Повний звичайний текст без таймкодів. |
| `SYLT` | Рядки з часовими мітками, лише якщо джерело повернуло синхронізований текст. |

Якщо синхронізований текст є, записуються обидва фрейми: `USLT` потрібен
плеєрам без підтримки `SYLT`. Якщо є лише звичайний текст, записується тільки
`USLT`. Штучні таймкоди не створюються.

Джерело — LRCLIB, ключ API не потрібен. За замовчуванням вбудовування
увімкнено для MP3; вимкнути можна прапорцем `--no-lyrics` або рядком
`lyrics_enabled = false` у конфігу. На формати `m4a` та `opus` це
налаштування не впливає.

Якщо текст не знайдено, сталася помилка мережі або сервер повернув помилку,
завантаження не переривається: MP3 зберігається зі звичайними метаданими. Якщо
у файлі вже був текст, а новий не знайдено, старі фрейми залишаються. Коли
знайдено новий текст, попередні `USLT`/`SYLT` замінюються, а не дублюються.
Інші теги, обкладинка й самі аудіодані не перекодовуються й не пошкоджуються.

```bash
trackfetch songs.txt --format mp3 # вбудувати текст (за замовчуванням)
trackfetch songs.txt --format mp3 --no-lyrics # не додавати текст у MP3
```

### Треки просто в аргументах

Можна не заводити файл, а назвати треки просто в командному рядку:
Expand Down Expand Up @@ -324,6 +356,9 @@ vocadb_min_interval = 0.5
# Запасна обкладинка YouTube
youtube_enabled = true

# Вбудовування тексту пісні в теги MP3
lyrics_enabled = true

# Пороги збігу
match_threshold = 0.6
title_threshold = 0.8
Expand Down Expand Up @@ -387,7 +422,7 @@ trackfetch songs.txt --spotify-client-id твій-id --spotify-client-secret т
| `opus` | **Оригінальний** звук YouTube в Opus, скопійований без перекодування. Найкраща доступна якість | більшість сучасних плеєрів, Android, браузери; не iTunes і не старі пристрої |
| `mp3` (за замовчуванням) | Звук YouTube, **перекодований** у MP3 VBR максимальної якості. Це повторне стиснення з втратами, тому трохи гірше за оригінал | усюди, зокрема старі плеєри й автомагнітоли |

У всіх трьох форматах однакові теги й вбудована обкладинка. `done.txt` не враховує формат, тому для кожного формату вказуй окрему теку `-o`.
У всіх трьох форматах однакові метадані й вбудована обкладинка. Текст пісні вбудовується лише в MP3. `done.txt` не враховує формат, тому для кожного формату вказуй окрему теку `-o`.

### Вхідний файл

Expand Down
8 changes: 8 additions & 0 deletions docs/tldr/trackfetch.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@

`trackfetch {{path/to/songs.txt}} {{[-f|--format]}} {{opus|m4a}}`

- Embed lyrics from LRCLIB into MP3 tags (enabled by default):

`trackfetch {{path/to/songs.txt}} {{[-f|--format]}} {{mp3}}`

- Do not embed lyrics into MP3 tags:

`trackfetch {{path/to/songs.txt}} {{[-f|--format]}} {{mp3}} --no-lyrics`

- Download a few tracks without a text file:

`trackfetch {{"Artist - Title"}} {{"Another Artist - Another Title"}}`
Expand Down
1 change: 1 addition & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ def fake_resolve_metadata(artist, title, source_config, runtime):
monkeypatch.setattr(m, "download_audio", fake_download_audio)
monkeypatch.setattr(m, "download_cover", fake_download_cover)
monkeypatch.setattr(m, "get_spotify", lambda *a, **k: object())
monkeypatch.setattr(m, "fetch_lyrics", lambda *a, **k: None)
monkeypatch.setattr(m.time, "sleep", lambda s: None)
return state

Expand Down
Loading
Loading