Coverage for downtify/isrc.py: 71%

107 statements  

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

1"""ISRC codes: the recording's own ID, written into every download. 

2 

3An ISRC (International Standard Recording Code) is the code a label gives 

4a recording - ``USCM51600061`` is Drake's *Keep The Family Close* - and 

5every streaming catalogue carries it. Two files with the same ISRC hold 

6the same recording whatever their titles say (*Tum Hi Ho* and *Tum Hi Ho 

7(From "Aashiqui 2")*, a ``feat.`` one catalogue adds and another leaves 

8out), so Downtify matches a song the library already has by it first 

9(:mod:`downtify.library_songs`), and its name and length only after. 

10 

11Unlike MusicBrainz IDs, an ISRC is not part of how Navidrome tells songs 

12and albums apart (its persistent IDs), so writing one into a file it 

13already knows changes nothing there. 

14 

15Where a download's ISRC comes from (:func:`for_song`): 

16 

17* the song itself, when its catalogue gave one (MusicBrainz); 

18* Deezer's track, for a song from Deezer (its album and playlist rows 

19 leave the code out; the track itself has it); 

20* otherwise a Deezer search: only a result with the same first artist and 

21 title (as :mod:`downtify.library_songs` compares them) and a length 

22 within :data:`LENGTH_SECONDS`, and only when every such result agrees 

23 on the code. Anything less certain writes nothing. 

24 

25Tags: ``TSRC`` in MP3s, ``ISRC`` in FLAC, Ogg and Opus, and the iTunes 

26``ISRC`` atom in M4A - what MusicBrainz Picard and players read. 

27""" 

28 

29from __future__ import annotations 

30 

31import re 

32from pathlib import Path 

33from typing import Any, Optional 

34 

35from loguru import logger 

36from mutagen import File as MutagenFile 

37from mutagen.id3 import ID3, TSRC, ID3NoHeaderError 

38from mutagen.mp4 import MP4, MP4FreeForm 

39 

40#: Two catalogues' lengths of one recording differ by a few seconds 

41#: (Spotify has Drake's *Keep The Family Close* at 328 s, Deezer at 331 s): 

42#: the library's own same-song tolerance 

43#: (:data:`downtify.library_songs.SAME_SONG_SECONDS`). 

44LENGTH_SECONDS = 3.0 

45 

46_SEARCH_URL = 'https://api.deezer.com/search' 

47_TRACK_URL = 'https://api.deezer.com/track/' 

48_MP4_KEY = '----:com.apple.iTunes:ISRC' 

49_FORM = re.compile(r'^[A-Z]{2}[A-Z0-9]{3}\d{7}$') 

50 

51 

52def normalize(value: Any) -> str: 

53 """*value* as a 12-character ISRC (``US-CM5-16-00061`` and 

54 ``uscm51600061`` both read ``USCM51600061``), ``''`` when it isn't 

55 one.""" 

56 

57 code = re.sub(r'[\s-]', '', str(value or '')).upper() 

58 return code if _FORM.match(code) else '' 

59 

60 

61# ── Tags ──────────────────────────────────────────────────────────────── 

62 

63 

64def read(path: Path) -> str: 

65 """The ISRC tag of an audio file, ``''`` without one.""" 

66 

67 suffix = path.suffix.lower() 

68 try: 

69 if suffix == '.mp3': 

70 frames = ID3(str(path)).getall('TSRC') 

71 return normalize(frames[0].text[0]) if frames else '' 

72 audio = MutagenFile(str(path)) 

73 except (ID3NoHeaderError, Exception): # noqa: BLE001 # unreadable: none 

74 return '' 

75 if audio is None or audio.tags is None: 

76 return '' 

77 if isinstance(audio, MP4): 

78 values = audio.tags.get(_MP4_KEY) or [] 

79 return ( 

80 normalize(bytes(values[0]).decode('utf-8', 'replace')) 

81 if values 

82 else '' 

83 ) 

84 values = audio.tags.get('isrc') or audio.tags.get('ISRC') or [] 

85 return normalize(values[0]) if values else '' 

86 

87 

88def write(path: Path, code: str) -> bool: 

89 """Write *code* as *path*'s ISRC tag (replacing one there). Whether 

90 it was written.""" 

