Coverage for downtify/cover_sources.py: 85%

149 statements  

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

1"""Find the best cover art available for a track. 

2 

3A track's own source often offers a small cover - Spotify's largest is 

4640px, and a library downloaded by an older Downtify often carries 300px 

5- while the same release is published at 1400px or more elsewhere. This 

6module asks the known sources (Spotify, iTunes, YouTube Music, Deezer) 

7for the release's cover at the configured size, all at once, measures 

8what comes back, and hands back the one the user's preference asks for. 

9 

10iTunes and YouTube Music resize their master image to the size asked 

11for, and send the master itself when it is smaller - never an enlarged 

12copy (measured: asking for 3000px gives 1400-3000px masters) - so a 

13cover's measured size is its real detail. 

14 

15Nothing here writes to a file; downloads (:mod:`downtify.downloader`) 

16and :mod:`downtify.library_upgrade` decide whether a candidate is worth 

17embedding. 

18""" 

19 

20from __future__ import annotations 

21 

22import re 

23from concurrent.futures import ThreadPoolExecutor 

24from dataclasses import dataclass 

25from pathlib import Path 

26from typing import Any, Optional 

27 

28import httpx 

29from loguru import logger 

30 

31from . import deezer, itunes, providers, spotify 

32from .cover_art import extract_cover_art 

33from .file_naming import file_name_key, title_key 

34from .image_size import image_short_side 

35 

36_TIMEOUT = 20 

37 

38SOURCE_FILE = 'file' 

39SOURCE_SPOTIFY = 'spotify' 

40SOURCE_ITUNES = 'itunes' 

41SOURCE_YOUTUBE = 'youtube-music' 

42SOURCE_DEEZER = 'deezer' 

43 

44#: Settings values for "where should artwork come from". 

45PREFERENCE_HIGHEST = 'highest' 

46ARTWORK_SOURCES = ( 

47 PREFERENCE_HIGHEST, 

48 SOURCE_SPOTIFY, 

49 SOURCE_ITUNES, 

50 SOURCE_YOUTUBE, 

51) 

52 

53 

54@dataclass(frozen=True) 

55class CoverCandidate: 

56 """One cover image, already fetched and measured.""" 

57 

58 source: str 

59 data: bytes 

60 width: int 

61 url: str = '' 

62 

63 @property 

64 def size_label(self) -> str: 

65 return f'{self.width}x{self.width}' if self.width else 'unknown' 

66 

67 

68def spotify_upgrade_url(url: str) -> str: 

69 """Point a small Spotify image URL at the largest published size (on 

70 either of Spotify's image hosts, see :func:`spotify.largest_cover_url`). 

71 A library tagged from the 300px variant gets the 640px one without 

72 another API call.""" 

73 

74 return spotify.largest_cover_url(url) 

75 

76 

77def _fetch(url: str) -> Optional[bytes]: 

78 if not url: 

79 return None 

80 try: 

81 resp = httpx.get(url, timeout=_TIMEOUT, follow_redirects=True) 

82 resp.raise_for_status() 

83 except Exception: 

84 logger.debug('Cover fetch failed: {}', url[:120]) 

85 return None 

86 data = resp.content 

87 return data if data else None 

88 

89 

90def _candidate(source: str, url: str) -> Optional[CoverCandidate]: 

91 data = _fetch(url) 

92 if data is None: 

93 return None 

94 width = image_short_side(data) 

95 if not width: 

96 return None 

97 return CoverCandidate(source=source, data=data, width=width, url=url) 

98 

99 

100def _artist_and_title(song: dict[str, Any]) -> tuple[str, str]: 

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

102 artist = artists[0] if artists else (song.get('artist') or '') 

103 title = song.get('name') or song.get('title') or '' 

104 return str(artist), str(title) 

105 

106 

107def same_song(song: dict[str, Any], artists: list[str], title: str) -> bool: 

108 """Whether a search result by *artists* called *title* is *song*: 

109 the titles match (ignoring ``(Deluxe)``/`` - Live`` style suffixes, 

110 see :func:`title_key`) and *song*'s first artist is among *artists* - 

111 so another song's or another artist's cover is never taken.""" 

112 

113 artist, wanted = _artist_and_title(song) 

114 wanted_title = title_key(wanted) 

115 wanted_artist = file_name_key(artist) 

116 if not wanted_title or not wanted_artist: 

117 return False 

118 if title_key(title) != wanted_title: 

119 return False 

120 return any(file_name_key(a) == wanted_artist for a in artists) 

121 

122 

123def _youtube_cover_url(song: dict[str, Any], px: int) -> str: 

124 """The cover of *song*'s YouTube Music release, *px* wide.""" 

125 

126 artist, title = _artist_and_title(song) 

127 if not title: 

128 return '' 

129 try: 

130 results = providers.search_songs(f'{artist} {title}'.strip(), limit=5) 

131 except Exception: 

132 logger.debug('Cover lookup: YouTube Music search failed') 

133 return '' 

134 for result in results: 

