Coverage for downtify/lyrics_cache.py: 84%

83 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-21 22:18 +0000

1"""Which lyrics providers have already been asked about a track. 

2 

3A provider that has no lyrics for a song today usually still has none 

4tomorrow, so every download and every library pass would otherwise repeat 

5the same misses. Hits are remembered too, but only so a re-download can 

6tell how the file got its lyrics; a miss expires after a while, since 

7catalogues do grow. 

8""" 

9 

10from __future__ import annotations 

11 

12import unicodedata 

13from datetime import datetime, timedelta, timezone 

14from pathlib import Path 

15from typing import Any, Optional 

16 

17from loguru import logger 

18 

19from .db.config import Dialect 

20from .db.core import Database, as_database 

21 

22#: How long a "this provider has nothing" answer is trusted. 

23DEFAULT_MISS_TTL_DAYS = 30 

24 

25 

26def _now() -> datetime: 

27 return datetime.now(timezone.utc) 

28 

29 

30def _parse(value: Optional[str]) -> Optional[datetime]: 

31 try: 

32 parsed = datetime.fromisoformat(str(value)) 

33 except (TypeError, ValueError): 

34 return None 

35 return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc) 

36 

37 

38def _clean(text: Any) -> str: 

39 return unicodedata.normalize('NFKC', str(text or '')).strip().casefold() 

40 

41 

42def song_key(song: dict[str, Any]) -> str: 

43 """Stable key for a song: its Spotify id, else artist and title. 

44 

45 Falls back to the text so tracks from YouTube Music, a CSV import or a 

46 library pass are cached too. 

47 """ 

48 

49 track_id = str(song.get('song_id') or '').strip() 

50 if track_id: 

51 return f'id:{track_id}' 

52 artists = song.get('artists') or [] 

53 artist = _clean(artists[0] if artists else song.get('artist')) 

54 title = _clean(song.get('name') or song.get('title')) 

55 if not title: 

56 return '' 

57 return f'text:{artist}|{title}' 

58 

59 

60class LyricsLookupCache: 

61 """Remembers, per song and provider, whether lyrics were found.""" 

62 

63 def __init__( 

64 self, 

65 db_path: str | Path | Database, 

66 miss_ttl_days: int = DEFAULT_MISS_TTL_DAYS, 

67 ) -> None: 

68 self.db = as_database(db_path, 'library') 

69 if isinstance(db_path, Database): 

70 self._path = str(self.db.path) if self.db.path else None 

71 else: 

72 self._path = str(db_path) 

73 self.miss_ttl = timedelta(days=miss_ttl_days) 

74 self._init_db() 

75 

76 def _connect(self): 

77 return self.db.connect() 

78 

79 def _init_db(self) -> None: 

80 # PostgreSQL gets its schema from the migrations. 

81 if self.db.dialect is not Dialect.SQLITE: 

82 return 

83 with self._connect() as conn: 

84 conn.execute(""" 

85 CREATE TABLE IF NOT EXISTS lyrics_lookups ( 

86 song_key TEXT NOT NULL, 

87 provider TEXT NOT NULL, 

88 found INTEGER NOT NULL, 

89 checked_at TEXT NOT NULL, 

90 PRIMARY KEY (song_key, provider) 

91 ) 

92 """) 

93 

94 def should_skip(self, key: str, provider: str) -> bool: 

95 """True when this provider recently had nothing for this song.""" 

96 

97 if not key: 

98 return False 

99 try: 

100 with self._connect() as conn: 

101 row = conn.execute( 

102 """SELECT found, checked_at FROM lyrics_lookups 

103 WHERE song_key = ? AND provider = ?""", 

104 (key, provider), 

105 ).fetchone() 

106 except Exception: 

107 logger.opt(exception=True).warning('Lyrics cache read failed') 

108 return False 

109 if row is None or row['found']: 

110 return False 

111 checked = _parse(row['checked_at']) 

112 return bool(checked and _now() - checked < self.miss_ttl) 

113 

114 def record(self, key: str, provider: str, found: bool) -> None: 

115 if not key: 

116 return 

117 try: 

118 with self._connect() as conn: 

119 conn.execute( 

120 """INSERT INTO lyrics_lookups 

121 (song_key, provider, found, checked_at) 

122 VALUES (?, ?, ?, ?) 

123 ON CONFLICT(song_key, provider) DO UPDATE SET 

124 found = excluded.found, 

125 checked_at = excluded.checked_at""", 

126 (key, provider, 1 if found else 0, _now().isoformat()), 

127 ) 

128 except Exception: 

129 logger.opt(exception=True).warning('Lyrics cache write failed') 

130 

131 def forget(self, key: str) -> int: 

132 """Drop what's known about a song, so every provider is tried again.""" 

133 

134 if not key: 

135 return 0 

136 try: 

137 with self._connect() as conn: 

138 cur = conn.execute( 

139 'DELETE FROM lyrics_lookups WHERE song_key = ?', (key,) 

140 ) 

141 return cur.rowcount 

142 except Exception: 

143 logger.opt(exception=True).warning('Lyrics cache delete failed') 

144 return 0 

145 

146 def clear(self) -> int: 

147 try: 

148 with self._connect() as conn: 

149 cur = conn.execute('DELETE FROM lyrics_lookups') 

150 return cur.rowcount 

151 except Exception: 

152 logger.opt(exception=True).warning('Lyrics cache clear failed') 

153 return 0