91 

92 code = normalize(code) 

93 if not code or not path.is_file(): 

94 return False 

95 suffix = path.suffix.lower() 

96 try: 

97 if suffix == '.mp3': 

98 try: 

99 tags = ID3(str(path)) 

100 except ID3NoHeaderError: 

101 tags = ID3() 

102 version = tags.version[1] if tags.version[1] in {3, 4} else 4 

103 tags.setall('TSRC', [TSRC(encoding=3, text=[code])]) 

104 tags.save(str(path), v2_version=version) 

105 return True 

106 audio = MutagenFile(str(path)) 

107 if audio is None: 

108 return False 

109 if audio.tags is None: 

110 audio.add_tags() 

111 if isinstance(audio, MP4): 

112 audio.tags[_MP4_KEY] = [MP4FreeForm(code.encode('utf-8'))] 

113 else: 

114 audio.tags['ISRC'] = [code] 

115 audio.save() 

116 return True 

117 except Exception: 

118 logger.opt(exception=True).warning( 

119 'Could not write the ISRC of {}', path.name 

120 ) 

121 return False 

122 

123 

124# ── Finding a song's ISRC ─────────────────────────────────────────────── 

125 

126 

127def _same_song(song: dict[str, Any], row: dict[str, Any]) -> bool: 

128 # Imported here: the library reads tags through this module. 

129 from .library_songs import _key # noqa: PLC0415 

130 

131 artist = row.get('artist') if isinstance(row.get('artist'), dict) else {} 

132 wanted = _key( 

133 song.get('artists') or [song.get('artist')], song.get('name') 

134 ) 

135 found = _key([artist.get('name')], row.get('title')) 

136 if not wanted or wanted != found: 

137 return False 

138 length = float(song.get('duration') or 0) 

139 other = float(row.get('duration') or 0) 

140 return bool(length and other) and abs(length - other) <= LENGTH_SECONDS 

141 

142 

143def _track_isrc(track_id: Any) -> str: 

144 from . import deezer # noqa: PLC0415 # see _same_song 

145 

146 try: 

147 return normalize( 

148 deezer._get_json(f'{_TRACK_URL}{track_id}').get('isrc') 

149 ) # noqa: SLF001 

150 except ValueError: 

151 return '' 

152 

153 

154def find_on_deezer(song: dict[str, Any]) -> str: 

155 """The ISRC of *song* on Deezer, when the search finds it beyond doubt 

156 (see the module notes); ``''`` otherwise, including when Deezer 

157 doesn't answer.""" 

158 

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

160 first = str(artists[0] if artists else song.get('artist') or '').strip() 

161 title = str(song.get('name') or '').strip() 

162 if not first or not title or not song.get('duration'): 

163 return '' 

164 from . import deezer # noqa: PLC0415 # see _same_song 

165 

166 try: 

167 rows = ( 

168 deezer._get_json( # noqa: SLF001 

169 _SEARCH_URL, q=f'{first} {title}', limit=10 

170 ).get('data') 

171 or [] 

172 ) 

173 except ValueError: 

174 return '' 

175 matches = [r for r in rows if isinstance(r, dict) and _same_song(song, r)] 

176 codes = {_track_isrc(r.get('id')) for r in matches[:3]} 

177 codes.discard('') 

178 return codes.pop() if len(codes) == 1 else '' 

179 

180 

181def for_song(song: dict[str, Any]) -> str: 

182 """The ISRC to write into *song*'s file (see the module notes), or 

183 ``''``.""" 

184 

185 known = normalize(song.get('isrc')) 

186 if known: 

187 return known 

188 song_id = str(song.get('song_id') or '') 

189 if song_id.startswith('deezer-') and song_id[len('deezer-') :].isdigit(): 

190 found = _track_isrc(song_id[len('deezer-') :]) 

191 if found: 

192 return found 

193 return find_on_deezer(song) 

194 

195 

196def lookup(song: dict[str, Any]) -> Optional[str]: 

197 """:func:`for_song` that never raises (a download's side lookup).""" 

198 

199 try: 

200 return for_song(song) or None 

201 except Exception: 

202 logger.opt(exception=True).debug( 

203 'ISRC lookup failed for {}', song.get('name') 

204 ) 

205 return None