Coverage for downtify/artist_suggestions.py: 99%

81 statements  

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

1"""Artists to follow, suggested on the Monitor page's Artists tab. 

2 

3Two lists, ranked from what the server already keeps - nothing is 

4searched for while they load: 

5 

6* **listening**: the user's own listens (``DiscoverStore.listens``), 

7 each artist's plays faded by how long ago they were last played, with 

8 Discover's half-life (:data:`downtify.discover.LISTEN_HALF_LIFE_DAYS`); 

9* **library**: the artists of the library the user can see, by track 

10 count, then album count. 

11 

12Artists the user already watches (paused watches too) and compilation 

13placeholders (``Various Artists``) are left out. Following one is a 

14separate step: :func:`artist_candidates` picks the YouTube Music artist 

15an artist watch follows, or leaves the choice to the user. 

16""" 

17 

18from __future__ import annotations 

19 

20import re 

21from datetime import datetime, timezone 

22from typing import Any, Iterable, Optional 

23from urllib.parse import urlsplit 

24 

25from .discover import LISTEN_HALF_LIFE_DAYS, artist_key 

26from .monitor import KIND_ARTIST 

27 

28#: Album artists of compilations, never an artist to follow. 

29_PLACEHOLDERS = frozenset( 

30 artist_key(name) 

31 for name in ( 

32 'Various Artists', 

33 'Various Artist', 

34 'Various', 

35 'Artistes divers', 

36 'Unknown', 

37 'Unknown Artist', 

38 ) 

39) 

40#: A YouTube Music artist's channel id; anything else isn't offered. 

41_CHANNEL_ID = re.compile(r'UC[A-Za-z0-9_-]{22}') 

42#: Where a YouTube Music artist's photo is served from. A photo from 

43#: anywhere else is dropped, not shown. 

44_PHOTO_HOSTS = frozenset({ 

45 'yt3.ggpht.com', 

46 'yt3.googleusercontent.com', 

47 'lh3.googleusercontent.com', 

48}) 

49 

50 

51def _parse_time(value: Any) -> Optional[datetime]: 

52 try: 

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

54 except (TypeError, ValueError): 

55 return None 

56 if parsed.tzinfo is None: 

57 parsed = parsed.replace(tzinfo=timezone.utc) 

58 return parsed 

59 

60 

61def _page( 

62 rows: list[dict[str, Any]], offset: int, limit: int 

63) -> dict[str, Any]: 

64 end = offset + limit 

65 return { 

66 'items': rows[offset:end], 

67 'total': len(rows), 

68 'next_offset': end if end < len(rows) else None, 

69 } 

70 

71 

72def artist_suggestions( 

73 library: Iterable[dict[str, Any]], 

74 listens: Iterable[dict[str, Any]], 

75 watches: Iterable[Any], 

76 *, 

77 listening_offset: int = 0, 

78 library_offset: int = 0, 

79 limit: int = 20, 

80 now: Optional[datetime] = None, 

81) -> dict[str, Any]: 

82 """One page of each list: ``{listening, library, half_life_days}``. 

83 

84 *library* is ``library_artist_index`` rows, *listens* the user's 

85 ``DiscoverStore.listens`` and *watches* their monitor watches - the 

86 caller scopes all three to the user asking. Each list is ``{items, 

87 total, next_offset}``; an item is ``{name, track_count, 

88 album_count}``, and a listening one also has ``plays`` (every listen 

89 counted), ``score`` (the faded plays it is ranked by) and 

90 ``last_played``. A listen with no readable time is left out. 

91 """ 

92 

93 now = now or datetime.now(timezone.utc) 

94 skip = _PLACEHOLDERS | { 

95 artist_key(watch.name) 

96 for watch in watches 

97 if watch.kind == KIND_ARTIST 

98 } 

99 counts: dict[str, dict[str, Any]] = {} 

100 for row in library: 

101 name = str(row.get('name') or '').strip() 

102 key = artist_key(name) 

103 if not key or key in skip: 

104 continue 

105 bucket = counts.setdefault( 

106 key, {'name': name, 'track_count': 0, 'album_count': 0} 

107 ) 

108 bucket['track_count'] += max(0, int(row.get('track_count') or 0)) 