135 url = str(result.get('cover_url') or '') 

136 names = [str(a) for a in result.get('artists') or []] 

137 if url and same_song(song, names, str(result.get('name') or '')): 

138 return providers.resize_thumbnail(url, px) 

139 return '' 

140 

141 

142def _deezer_cover_url(song: dict[str, Any], px: int) -> str: 

143 artist, title = _artist_and_title(song) 

144 if not title: 

145 return '' 

146 try: 

147 return deezer.find_track_cover(artist, title, px) 

148 except Exception: 

149 logger.debug('Cover lookup: Deezer search failed') 

150 return '' 

151 

152 

153def _spotify_cover_url(song: dict[str, Any]) -> str: 

154 url = spotify_upgrade_url(str(song.get('cover_url') or '')) 

155 if url: 

156 return url 

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

158 if not re.fullmatch(r'[A-Za-z0-9]{22}', track_id): 

159 return '' 

160 try: 

161 fetched = spotify.track_from_id(track_id) 

162 except Exception: 

163 logger.debug('Cover lookup: Spotify track {} failed', track_id) 

164 return '' 

165 return spotify_upgrade_url(str((fetched or {}).get('cover_url') or '')) 

166 

167 

168def current_cover(path: Path) -> Optional[CoverCandidate]: 

169 """The cover already embedded in (or sitting next to) *path*.""" 

170 

171 data, _mime = extract_cover_art(path) 

172 if not data: 

173 return None 

174 return CoverCandidate( 

175 source=SOURCE_FILE, data=data, width=image_short_side(data) 

176 ) 

177 

178 

179def _source_url(source: str, song: dict[str, Any], px: int) -> str: 

180 if source == SOURCE_SPOTIFY: 

181 return _spotify_cover_url(song) 

182 if source == SOURCE_ITUNES: 

183 return itunes.fetch_artwork_url(song, size=px) 

184 if source == SOURCE_YOUTUBE: 

185 return _youtube_cover_url(song, px) 

186 if source == SOURCE_DEEZER: 

187 return _deezer_cover_url(song, px) 

188 return '' 

189 

190 

191def _candidate_from( 

192 source: str, song: dict[str, Any], px: int 

193) -> Optional[CoverCandidate]: 

194 try: 

195 return _candidate(source, _source_url(source, song, px)) 

196 except Exception: 

197 logger.opt(exception=True).debug('Cover lookup: {} failed', source) 

198 return None 

199 

200 

201def collect_candidates( 

202 song: dict[str, Any], 

203 *, 

204 sources: tuple[str, ...], 

205 px: Optional[int] = None, 

206) -> list[CoverCandidate]: 

207 """Fetch and measure one cover per requested source, all at once, 

208 each asked for *px* pixels (the configured cover size by default, 

209 see :func:`providers.cover_resolution`); returned in *sources*' 

210 order.""" 

211 

212 size = px or providers.cover_resolution() 

213 if not sources: 

214 return [] 

215 with ThreadPoolExecutor( 

216 max_workers=len(sources), thread_name_prefix='downtify-cover' 

217 ) as pool: 

218 futures = [ 

219 pool.submit(_candidate_from, source, song, size) 

220 for source in sources 

221 ] 

222 results = [future.result() for future in futures] 

223 return [c for c in results if c is not None] 

224 

225 

226def _preferred_order(preference: str) -> tuple[str, ...]: 

227 remote = (SOURCE_SPOTIFY, SOURCE_ITUNES, SOURCE_YOUTUBE, SOURCE_DEEZER) 

228 if preference in remote: 

229 return (preference,) + tuple(s for s in remote if s != preference) 

230 return remote 

231 

232 

233def best_cover( 

234 song: dict[str, Any], 

235 *, 

236 current: Optional[CoverCandidate], 

237 preference: str = PREFERENCE_HIGHEST, 

238 px: Optional[int] = None, 

239) -> Optional[CoverCandidate]: 

240 """The cover worth embedding, or ``None`` to leave the file alone. 

241 

242 With a named preference, that source wins as long as it beats what 

243 the file already has; the others are only tried when it has nothing. 

244 With ``highest`` every source is asked and the largest image wins. 

245 A candidate has to be strictly larger than the current cover, so a 

246 re-run never rewrites a file for nothing. Each source is asked for 

247 *px* pixels (the configured cover size by default). 

248 """ 

249 

250 have = current.width if current else 0 

251 order = _preferred_order(preference) 

252 

253 if preference == PREFERENCE_HIGHEST: 

254 candidates = collect_candidates(song, sources=order, px=px) 

255 else: 

256 candidates = [] 

257 for source in order: 

258 candidates = collect_candidates(song, sources=(source,), px=px) 

259 if candidates: 

260 # The preferred source answered; the rest are a fallback 

261 # for when it has nothing at all, not a size contest. 

262 break 

263 

264 if not candidates: 

265 return None 

266 best = max(candidates, key=lambda c: c.width) 

267 return best if best.width > have else None