Repository navigation
Expand file tree
/
Copy pathupdate_lyrics.py
More file actions
executable file
·800 lines (724 loc) · 29.6 KB
/
Copy pathupdate_lyrics.py
File metadata and controls
executable file
·800 lines (724 loc) · 29.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
#!/usr/bin/env -S uv run
# /// script
# dependencies = [
# "structlog",
# "mutagen",
# "requests",
# "rich",
# ]
# ///
import os
import random
import re
import sys
import threading
import time
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import requests
from mutagen.flac import FLAC
from rich.console import Console
from rich.progress import (
BarColumn,
MofNCompleteColumn,
Progress,
SpinnerColumn,
TextColumn,
TimeRemainingColumn,
)
from log import _console_handler, logger
from lrc_format import (
apply_headers,
capitalize_lrc,
capitalize_txt,
has_manual_instrumental_marker,
is_instrumental_marker,
is_invalid_lrc,
is_lrc,
make_instrumental_lrc,
normalize_lrc_text,
normalize_text,
resolve_artist,
)
from lrclib_client import lrclib_headers
MAX_WORKERS = 8
LANGUAGE_TAG = "LYRICS_LANGUAGE" # written by fixtags.py from MusicBrainz (ADR 0002 section 5b)
INSTRUMENTAL_LANGUAGE = "zxx" # ISO 639-3 "no linguistic content"
TRAILING_BRACKET_RE = re.compile(r"\s*[\(\[][^()\[\]]*[\)\]]\s*$")
def strip_trailing_bracket(title: str) -> str:
"""Strip one trailing (...)/[...] group, e.g. '(Live at Wembley)'."""
return TRAILING_BRACKET_RE.sub("", title).strip()
def is_instrumental_language(values: list[str]) -> bool:
"""Does MusicBrainz call the track an instrumental? Only a lone `zxx` counts: `zxx` next to
a real language, `mul`, `und` or no tag say nothing."""
return [str(v).strip().lower() for v in values] == [INSTRUMENTAL_LANGUAGE]
def flactag(song: FLAC | dict, tag: str) -> str:
tags = song.tags if isinstance(song, FLAC) and song.tags else song
if not isinstance(tags, dict):
try:
tags = dict(tags)
except (TypeError, ValueError):
tags = {}
for k in (tag, tag.upper(), tag.lower()):
if tags.get(k):
val = tags[k]
return str(val[0]) if isinstance(val, (list, tuple)) else str(val)
return ""
LRCLIB_GET_URL = "https://lrclib.net/api/get"
MAX_ATTEMPTS = 4 # per request; the shared Pacer spaces the attempts
MAX_RETRY_AFTER = 300.0
# Spacing like the official client (lrcget): wait BASE_INTERVAL plus up to REQUEST_JITTER after
# each response, about 85 requests/min with latency. No burst: bursts provoked 429s (ADR 0007 s.4).
BASE_INTERVAL = 0.5
REQUEST_JITTER = 0.25
DEFAULT_RETRY_AFTER = 1.0 # a 429 without Retry-After, as lrcget treats it
RETRY_BACKOFF = 1.0 # seconds before the 2nd attempt after a 5xx/network error; doubles each time
MAX_INTERVAL = 8.0
RELAX_AFTER = 10 # consecutive successes before the interval shrinks again
DOWN_AFTER = 5 # failures in a row, with no success for DOWN_WINDOW seconds, open the circuit
DOWN_WINDOW = 60.0
# (cool-down seconds, workers) for each pass over tracks that lrclib failed to answer
RETRY_ROUNDS = ((30, 2), (60, 2))
class Pacer:
"""Shared request pacing: one request in flight at a time.
lrclib asks clients to send requests sequentially. Each request starts `interval` (plus up to
REQUEST_JITTER) after the previous one finished. A 429 (a real rate limit) doubles the interval
and every run of successes shrinks it again, so it settles at whatever rate lrclib tolerates.
5xx and network errors do not change the pacing.
"""
def __init__(self) -> None:
self._lock = threading.Lock()
self._slot = threading.Semaphore(1)
self._interval = BASE_INTERVAL
self._next_start = 0.0
self._floor_until = 0.0 # Retry-After: no request may start before this
self._raised_at = 0.0
self._successes = 0
self._fail_streak = 0
self._last_success = time.monotonic()
self._down_reported = False
self._auth_failed = False
self._auth_reported = False
def acquire(self) -> float:
"""Wait for the single request slot and for the next start time; return the start time.
Every acquire() must be paired with a release() once the request has finished.
"""
self._slot.acquire()
with self._lock:
now = time.monotonic()
start = max(now, self._next_start, self._floor_until)
if start > now:
time.sleep(start - now)
return start
def release(self) -> None:
with self._lock:
gap = self._interval + random.uniform(0, REQUEST_JITTER)
self._next_start = max(self._next_start, time.monotonic() + gap)
self._slot.release()
def failure(
self,
started_at: float,
retry_after: float | None = None,
rate_limited: bool = False,
) -> tuple[float, bool]:
"""Record a failed request; return (interval, whether this raised it).
Only a rate limit (429) widens the interval; other failures just count towards the
circuit breaker. A request that started before the last raise cannot escalate it again.
"""
with self._lock:
now = time.monotonic()
self._successes = 0
self._fail_streak += 1
raised = False
if rate_limited and started_at > self._raised_at and self._interval < MAX_INTERVAL:
self._interval = min(self._interval * 2, MAX_INTERVAL)
self._raised_at = now
self._next_start = max(self._next_start, now + self._interval)
raised = True
if rate_limited and retry_after is None:
retry_after = DEFAULT_RETRY_AFTER
if retry_after is not None:
self._floor_until = max(self._floor_until, now + min(retry_after, MAX_RETRY_AFTER))
return self._interval, raised
def success(self) -> tuple[float, bool]:
"""Record a good answer; return (interval, whether this relaxed it)."""
with self._lock:
self._fail_streak = 0
self._last_success = time.monotonic()
self._successes += 1
relaxed = False
if self._successes >= RELAX_AFTER and self._interval > BASE_INTERVAL:
self._interval = max(BASE_INTERVAL, self._interval * 0.75)
self._successes = 0
relaxed = True
return self._interval, relaxed
def is_down(self) -> bool:
"""True after DOWN_AFTER failures in a row with no success for DOWN_WINDOW seconds,
or once lrclib has rejected the app id (retrying cannot help)."""
with self._lock:
return self._auth_failed or (
self._fail_streak >= DOWN_AFTER
and time.monotonic() - self._last_success >= DOWN_WINDOW
)
def reject_credentials(self) -> bool:
"""Record a 401; True only the first time, so the error is logged once."""
with self._lock:
first = not self._auth_reported
self._auth_failed = True
self._auth_reported = True
return first
def report_down_once(self) -> bool:
"""True the first time it is called while the circuit is open (for one log line)."""
if not self.is_down():
return False
with self._lock:
first = not self._down_reported
self._down_reported = True
return first
def close_circuit(self) -> None:
"""Forget the failure streak before a retry round; keep the learned interval."""
with self._lock:
self._fail_streak = 0
self._last_success = time.monotonic()
self._down_reported = False
self._auth_failed = False # a retry round probes once more
self._floor_until = 0.0
def _lrclib_get(session: requests.Session, pacer: Pacer, params: dict, title: str) -> dict | None:
"""One lrclib lookup: the JSON body on 200, {} on 404, None if lrclib kept failing."""
reason = ""
if pacer.is_down():
return None # circuit open: defer to the retry rounds instead of waiting again
for attempt in range(MAX_ATTEMPTS):
started_at = pacer.acquire()
retry_after = None
rate_limited = False
try:
try:
response = session.get(
LRCLIB_GET_URL, params=params, headers=lrclib_headers(), timeout=10
)
if response.status_code == 401:
if pacer.reject_credentials():
logger.error(
"lrclib rejected the Lrclib-App-Id header (401); see lrclib_client.py"
)
return None
if response.status_code in (200, 404):
body = response.json() if response.status_code == 200 else {}
interval, relaxed = pacer.success()
if relaxed:
logger.info(f"lrclib is answering again; one request per {interval:.1f} s")
return body
reason = f"HTTP {response.status_code}"
rate_limited = response.status_code == 429
header = response.headers.get("Retry-After")
if (
response.status_code in (429, 503)
and header
and header.replace(".", "", 1).isdigit()
):
# lrclib requires honoring Retry-After plus up to 30% random jitter
retry_after = float(header) * (1 + random.uniform(0, 0.3))
except requests.RequestException as e:
reason = type(e).__name__
finally:
pacer.release()
interval, raised = pacer.failure(started_at, retry_after, rate_limited)
if raised:
logger.warning(
f"lrclib rate limit hit ({reason}); slowing to one request per {interval:.1f} s"
)
if pacer.report_down_once():
logger.warning("lrclib looks down; deferring the remaining tracks to the retry rounds")
if pacer.is_down():
break
if not rate_limited and retry_after is None and attempt < MAX_ATTEMPTS - 1:
# 5xx / network error: plain backoff, the pacing interval stays as it is
time.sleep(RETRY_BACKOFF * 2**attempt * (1 + random.uniform(0, 0.3)))
return None
def _fetch_one(
flac_path: str, session: requests.Session, pacer: Pacer | None = None
) -> tuple[str, str, str, str, str, str, str, str]:
"""Read tags, fetch/upgrade lyrics, apply LRC metadata headers from FLAC tags.
Returns:
(flac_path, artist, title, lyrics_text, lyrics_type, status, discogs_id, track)
"""
pacer = pacer or Pacer()
if not os.path.isfile(flac_path):
return flac_path, "", "", "", "none", "skip", "", ""
discogs_id = ""
track = ""
artist = ""
title = ""
existing_lyrics = ""
try:
song = FLAC(flac_path)
artist = resolve_artist(flactag(song, "ALBUMARTIST"), flactag(song, "ARTIST"))
title = flactag(song, "TITLE")
discogs_id = flactag(song, "DISCOGS_RELEASE_ID")
track = flactag(song, "TRACKNUMBER")
album = flactag(song, "ALBUM")
existing_lyrics = flactag(song, "LYRICS").strip()
instrumental_language = is_instrumental_language(list(song.get(LANGUAGE_TAG) or []))
length = float(song.info.length) if song.info and hasattr(song.info, "length") else 0.0
except Exception as e: # noqa: BLE001
logger.warning(f"Could not read FLAC tags for {flac_path}: {e}")
return flac_path, "", "", "", "none", "error", "", ""
if not artist or not title:
logger.info(f"Missing ALBUMARTIST/ARTIST or TITLE tag in {flac_path}")
return flac_path, artist, title, "", "none", "error", discogs_id, track
# Check existing embedded FLAC lyrics
if existing_lyrics and is_instrumental_marker(existing_lyrics):
return (
flac_path,
artist,
title,
existing_lyrics,
"instrumental",
"skip",
discogs_id,
track,
)
if existing_lyrics and has_manual_instrumental_marker(existing_lyrics):
# User (or another tool) left an informal/incomplete instrumental marker —
# normalize to the canonical block without hitting lrclib.net. This is a
# syntax fix, not new information, so it's counted as 'fix' not 'new'.
marker_lrc = make_instrumental_lrc(artist, title, album, length)
return (
flac_path,
artist,
title,
marker_lrc,
"instrumental",
"fix",
discogs_id,
track,
)
if instrumental_language and not is_lrc(existing_lyrics):
# MusicBrainz says the track has no vocals: no lrclib request (it can only return wrong
# lyrics for it). Plain text is replaced; an existing LRC is left to the rule below.
logger.info(f"Instrumental via {LANGUAGE_TAG}={INSTRUMENTAL_LANGUAGE}: {artist} - {title}")
marker_lrc = make_instrumental_lrc(artist, title, album, length)
return (
flac_path,
artist,
title,
marker_lrc,
"instrumental",
"new",
discogs_id,
track,
)
if existing_lyrics and is_lrc(existing_lyrics):
# An existing LRC is never replaced by another source (no lrclib request at all); it is only
# corrected in place: headers, typographic characters and line capitalization.
updated_lrc = apply_headers(existing_lyrics, artist, title, album, length)
updated_lrc = capitalize_lrc(normalize_lrc_text(updated_lrc))
if updated_lrc != existing_lyrics:
return (
flac_path,
artist,
title,
updated_lrc,
"lrc",
"fix",
discogs_id,
track,
)
return (
flac_path,
artist,
title,
existing_lyrics,
"lrc",
"skip",
discogs_id,
track,
)
stripped_title = strip_trailing_bracket(title)
track_names = [title] if stripped_title == title else [title, stripped_title]
duration = str(round(length))
# Try each artist (ALBUMARTIST, then the track's own ARTIST when it differs: compilations and
# soundtracks have a "Various Artists" album artist that lrclib does not know), and for each the
# track_name (full title, then stripped) with album_name, then without.
track_artist = flactag(song, "ARTIST")
search_artists = (
[artist] if not track_artist or track_artist == artist else [artist, track_artist]
)
variants = [
v
for artist_name in search_artists
for track_name in track_names
for v in (
{
"artist_name": artist_name,
"track_name": track_name,
"album_name": album,
"duration": duration,
},
{
"artist_name": artist_name,
"track_name": track_name,
"duration": duration,
},
)
]
data = {}
found_via_stripped = False
for params in variants:
body = _lrclib_get(session, pacer, params, title)
if body is None:
# lrclib is throttling or down, which is not the same as "not found": stop probing
# further variants and never write or remove anything for this track.
return flac_path, artist, title, "", "none", "failed", discogs_id, track
if body:
data = body
found_via_stripped = params["track_name"] != title
break
if found_via_stripped:
logger.info(f"Lyrics found via stripped title '{stripped_title}' (original: '{title}')")
if data.get("instrumental"):
marker_lrc = make_instrumental_lrc(artist, title, album, length)
if marker_lrc == existing_lyrics:
return (
flac_path,
artist,
title,
existing_lyrics,
"instrumental",
"skip",
discogs_id,
track,
)
return (
flac_path,
artist,
title,
marker_lrc,
"instrumental",
"new",
discogs_id,
track,
)
if data.get("syncedLyrics"):
lrc = re.sub(r"\[(\d{2}:\d{2}\.\d{2})\d\]", r"[\1]", data["syncedLyrics"])
if is_invalid_lrc(lrc):
logger.warning(f"Invalid LRC timestamps from lrclib, skipping: {title} ({artist})")
else:
lrc = apply_headers(lrc, artist, title, album, length)
lrc = capitalize_lrc(normalize_lrc_text(lrc))
if lrc == existing_lyrics:
return (
flac_path,
artist,
title,
existing_lyrics,
"lrc",
"skip",
discogs_id,
track,
)
return flac_path, artist, title, lrc, "lrc", "new", discogs_id, track
if data.get("plainLyrics") and not existing_lyrics:
txt = capitalize_txt(normalize_text(data["plainLyrics"]))
return flac_path, artist, title, txt, "txt", "new", discogs_id, track
# Nothing new fetched — keep what is on disk (only TXT reaches this point: an existing LRC was
# handled above), normalizing characters and capitalization if needed.
if existing_lyrics:
fixed = capitalize_txt(normalize_text(existing_lyrics))
if fixed != existing_lyrics:
return flac_path, artist, title, fixed, "txt", "fix", discogs_id, track
return (
flac_path,
artist,
title,
existing_lyrics,
"txt",
"skip",
discogs_id,
track,
)
logger.warning(
f"No lyrics found at lrclib: '{title}' (artist searched: '{artist}', album: '{album}')"
)
return flac_path, artist, title, "", "none", "skip", discogs_id, track
def _collect_tracks(flacdir: str) -> list[str]:
"""Return the path of every FLAC that has a DISCOGS_RELEASE_ID."""
tracks = []
for root, _, files in os.walk(flacdir):
flacs = sorted(f for f in files if f.endswith(".flac"))
if not flacs:
continue
first = os.path.join(root, flacs[0])
try:
song = FLAC(first)
discogs_id_str = flactag(song, "DISCOGS_RELEASE_ID")
int(discogs_id_str)
except (ValueError, TypeError):
continue
for f in flacs:
tracks.append(os.path.join(root, f))
return tracks
def _write_if_changed(path: Path, text: str) -> bool:
"""Write text to path unless it already holds exactly that; True if it was written."""
try:
if path.read_text(encoding="utf-8") == text:
return False
except (OSError, UnicodeDecodeError):
pass
path.write_text(text, encoding="utf-8")
return True
def prune_cache(
lyrics_dir: Path, tracks: dict[str, list[tuple[str, str]]], broken_dirs: set[str]
) -> list[Path]:
"""Remove lyrics cache files {id}_{key}.lrc|txt whose key no track of that id has any more.
tracks maps a directory to the (discogs_id, track) of every track collected from it, including
tracks whose lookup failed. The cache key has no disc number, so an id is only pruned when all
of its tracks come from one directory (an id spread over disc subfolders, or a partial run of
one of them, cannot be judged) and no track of that directory was unreadable.
"""
keys_by_id: dict[str, set[str]] = {}
dirs_by_id: dict[str, set[str]] = {}
for directory, entries in tracks.items():
for discogs_id, track in entries:
if discogs_id:
keys_by_id.setdefault(discogs_id, set()).add(track)
dirs_by_id.setdefault(discogs_id, set()).add(directory)
removed: list[Path] = []
for discogs_id, keys in keys_by_id.items():
dirs = dirs_by_id[discogs_id]
if len(dirs) != 1 or dirs & broken_dirs:
continue
for path in sorted(lyrics_dir.glob(f"{discogs_id}_*")):
if path.suffix in (".lrc", ".txt") and path.stem[len(discogs_id) + 1 :] not in keys:
path.unlink()
removed.append(path)
return removed
def _apply_result(result: tuple, stats: dict, lyrics_dir: Path) -> None:
"""Count one finished track and write its lyrics to the FLAC tag and the lyrics cache."""
flac_path, artist, title, lyrics, lyric_type, action, discogs_id, track = result
if lyric_type == "lrc":
stats["lrc"] += 1
elif lyric_type == "txt":
stats["txt"] += 1
elif lyric_type == "instrumental":
stats["instrumental"] += 1
else:
stats["none"] += 1
if action in ("new", "fix"):
stats["new" if action == "new" else "fixed"] += 1
try:
t = FLAC(flac_path)
if not t.tags:
t.add_tags()
t["LYRICS"] = [lyrics]
t.save()
try:
os.utime(flac_path, None)
except OSError as e:
logger.warning(f"Could not touch file mtime for {flac_path}: {e}")
if lyric_type == "instrumental":
logger.success(f"Instrumental track marked: {title} ({artist})")
elif action == "fix":
logger.success(f"Lyrics fixed: {title} ({artist})")
else:
kind = "LRC" if lyric_type == "lrc" else "TXT"
logger.success(f"{kind} lyrics added: {title} ({artist})")
except OSError as e:
logger.error(f"Could not save lyrics for {flac_path}: {e}")
if discogs_id:
lrc_file = lyrics_dir / f"{discogs_id}_{track}.lrc"
txt_file = lyrics_dir / f"{discogs_id}_{track}.txt"
if not lyrics:
lrc_file.unlink(missing_ok=True)
txt_file.unlink(missing_ok=True)
else:
ext = (
"lrc" if lyric_type in ("lrc", "instrumental") or lyrics.startswith("[") else "txt"
)
target_file = lyrics_dir / f"{discogs_id}_{track}.{ext}"
other_file = txt_file if ext == "lrc" else lrc_file
other_file.unlink(missing_ok=True)
stats[
"cache_written" if _write_if_changed(target_file, lyrics) else "cache_unchanged"
] += 1
def _run_pass(
paths: list[str],
workers: int,
session: requests.Session,
pacer: Pacer,
handle: Callable[[tuple | None, str], None],
on_interrupt: Callable[[], None],
) -> list[str]:
"""Fetch lyrics for paths on a thread pool; pass each result to handle().
handle() receives the result tuple, or None if the worker raised. Returns the paths
lrclib failed to answer, so the caller can retry them later.
"""
failed = []
with ThreadPoolExecutor(max_workers=workers) as executor:
futures = {executor.submit(_fetch_one, path, session, pacer): path for path in paths}
try:
for future in as_completed(futures):
try:
result = future.result()
except Exception as e: # noqa: BLE001
logger.error(f"Fetch error: {e}")
handle(None, futures[future])
continue
if result[5] == "failed":
failed.append(futures[future])
handle(result, futures[future])
except KeyboardInterrupt:
logger.warning("Interrupted by user (Ctrl+C). Exiting...")
executor.shutdown(wait=False, cancel_futures=True)
on_interrupt()
return failed
def main() -> None:
if len(sys.argv) != 2:
from config import nzbdir as flacdir
else:
flacdir = sys.argv[1]
logger.info(f"Scanning tracks in {flacdir}")
tracks = _collect_tracks(flacdir)
total = len(tracks)
logger.info(
f"Fetching lyrics for {total} tracks with {MAX_WORKERS} workers (lrclib requests go one at a time)"
)
stats = {
"lrc": 0,
"txt": 0,
"none": 0,
"instrumental": 0,
"new": 0,
"fixed": 0,
"failed": 0,
"cache_written": 0,
"cache_unchanged": 0,
"cache_pruned": 0,
}
done = 0
last_report = time.monotonic()
is_tty = sys.stderr.isatty()
data_dir = Path(
os.environ.get("CONFIG_DIR") or getattr(__import__("config"), "config_dir", ".")
)
lyrics_dir = data_dir / "lyrics"
lyrics_dir.mkdir(parents=True, exist_ok=True)
session = requests.Session()
adapter = requests.adapters.HTTPAdapter(pool_connections=MAX_WORKERS, pool_maxsize=MAX_WORKERS)
session.mount("https://", adapter)
pacer = Pacer()
console = Console(stderr=True)
progress = Progress(
SpinnerColumn(),
TextColumn("[bold blue]Progress:"),
BarColumn(),
MofNCompleteColumn(),
TextColumn("• [cyan]LRC:[/cyan] {task.fields[lrc]}"),
TextColumn("[green]TXT:[/green] {task.fields[txt]}"),
TextColumn("[bright_black]None:[/bright_black] {task.fields[none]}"),
TextColumn("[yellow]Instrumental:[/yellow] {task.fields[instrumental]}"),
TextColumn("[magenta]New:[/magenta] {task.fields[new]}"),
TextColumn("[blue]Fixed:[/blue] {task.fields[fixed]}"),
TextColumn("[bold red]Failed:[/bold red] {task.fields[failed]}"),
TimeRemainingColumn(),
console=console,
disable=not is_tty,
)
task_id = progress.add_task("Fetching", total=total, **stats)
orig_stream = _console_handler.stream
failed_info: dict[str, tuple[str, str]] = {}
cache_tracks: dict[str, list[tuple[str, str]]] = {} # directory -> (discogs_id, track)
broken_dirs: set[str] = set() # directories with a track whose key is unknown
def on_interrupt() -> None:
if is_tty:
_console_handler.stream = orig_stream
os._exit(130)
def handle(result: tuple | None, first_pass: bool, path: str) -> None:
nonlocal done, last_report
directory = os.path.dirname(path)
if result is None or (result[5] == "error" and not result[6]):
broken_dirs.add(directory) # unreadable track: its cache key is unknown
if result is not None:
path, artist, title, action = result[0], result[1], result[2], result[5]
entries = cache_tracks.setdefault(directory, [])
if (result[6], result[7]) not in entries:
entries.append((result[6], result[7]))
if action == "failed":
# lrclib did not answer: nothing is written or removed for this track.
if first_pass:
stats["failed"] += 1
failed_info[path] = (artist, title)
else:
if not first_pass:
stats["failed"] -= 1 # recovered in a retry pass
failed_info.pop(path, None)
_apply_result(result, stats, lyrics_dir)
if not first_pass:
progress.update(task_id, advance=0, **stats)
return
done += 1
progress.update(task_id, advance=1, **stats)
if not is_tty and time.monotonic() - last_report >= 5:
logger.info(
f"Progress: {done}/{total} tracks — "
f"LRC: {stats['lrc']} TXT: {stats['txt']} "
f"None: {stats['none']} Instrumental: {stats['instrumental']} "
f"New: {stats['new']} Fixed: {stats['fixed']} "
f"Failed: {stats['failed']}"
)
last_report = time.monotonic()
failed: list[str] = []
with progress:
if is_tty:
_console_handler.stream = sys.stderr
try:
failed = _run_pass(
tracks,
MAX_WORKERS,
session,
pacer,
lambda r, p: handle(r, True, p),
on_interrupt,
)
for cooldown, workers in RETRY_ROUNDS:
if not failed:
break
logger.warning(
f"{len(failed)} tracks got no answer from lrclib; "
f"retrying in {cooldown} s with {workers} workers"
)
time.sleep(cooldown)
pacer.close_circuit()
failed = _run_pass(
failed,
workers,
session,
pacer,
lambda r, p: handle(r, False, p),
on_interrupt,
)
except KeyboardInterrupt:
logger.warning("Interrupted by user (Ctrl+C). Exiting...")
on_interrupt()
finally:
if is_tty:
_console_handler.stream = orig_stream
for path in failed:
artist, title = failed_info.get(path, ("", ""))
logger.warning(f"Lyrics not fetched, lrclib unavailable: {artist} - {title} ({path})")
# Only after a complete run (an interrupted one exits above): drop cache entries of tracks that
# no longer exist, e.g. after a TRACKNUMBER retag.
for stale in prune_cache(lyrics_dir, cache_tracks, broken_dirs):
stats["cache_pruned"] += 1
logger.info(f"Removed stale lyrics cache entry: {stale.name}")
logger.info(
f"Done — LRC: {stats['lrc']} TXT: {stats['txt']} "
f"None: {stats['none']} Instrumental: {stats['instrumental']} "
f"New: {stats['new']} Fixed: {stats['fixed']} Failed: {stats['failed']} — "
f"Cache: {stats['cache_written']} written, {stats['cache_unchanged']} unchanged, "
f"{stats['cache_pruned']} pruned"
)
if __name__ == "__main__":
main()