109 bucket['album_count'] += max(0, int(row.get('album_count') or 0)) 

110 in_library = sorted( 

111 (row for row in counts.values() if row['track_count']), 

112 key=lambda row: ( 

113 -row['track_count'], 

114 -row['album_count'], 

115 row['name'].casefold(), 

116 ), 

117 ) 

118 

119 played: dict[str, dict[str, Any]] = {} 

120 for row in listens: 

121 name = str(row.get('name') or '').strip() 

122 key = artist_key(name) 

123 plays = max(0, int(row.get('plays') or 0)) 

124 last = _parse_time(row.get('last_played')) 

125 if not key or key in skip or not plays or last is None: 

126 continue 

127 age_days = max(0.0, (now - last).total_seconds() / 86400) 

128 bucket = played.get(key) 

129 if bucket is None: 

130 known = counts.get(key, {'name': name}) 

131 bucket = played[key] = { 

132 'name': known['name'], 

133 'track_count': known.get('track_count', 0), 

134 'album_count': known.get('album_count', 0), 

135 'plays': 0, 

136 'score': 0.0, 

137 'last_played': last, 

138 } 

139 bucket['plays'] += plays 

140 bucket['score'] += plays * 0.5 ** (age_days / LISTEN_HALF_LIFE_DAYS) 

141 bucket['last_played'] = max(bucket['last_played'], last) 

142 listening = sorted( 

143 played.values(), 

144 key=lambda row: (-row['score'], row['name'].casefold()), 

145 ) 

146 for row in listening: 

147 row['score'] = round(row['score'], 3) 

148 row['last_played'] = ( 

149 row['last_played'].astimezone(timezone.utc).isoformat() 

150 ) 

151 

152 return { 

153 'listening': _page(listening, listening_offset, limit), 

154 'library': _page(in_library, library_offset, limit), 

155 'half_life_days': LISTEN_HALF_LIFE_DAYS, 

156 } 

157 

158 

159def _photo(row: dict[str, Any]) -> str: 

160 value = str(row.get('cover_url') or '') 

161 try: 

162 parsed = urlsplit(value) 

163 port = parsed.port 

164 except ValueError: 

165 return '' 

166 if ( 

167 parsed.scheme == 'https' 

168 and parsed.hostname in _PHOTO_HOSTS 

169 and not parsed.username 

170 and not parsed.password 

171 and port in {None, 443} 

172 ): 

173 return value 

174 return '' 

175 

176 

177def artist_candidates( 

178 name: str, results: Iterable[dict[str, Any]], *, limit: int = 10 

179) -> dict[str, Any]: 

180 """The YouTube Music artists to offer for *name*: ``{candidates, 

181 url}``. 

182 

183 *results* are ``providers.search_artists`` rows. ``url`` is set only 

184 when exactly one of them is named *name* (case and the characters a 

185 file name can't hold ignored, see :func:`artist_key`): that one is 

186 followed without asking. Otherwise - namesakes, or no exact name - the 

187 user picks from ``candidates`` (``{name, artist_id, url, 

188 image_url}``, the ones named *name* first, at most *limit* - a famous 

189 name easily has twenty namesakes), never the top result on its own. 

190 Rows without a valid channel id are left out, and the link is built 

191 from the id, not taken from the row. 

192 """ 

193 

194 wanted = artist_key(name) 

195 named: dict[str, dict[str, str]] = {} 

196 others: dict[str, dict[str, str]] = {} 

197 for row in results: 

198 channel = str(row.get('artist_id') or '') 

199 if not _CHANNEL_ID.fullmatch(channel): 

200 continue 

201 if channel in named or channel in others: 

202 continue 

203 candidate = { 

204 'name': str(row.get('name') or '').strip(), 

205 'artist_id': channel, 

206 'url': f'https://music.youtube.com/channel/{channel}', 

207 'image_url': _photo(row), 

208 } 

209 if artist_key(candidate['name']) == wanted: 

210 named[channel] = candidate 

211 else: 

212 others[channel] = candidate 

213 exact = list(named.values()) 

214 return { 

215 'candidates': [*exact, *others.values()][:limit], 

216 'url': exact[0]['url'] if len(exact) == 1 else None, 

217 }